test.cc 1024 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461
  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. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. #ifdef CPPHTTPLIB_SSL_ENABLED
  492. bool match_hostname(const std::string &pattern, const std::string &hostname);
  493. #endif
  494. } // namespace detail
  495. } // namespace httplib
  496. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  497. struct {
  498. const char *line;
  499. const char *version;
  500. int status;
  501. const char *reason;
  502. } cases[] = {
  503. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  504. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  505. // The reason phrase may be empty, or left out along with its space.
  506. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  507. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  508. };
  509. for (const auto &c : cases) {
  510. std::string version;
  511. int status = 0;
  512. std::string reason = "unset";
  513. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  514. << c.line;
  515. EXPECT_EQ(c.version, version);
  516. EXPECT_EQ(c.status, status);
  517. EXPECT_EQ(c.reason, reason);
  518. }
  519. }
  520. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  521. const char *lines[] = {
  522. "HTTP/2 200 OK\r\n",
  523. "HTTP/1.2 200 OK\r\n",
  524. "HTTP/1.1 20 OK\r\n",
  525. "HTTP/1.1 2000 OK\r\n",
  526. "HTTP/1.1 2x0 OK\r\n",
  527. "HTTP/1.1 200 OK\r\n",
  528. "HTTP/1.1 200OK\r\n",
  529. "HTTP/1.1 200 O\rK\r\n",
  530. "HTTP/1.1 200 OK",
  531. "HTTP/1.1 200 OK\r\nX",
  532. "",
  533. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  534. "HTTP/1.1 200 OK\n",
  535. #endif
  536. };
  537. for (auto line : lines) {
  538. std::string version;
  539. int status = 0;
  540. std::string reason;
  541. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  542. << line;
  543. }
  544. }
  545. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  546. // Long enough to overflow the stack when matched with std::regex.
  547. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  548. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  549. std::string version;
  550. int status = 0;
  551. std::string reason;
  552. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  553. EXPECT_EQ(200, status);
  554. EXPECT_EQ(long_reason, reason);
  555. }
  556. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  557. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  558. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  559. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  560. EXPECT_EQ("", detail::file_extension("noext"));
  561. EXPECT_EQ("", detail::file_extension("a."));
  562. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  563. EXPECT_EQ("", detail::file_extension("a.b-c"));
  564. // Long enough to overflow the stack when matched with std::regex.
  565. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  566. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  567. }
  568. #ifdef CPPHTTPLIB_SSL_ENABLED
  569. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  570. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  573. // A wildcard needs two labels after it, in the leftmost label only
  574. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  575. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  576. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  577. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  578. EXPECT_FALSE(
  579. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  580. // No name may have an empty label
  581. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  582. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  583. }
  584. #endif
  585. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  586. detail::case_ignore::hash hash;
  587. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  588. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  589. // Long enough to overflow the stack if hashed one call per character.
  590. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  591. }
  592. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  593. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  594. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  595. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  596. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  597. // Same 26-bit hash as html, svg and js.
  598. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  601. }
  602. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  603. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  604. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  605. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  606. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  607. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  608. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  609. // Same 26-bit hash as application/json.
  610. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  611. }
  612. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  613. Request req;
  614. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  615. EXPECT_TRUE(req.is_multipart_form_data());
  616. std::string boundary;
  617. EXPECT_TRUE(detail::parse_multipart_boundary(
  618. req.get_header_value("Content-Type"), boundary));
  619. EXPECT_EQ("x", boundary);
  620. }
  621. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  622. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  623. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  624. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  625. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  626. // Same 26-bit hash as REMOTE_ADDR.
  627. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  628. }
  629. // Forward declaration: in split builds split.py strips `inline` and moves the
  630. // definition into httplib.cc, so detail::base64_encode is not visible from the
  631. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  632. // in both header-only and split builds.
  633. namespace httplib {
  634. namespace detail {
  635. std::string base64_encode(const std::string &in);
  636. } // namespace detail
  637. } // namespace httplib
  638. TEST(Base64EncodeTest, KnownAnswers) {
  639. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  640. // where the accumulator's top bit is already set before the next shift.
  641. EXPECT_EQ("", detail::base64_encode(""));
  642. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  643. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  644. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  645. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  646. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  647. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  648. // High bytes keep the top bit set across several rounds.
  649. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  650. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  651. }
  652. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  653. string unescapedCharacters = "-_.!~*'()";
  654. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  655. }
  656. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  657. string reservedCharacters = ";,/?:@&=+$";
  658. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  659. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  660. }
  661. TEST(ClientQueryOrder, PreserveOrder) {
  662. // This test reproduces Issue #2259: client may reorder query parameters
  663. // when sending a GET request. The expected behavior is that the client
  664. // preserves the original query string order when the caller supplied it
  665. // as part of the path.
  666. Server svr;
  667. svr.Get("/", [&](const Request &req, Response &res) {
  668. // Echo back the raw target so the test can assert ordering
  669. res.set_content(req.target, "text/plain");
  670. });
  671. std::thread t{[&] { svr.listen(HOST, PORT); }};
  672. auto se = detail::scope_exit([&] {
  673. svr.stop();
  674. t.join();
  675. ASSERT_FALSE(svr.is_running());
  676. });
  677. svr.wait_until_ready();
  678. Client cli(HOST, PORT);
  679. ASSERT_TRUE(cli.is_valid());
  680. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  681. auto res = cli.Get(original);
  682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  683. // Expect the echoed target to exactly match the original path (order
  684. // preserved)
  685. EXPECT_EQ(res->body, original);
  686. }
  687. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  688. string chineseCharacters = U8("中国語");
  689. string russianCharacters = U8("дом");
  690. string brazilianCharacters = U8("óculos");
  691. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  692. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  693. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  694. "%D0%B4%D0%BE%D0%BC");
  695. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  696. }
  697. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  698. string unescapedCharacters = "-_.!~*'()";
  699. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  700. }
  701. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  702. string reservedCharacters = ";,/?:@&=+$";
  703. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  704. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  705. }
  706. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  707. string chineseCharacters = U8("中国語");
  708. string russianCharacters = U8("дом");
  709. string brazilianCharacters = U8("óculos");
  710. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  711. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  712. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  713. "%D0%B4%D0%BE%D0%BC");
  714. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  715. }
  716. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  717. // Issue #2082 use case: encoding path component with ampersand
  718. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  719. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  720. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  721. }
  722. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  723. string unescapedCharacters = "-_.!~*'()";
  724. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  725. }
  726. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  727. string reservedCharacters = ";,/?:@&=+$#";
  728. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  729. }
  730. TEST(EncodeUriTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  737. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  738. }
  739. TEST(EncodeUriTest, TestCompleteUri) {
  740. string uri =
  741. "https://example.com/path/to/resource?query=value&param=test#fragment";
  742. EXPECT_EQ(
  743. httplib::encode_uri(uri),
  744. "https://example.com/path/to/resource?query=value&param=test#fragment");
  745. }
  746. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  747. string uri =
  748. "https://example.com/path with spaces/file name.html?q=hello world";
  749. EXPECT_EQ(httplib::encode_uri(uri),
  750. "https://example.com/path%20with%20spaces/"
  751. "file%20name.html?q=hello%20world");
  752. }
  753. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  754. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  755. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  756. }
  757. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  758. string unescapedCharacters = "-_.!~*'()";
  759. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  760. }
  761. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  762. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  763. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  764. string encodedBrazilian = "%C3%B3culos";
  765. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  767. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  768. }
  769. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  770. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  772. "Piri Tommy Villiers - on & on");
  773. }
  774. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  775. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  776. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  777. }
  778. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  779. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  780. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  781. }
  782. TEST(DecodeUriTest, TestUTF8Characters) {
  783. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  784. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  785. string encodedBrazilian = "%C3%B3culos";
  786. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  787. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  788. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  789. }
  790. TEST(DecodeUriTest, TestCompleteUri) {
  791. string encodedUri = "https://example.com/path%20with%20spaces/"
  792. "file%20name.html?q=hello%20world";
  793. EXPECT_EQ(
  794. httplib::decode_uri(encodedUri),
  795. "https://example.com/path with spaces/file name.html?q=hello world");
  796. }
  797. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  798. string original =
  799. "https://example.com/path with spaces/file name.html?q=hello world";
  800. string encoded = httplib::encode_uri(original);
  801. string decoded = httplib::decode_uri(encoded);
  802. EXPECT_EQ(decoded, original);
  803. }
  804. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  805. // decode_uri is the inverse of encode_uri: an escaped reserved character
  806. // stays encoded so it is not promoted into a real delimiter, while
  807. // non-reserved escapes still decode (like JS decodeURI).
  808. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  809. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  810. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  811. "%3F%3A%40%26%3D%2B%24%2C%3B");
  812. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  813. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  814. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  815. "http://example.com/a%2Fb");
  816. // decode_uri_component still decodes the reserved character.
  817. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  818. }
  819. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  820. string original = "Piri Tommy Villiers - on & on";
  821. string encoded = httplib::encode_uri_component(original);
  822. string decoded = httplib::decode_uri_component(encoded);
  823. EXPECT_EQ(decoded, original);
  824. }
  825. TEST(TrimTests, TrimStringTests) {
  826. EXPECT_EQ("abc", detail::trim_copy("abc"));
  827. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  828. EXPECT_TRUE(detail::trim_copy("").empty());
  829. }
  830. TEST(AsciiTest, LocaleIndependentClassification) {
  831. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  832. // which consult the global C locale: std::isalnum(0xC5) can return true
  833. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  834. // helpers must classify every byte by the ASCII grammar alone.
  835. for (int i = 0; i < 256; i++) {
  836. auto c = static_cast<char>(i);
  837. auto is_digit = i >= '0' && i <= '9';
  838. auto is_upper = i >= 'A' && i <= 'Z';
  839. auto is_lower = i >= 'a' && i <= 'z';
  840. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  841. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  842. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  843. << "byte " << i;
  844. }
  845. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  846. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  847. // Non-ASCII bytes must be percent-encoded, never passed through as
  848. // alphanumeric.
  849. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  850. }
  851. TEST(FromCharsTest, Double) {
  852. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  853. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  854. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  855. auto parse = [](const std::string &s, double &v) {
  856. return detail::from_chars(s.data(), s.data() + s.size(), v);
  857. };
  858. double v = -1.0;
  859. // Representative quality values.
  860. EXPECT_EQ(parse("0", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.0);
  862. EXPECT_EQ(parse("1", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 1.0);
  864. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.8);
  866. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.001);
  868. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. // A missing integer or fractional part is tolerated.
  871. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  872. EXPECT_DOUBLE_EQ(v, 0.5);
  873. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 5.0);
  875. // Values outside [0, 1] still parse; the caller range-checks them.
  876. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  877. EXPECT_DOUBLE_EQ(v, 123.456);
  878. // Stops at the first byte that is not part of the number and reports where.
  879. std::string trailing = "0.9, text/html";
  880. auto r = parse(trailing, v);
  881. EXPECT_EQ(r.ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 0.9);
  883. EXPECT_EQ(*r.ptr, ',');
  884. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  885. // outright, and an 'e'/'E' simply ends the number.
  886. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  888. std::string exp_input = "1.5e3";
  889. r = parse(exp_input, v);
  890. EXPECT_EQ(r.ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 1.5);
  892. EXPECT_EQ(*r.ptr, 'e');
  893. // Invalid inputs.
  894. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  898. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  899. // Pathological but well-formed inputs must stay bounded (no overflow, no
  900. // out-of-bounds table access) and stay within [0, 1] for the caller.
  901. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  902. std::errc{});
  903. EXPECT_DOUBLE_EQ(v, 0.0);
  904. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  905. std::errc{});
  906. EXPECT_GE(v, 0.0);
  907. EXPECT_LE(v, 1.0);
  908. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  909. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  910. }
  911. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  912. // Simple case without quality values
  913. std::vector<std::string> result1;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html,application/json,text/plain", result1));
  916. EXPECT_EQ(result1.size(), 3U);
  917. EXPECT_EQ(result1[0], "text/html");
  918. EXPECT_EQ(result1[1], "application/json");
  919. EXPECT_EQ(result1[2], "text/plain");
  920. // With quality values
  921. std::vector<std::string> result2;
  922. EXPECT_TRUE(detail::parse_accept_header(
  923. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  924. EXPECT_EQ(result2.size(), 3U);
  925. EXPECT_EQ(result2[0], "application/json"); // highest q value
  926. EXPECT_EQ(result2[1], "text/html");
  927. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  928. }
  929. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  930. // Mixed with and without quality values
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(
  933. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  934. EXPECT_EQ(result.size(), 3U);
  935. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  936. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  937. EXPECT_EQ(result[2], "application/json"); // q=0.5
  938. }
  939. TEST(ParseAcceptHeaderTest, EdgeCases) {
  940. // Empty header
  941. std::vector<std::string> empty_result;
  942. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  943. EXPECT_TRUE(empty_result.empty());
  944. // Single type
  945. std::vector<std::string> single_result;
  946. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  947. EXPECT_EQ(single_result.size(), 1U);
  948. EXPECT_EQ(single_result[0], "application/json");
  949. // Wildcard types
  950. std::vector<std::string> wildcard_result;
  951. EXPECT_TRUE(detail::parse_accept_header(
  952. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  953. EXPECT_EQ(wildcard_result.size(), 3U);
  954. EXPECT_EQ(wildcard_result[0], "application/json");
  955. EXPECT_EQ(wildcard_result[1], "text/*");
  956. EXPECT_EQ(wildcard_result[2], "*/*");
  957. }
  958. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  959. // Common browser Accept header
  960. std::vector<std::string> browser_result;
  961. EXPECT_TRUE(
  962. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  963. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  964. browser_result));
  965. EXPECT_EQ(browser_result.size(), 6U);
  966. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  970. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  971. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  972. // API client header
  973. std::vector<std::string> api_result;
  974. EXPECT_TRUE(detail::parse_accept_header(
  975. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  976. api_result));
  977. EXPECT_EQ(api_result.size(), 3U);
  978. EXPECT_EQ(api_result[0], "application/json");
  979. EXPECT_EQ(api_result[1], "application/xml");
  980. EXPECT_EQ(api_result[2], "text/plain");
  981. }
  982. TEST(ParseAcceptHeaderTest, SpecialCases) {
  983. // Quality value with 3 decimal places
  984. std::vector<std::string> decimal_result;
  985. EXPECT_TRUE(detail::parse_accept_header(
  986. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  987. EXPECT_EQ(decimal_result.size(), 2U);
  988. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  989. EXPECT_EQ(decimal_result[1], "text/html");
  990. // Zero quality (should still be included but with lowest priority)
  991. std::vector<std::string> zero_q_result;
  992. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  993. zero_q_result));
  994. EXPECT_EQ(zero_q_result.size(), 2U);
  995. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  996. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  997. // No spaces around commas
  998. std::vector<std::string> no_space_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1001. no_space_result));
  1002. EXPECT_EQ(no_space_result.size(), 3U);
  1003. EXPECT_EQ(no_space_result[0], "text/html");
  1004. EXPECT_EQ(no_space_result[1], "application/json");
  1005. EXPECT_EQ(no_space_result[2], "text/plain");
  1006. }
  1007. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1008. // Quality values always use '.' as the decimal separator, so parsing must
  1009. // not depend on the process locale. An embedding application may have
  1010. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1011. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1012. std::string saved = cur ? cur : "C";
  1013. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1014. "fr_FR.UTF-8"};
  1015. bool switched = false;
  1016. for (const auto loc : comma_locales) {
  1017. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1018. std::localeconv()->decimal_point[0] == ',') {
  1019. switched = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!switched) {
  1024. std::setlocale(LC_NUMERIC, saved.c_str());
  1025. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1026. }
  1027. // The higher-weighted type appears later in the list, so a correct parse
  1028. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1029. // sensitive parse reads both weights as 0 and leaves the original order.
  1030. std::vector<std::string> result;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "application/json;q=0.1,text/html;q=0.9", result));
  1033. ASSERT_EQ(result.size(), 2U);
  1034. EXPECT_EQ(result[0], "text/html");
  1035. EXPECT_EQ(result[1], "application/json");
  1036. std::setlocale(LC_NUMERIC, saved.c_str());
  1037. }
  1038. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1039. std::vector<std::string> result;
  1040. // Invalid quality value (> 1.0)
  1041. EXPECT_FALSE(
  1042. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1043. // Invalid quality value (< 0.0)
  1044. EXPECT_FALSE(
  1045. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1046. // Invalid quality value (not a number)
  1047. EXPECT_FALSE(detail::parse_accept_header(
  1048. "text/html;q=invalid,application/json", result));
  1049. // A valid numeric prefix does not make the entire quality value valid.
  1050. EXPECT_FALSE(detail::parse_accept_header(
  1051. "text/html;q=0.5junk,application/json", result));
  1052. // Empty quality value
  1053. EXPECT_FALSE(
  1054. detail::parse_accept_header("text/html;q=,application/json", result));
  1055. // Invalid media type format (no slash and not wildcard)
  1056. EXPECT_FALSE(
  1057. detail::parse_accept_header("invalidtype,application/json", result));
  1058. // Valid cases should still work
  1059. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1060. EXPECT_EQ(result.size(), 1U);
  1061. EXPECT_EQ(result[0], "*/*");
  1062. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1063. EXPECT_EQ(result.size(), 1U);
  1064. EXPECT_EQ(result[0], "*");
  1065. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "text/*");
  1068. }
  1069. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1070. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1071. // and must not be answered with 400 Bad Request.
  1072. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1073. struct {
  1074. const char *value;
  1075. std::vector<std::string> expected;
  1076. } cases[] = {
  1077. {",application/json", {"application/json"}},
  1078. {"text/html,", {"text/html"}},
  1079. {"text/html,,*/*", {"text/html", "*/*"}},
  1080. // An empty element may be spelled with whitespace in it
  1081. {"text/html, , application/json", {"text/html", "application/json"}},
  1082. // Nothing but empty elements is an empty list, which means the same
  1083. // thing as no Accept header at all
  1084. {",,,", {}},
  1085. // Quality values still apply across ignored empty elements
  1086. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1087. };
  1088. for (const auto &c : cases) {
  1089. std::vector<std::string> result;
  1090. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1091. << "value: " << c.value;
  1092. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1093. }
  1094. // An invalid entry is still rejected when empty elements surround it
  1095. std::vector<std::string> result;
  1096. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1097. }
  1098. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1099. // or ';' inside one does not end the list element or the parameter. Section
  1100. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1101. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1102. struct {
  1103. const char *value;
  1104. std::vector<std::string> expected;
  1105. } cases[] = {
  1106. {"text/html;profile=\"a,b\",application/json",
  1107. {"text/html", "application/json"}},
  1108. // A "q=" inside a quoted value is not the weight
  1109. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1110. {"text/html", "application/json"}},
  1111. // The weight after a quoted value still applies
  1112. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1113. {"application/json", "text/html"}},
  1114. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1115. {"application/json", "text/html"}},
  1116. {"text/html;profile=\"a\\\"b\",application/json",
  1117. {"text/html", "application/json"}},
  1118. // An escaped backslash does not escape the '"' after it
  1119. {"text/html;profile=\"a\\\\\",application/json",
  1120. {"text/html", "application/json"}},
  1121. };
  1122. for (const auto &c : cases) {
  1123. std::vector<std::string> result;
  1124. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1125. << "value: " << c.value;
  1126. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1127. }
  1128. }
  1129. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1130. Server svr;
  1131. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1132. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1133. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1134. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1135. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1136. res.set_content("ok", "text/plain");
  1137. });
  1138. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1139. EXPECT_TRUE(false);
  1140. res.set_content("bad request", "text/plain");
  1141. });
  1142. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1143. auto se = detail::scope_exit([&] {
  1144. svr.stop();
  1145. listen_thread.join();
  1146. ASSERT_FALSE(svr.is_running());
  1147. });
  1148. svr.wait_until_ready();
  1149. Client cli("localhost", PORT);
  1150. {
  1151. auto res = cli.Get(
  1152. "/accept_ok",
  1153. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. auto res = cli.Get("/accept_bad_request",
  1159. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1162. }
  1163. }
  1164. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1165. Server svr;
  1166. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1167. res.set_content("ok", "text/plain");
  1168. });
  1169. std::atomic<int> start_count{0};
  1170. std::atomic<bool> running_when_called{false};
  1171. svr.set_start_handler([&]() {
  1172. running_when_called = svr.is_running();
  1173. start_count++;
  1174. });
  1175. auto port = svr.bind_to_any_port(HOST);
  1176. std::thread t([&]() { svr.listen_after_bind(); });
  1177. auto se = detail::scope_exit([&] {
  1178. svr.stop();
  1179. t.join();
  1180. ASSERT_FALSE(svr.is_running());
  1181. });
  1182. svr.wait_until_ready();
  1183. // A successful request proves the accept loop is running, which the start
  1184. // handler precedes; so by now the handler must have run exactly once.
  1185. Client cli(HOST, port);
  1186. cli.set_connection_timeout(std::chrono::seconds(5));
  1187. auto res = cli.Get("/");
  1188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1189. EXPECT_EQ(StatusCode::OK_200, res->status);
  1190. EXPECT_EQ(1, start_count.load());
  1191. EXPECT_TRUE(running_when_called.load());
  1192. }
  1193. TEST(DivideTest, DivideStringTests) {
  1194. auto divide = [](const std::string &str, char d) {
  1195. std::string lhs;
  1196. std::string rhs;
  1197. detail::divide(str, d,
  1198. [&](const char *lhs_data, std::size_t lhs_size,
  1199. const char *rhs_data, std::size_t rhs_size) {
  1200. lhs.assign(lhs_data, lhs_size);
  1201. rhs.assign(rhs_data, rhs_size);
  1202. });
  1203. return std::make_pair(std::move(lhs), std::move(rhs));
  1204. };
  1205. {
  1206. const auto res = divide("", '=');
  1207. EXPECT_EQ(res.first, "");
  1208. EXPECT_EQ(res.second, "");
  1209. }
  1210. {
  1211. const auto res = divide("=", '=');
  1212. EXPECT_EQ(res.first, "");
  1213. EXPECT_EQ(res.second, "");
  1214. }
  1215. {
  1216. const auto res = divide(" ", '=');
  1217. EXPECT_EQ(res.first, " ");
  1218. EXPECT_EQ(res.second, "");
  1219. }
  1220. {
  1221. const auto res = divide("a", '=');
  1222. EXPECT_EQ(res.first, "a");
  1223. EXPECT_EQ(res.second, "");
  1224. }
  1225. {
  1226. const auto res = divide("a=", '=');
  1227. EXPECT_EQ(res.first, "a");
  1228. EXPECT_EQ(res.second, "");
  1229. }
  1230. {
  1231. const auto res = divide("=b", '=');
  1232. EXPECT_EQ(res.first, "");
  1233. EXPECT_EQ(res.second, "b");
  1234. }
  1235. {
  1236. const auto res = divide("a=b", '=');
  1237. EXPECT_EQ(res.first, "a");
  1238. EXPECT_EQ(res.second, "b");
  1239. }
  1240. {
  1241. const auto res = divide("a=b=", '=');
  1242. EXPECT_EQ(res.first, "a");
  1243. EXPECT_EQ(res.second, "b=");
  1244. }
  1245. {
  1246. const auto res = divide("a=b=c", '=');
  1247. EXPECT_EQ(res.first, "a");
  1248. EXPECT_EQ(res.second, "b=c");
  1249. }
  1250. }
  1251. TEST(SplitTest, ParseQueryString) {
  1252. string s = "key1=val1&key2=val2&key3=val3";
  1253. Params dic;
  1254. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1255. [&](const char *b, const char *e) {
  1256. string key, val;
  1257. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1258. if (key.empty()) {
  1259. key.assign(b2, e2);
  1260. } else {
  1261. val.assign(b2, e2);
  1262. }
  1263. });
  1264. dic.emplace(key, val);
  1265. });
  1266. EXPECT_EQ("val1", dic.find("key1")->second);
  1267. EXPECT_EQ("val2", dic.find("key2")->second);
  1268. EXPECT_EQ("val3", dic.find("key3")->second);
  1269. }
  1270. TEST(SplitTest, ParseInvalidQueryTests) {
  1271. {
  1272. string s = " ";
  1273. Params dict;
  1274. detail::parse_query_text(s, dict);
  1275. EXPECT_TRUE(dict.empty());
  1276. }
  1277. {
  1278. string s = " = =";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. }
  1284. TEST(ParseQueryTest, ParseQueryString) {
  1285. {
  1286. std::string s = "key1=val1&key2=val2&key3=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("val1", dic.find("key1")->second);
  1290. EXPECT_EQ("val2", dic.find("key2")->second);
  1291. EXPECT_EQ("val3", dic.find("key3")->second);
  1292. }
  1293. {
  1294. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1295. Params dic;
  1296. detail::parse_query_text(s, dic);
  1297. EXPECT_EQ("", dic.find("key1")->second);
  1298. EXPECT_EQ("val1", dic.find("key2")->second);
  1299. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1300. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1301. }
  1302. }
  1303. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1304. Params dic;
  1305. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1306. dic.emplace("key1", "val1");
  1307. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1308. dic.emplace("key2", "val2");
  1309. dic.emplace("key3", "val3");
  1310. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1311. }
  1312. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1313. Params params;
  1314. params.emplace("a", "1");
  1315. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1316. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1317. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1318. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1319. // Long enough to overflow the stack when matched with std::regex.
  1320. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1321. EXPECT_EQ("/p?" + long_query + "&a=1",
  1322. append_query_params("/p?" + long_query, params));
  1323. }
  1324. // Joins every entry of a Headers or Params into "key=value " so a whole
  1325. // traversal can be compared in one assertion. Both are instantiations of the
  1326. // same insertion-ordered container, so one helper serves both.
  1327. template <typename Map> static std::string entries_to_string(const Map &m) {
  1328. std::string s;
  1329. for (const auto &entry : m) {
  1330. s += entry.first + "=" + entry.second + " ";
  1331. }
  1332. return s;
  1333. }
  1334. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1335. // Params used to be a std::multimap, which sorted by name and handed the
  1336. // caller's query back alphabetised. A client signing its query string could
  1337. // not reproduce the order it asked for.
  1338. Params dic;
  1339. dic.emplace("zulu", "1");
  1340. dic.emplace("alpha", "2");
  1341. dic.emplace("mike", "3");
  1342. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1343. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1344. }
  1345. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1346. Params dic;
  1347. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1349. }
  1350. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1351. Request req;
  1352. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1353. req.params);
  1354. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag"));
  1356. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1357. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1358. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1359. EXPECT_EQ("", req.get_param_value("tag", 3));
  1360. }
  1361. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1362. // Params shares its container with Headers, which matches field names
  1363. // case-insensitively. Parameter names must not pick that up.
  1364. Params dic;
  1365. dic.emplace("Key", "upper");
  1366. dic.emplace("key", "lower");
  1367. EXPECT_EQ(2U, dic.size());
  1368. EXPECT_EQ(1U, dic.count("Key"));
  1369. EXPECT_EQ(1U, dic.count("key"));
  1370. EXPECT_EQ("upper", dic.find("Key")->second);
  1371. EXPECT_EQ("lower", dic.find("key")->second);
  1372. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1373. }
  1374. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1375. Server svr;
  1376. std::string order;
  1377. svr.Get("/order", [&](const Request &req, Response &res) {
  1378. order = entries_to_string(req.params);
  1379. res.set_content("ok", "text/plain");
  1380. });
  1381. auto port = svr.bind_to_any_port(HOST);
  1382. thread t = thread([&] { svr.listen_after_bind(); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. t.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, port);
  1390. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1391. ASSERT_TRUE(res);
  1392. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1393. }
  1394. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1395. Server svr;
  1396. std::string field_order, file_order;
  1397. svr.Post("/order", [&](const Request &req, Response &res) {
  1398. for (const auto &field : req.form.fields) {
  1399. field_order += field.first + "=" + field.second.content + " ";
  1400. }
  1401. for (const auto &file : req.form.files) {
  1402. file_order += file.first + "=" + file.second.filename + " ";
  1403. }
  1404. res.set_content("ok", "text/plain");
  1405. });
  1406. auto port = svr.bind_to_any_port(HOST);
  1407. thread t = thread([&] { svr.listen_after_bind(); });
  1408. auto se = detail::scope_exit([&] {
  1409. svr.stop();
  1410. t.join();
  1411. ASSERT_FALSE(svr.is_running());
  1412. });
  1413. svr.wait_until_ready();
  1414. UploadFormDataItems items = {
  1415. {"zulu", "1", "", ""},
  1416. {"alpha", "2", "", ""},
  1417. {"mike", "3", "", ""},
  1418. {"zebra", "z", "z.txt", "text/plain"},
  1419. {"apple", "a", "a.txt", "text/plain"},
  1420. };
  1421. Client cli(HOST, port);
  1422. auto res = cli.Post("/order", items);
  1423. ASSERT_TRUE(res);
  1424. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1425. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1426. }
  1427. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1428. Server svr;
  1429. std::vector<std::string> values;
  1430. std::string first, second, out_of_range, order;
  1431. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1432. values = req.form.get_fields("tag");
  1433. first = req.form.get_field("tag", 0);
  1434. second = req.form.get_field("tag", 1);
  1435. out_of_range = req.form.get_field("tag", 2);
  1436. for (const auto &field : req.form.fields) {
  1437. order += field.first + "=" + field.second.content + " ";
  1438. }
  1439. res.set_content("ok", "text/plain");
  1440. });
  1441. auto port = svr.bind_to_any_port(HOST);
  1442. thread t = thread([&] { svr.listen_after_bind(); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. t.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1450. // not adjacent in the container.
  1451. UploadFormDataItems items = {
  1452. {"tag", "first", "", ""},
  1453. {"other", "x", "", ""},
  1454. {"tag", "second", "", ""},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/repeated", items);
  1458. ASSERT_TRUE(res);
  1459. ASSERT_EQ(2U, values.size());
  1460. EXPECT_EQ("first", values[0]);
  1461. EXPECT_EQ("second", values[1]);
  1462. EXPECT_EQ("first", first);
  1463. EXPECT_EQ("second", second);
  1464. // std::multimap already kept entries sharing a name in insertion order, so
  1465. // everything above passes without this change too. The whole traversal is
  1466. // what tells the two apart: sorting by name would hoist "other" to the front
  1467. // and the two "tag" parts would end up adjacent.
  1468. EXPECT_EQ("tag=first other=x tag=second ", order);
  1469. // Advancing past the last entry of a name used to run off the container;
  1470. // the container's saturating increment makes it return the default instead.
  1471. EXPECT_EQ("", out_of_range);
  1472. }
  1473. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1474. Server svr;
  1475. std::string file_names;
  1476. svr.Post("/upload", [&](const Request &req, Response &res) {
  1477. for (const auto &file : req.form.files) {
  1478. file_names += file.first + "|" + file.second.filename + " ";
  1479. }
  1480. res.set_content("ok", "text/plain");
  1481. });
  1482. auto port = svr.bind_to_any_port(HOST);
  1483. thread t = thread([&] { svr.listen_after_bind(); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. t.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. // A trailing backslash would otherwise escape the closing quote.
  1491. UploadFormDataItems items = {
  1492. {"dir\\", "x", "a.txt", "text/plain"},
  1493. {"b", "y", "a\\\\b.txt", "text/plain"},
  1494. };
  1495. Client cli(HOST, port);
  1496. auto res = cli.Post("/upload", items);
  1497. ASSERT_TRUE(res);
  1498. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1499. }
  1500. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1501. // Server::read_content() keeps a FormFields::iterator alive across the
  1502. // content callbacks that fill the part it points at. The container is
  1503. // vector-backed, so a later emplace can reallocate and invalidate an older
  1504. // iterator; 64 parts grow the vector through seven reallocations, which
  1505. // checks that every part's content still lands in its own entry.
  1506. const size_t part_count = 64;
  1507. // One formula for both the parts sent and the values expected back, so the
  1508. // two cannot drift apart.
  1509. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1510. auto content_of = [](size_t i) {
  1511. return std::string(64, static_cast<char>('a' + (i % 26)));
  1512. };
  1513. Server svr;
  1514. std::vector<std::pair<std::string, std::string>> received;
  1515. svr.Post("/many", [&](const Request &req, Response &res) {
  1516. for (const auto &field : req.form.fields) {
  1517. received.emplace_back(field.first, field.second.content);
  1518. }
  1519. res.set_content("ok", "text/plain");
  1520. });
  1521. auto port = svr.bind_to_any_port(HOST);
  1522. thread t = thread([&] { svr.listen_after_bind(); });
  1523. auto se = detail::scope_exit([&] {
  1524. svr.stop();
  1525. t.join();
  1526. ASSERT_FALSE(svr.is_running());
  1527. });
  1528. svr.wait_until_ready();
  1529. UploadFormDataItems items;
  1530. for (size_t i = 0; i < part_count; i++) {
  1531. items.push_back({name_of(i), content_of(i), "", ""});
  1532. }
  1533. Client cli(HOST, port);
  1534. auto res = cli.Post("/many", items);
  1535. ASSERT_TRUE(res);
  1536. ASSERT_EQ(part_count, received.size());
  1537. for (size_t i = 0; i < part_count; i++) {
  1538. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1539. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1540. }
  1541. }
  1542. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1543. string content_type = "multipart/form-data; boundary=something";
  1544. string boundary;
  1545. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(boundary, "something");
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1550. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1551. string boundary;
  1552. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1553. EXPECT_TRUE(ret);
  1554. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1557. string content_type =
  1558. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1559. string boundary;
  1560. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1561. EXPECT_TRUE(ret);
  1562. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1565. string content_type =
  1566. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1567. string boundary;
  1568. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1569. EXPECT_TRUE(ret);
  1570. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1571. }
  1572. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1573. const string boundary(70, 'a');
  1574. string content_type = "multipart/form-data; boundary=" + boundary;
  1575. string parsed;
  1576. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(parsed, boundary);
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1581. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1582. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1583. string parsed;
  1584. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1585. EXPECT_FALSE(ret);
  1586. }
  1587. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1588. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1589. // is 72 characters on the wire and still valid.
  1590. const string boundary(70, 'a');
  1591. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1592. string parsed;
  1593. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1594. EXPECT_EQ(parsed, boundary);
  1595. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1596. parsed.clear();
  1597. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1598. }
  1599. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1600. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1601. // The parameter parser must not treat that '=' as the key/value separator.
  1602. string content_type =
  1603. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1604. "charset=UTF-8";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1608. }
  1609. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1610. // A ';' inside the quoted-string is part of the value, not a parameter
  1611. // separator, so it must not truncate the boundary.
  1612. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1613. string parsed;
  1614. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1615. EXPECT_EQ(parsed, "a;b");
  1616. }
  1617. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(
  1620. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1621. EXPECT_EQ("a\\b", parsed);
  1622. EXPECT_TRUE(detail::parse_multipart_boundary(
  1623. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1624. EXPECT_EQ("a\"b", parsed);
  1625. }
  1626. TEST(ParseDispositionParamsTest, QuotedValues) {
  1627. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1628. // ';' and '=' are ordinary characters inside one.
  1629. struct {
  1630. const char *value;
  1631. std::vector<std::pair<const char *, const char *>> expected;
  1632. } cases[] = {
  1633. {"name=\"file1\"; filename=\"a.txt\"",
  1634. {{"name", "file1"}, {"filename", "a.txt"}}},
  1635. // Whitespace around '=' and ';' is still trimmed
  1636. {"name=\"file2\" ;filename = \"a.html\"",
  1637. {{"name", "file2"}, {"filename", "a.html"}}},
  1638. // '=' inside the value used to leave only the text after the last one
  1639. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1640. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1641. {"name=\"x=y\"", {{"name", "x=y"}}},
  1642. // ';' inside the value used to truncate the pair and leave a bogus one
  1643. {"name=\"file3\"; filename=\"a;b.txt\"",
  1644. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1645. // An unquoted value keeps working, and so does filename*
  1646. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1647. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1648. // A parameter with no key is dropped rather than turned into one whose
  1649. // key is the value
  1650. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1651. // An escaped quote does not end the value
  1652. {"name=\"a\\\"; filename=evil.php\"",
  1653. {{"name", "a\"; filename=evil.php"}}},
  1654. // Other backslashes, as in a Windows path, are kept
  1655. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1656. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1657. };
  1658. for (const auto &c : cases) {
  1659. Params params;
  1660. detail::parse_disposition_params(c.value, params);
  1661. for (const auto &kv : c.expected) {
  1662. auto it = params.find(kv.first);
  1663. ASSERT_NE(it, params.end())
  1664. << "value: " << c.value << ", key: " << kv.first;
  1665. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1666. }
  1667. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1668. }
  1669. }
  1670. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1671. Server svr;
  1672. std::string filename;
  1673. std::string content;
  1674. svr.Post("/upload", [&](const Request &req, Response &) {
  1675. const auto &file = req.form.get_file("file");
  1676. filename = file.filename;
  1677. content = file.content;
  1678. });
  1679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1680. auto se = detail::scope_exit([&] {
  1681. svr.stop();
  1682. thread.join();
  1683. ASSERT_FALSE(svr.is_running());
  1684. });
  1685. svr.wait_until_ready();
  1686. std::string body = "--B\r\n"
  1687. "Content-Disposition: form-data; name=\"file\"; "
  1688. "filename=\"a.txt\"\r\n"
  1689. "Content-Type: text/plain\r\n"
  1690. "\r\n"
  1691. "hello\r\n"
  1692. "--B--\r\n";
  1693. Client cli(HOST, PORT);
  1694. auto res = cli.Post(
  1695. "/upload",
  1696. [&](size_t offset, DataSink &sink) {
  1697. if (offset < body.size()) {
  1698. sink.write(&body[offset], 1);
  1699. } else {
  1700. sink.done();
  1701. }
  1702. return true;
  1703. },
  1704. "multipart/form-data; boundary=B");
  1705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1706. EXPECT_EQ(StatusCode::OK_200, res->status);
  1707. EXPECT_EQ("a.txt", filename);
  1708. EXPECT_EQ("hello", content);
  1709. }
  1710. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1711. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1712. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1713. Server svr;
  1714. std::string field_value, file_name, file_filename;
  1715. bool has_field = false, has_file = false;
  1716. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1717. has_field = req.form.has_field("x=y");
  1718. field_value = req.form.get_field("x=y");
  1719. has_file = req.form.has_file("file1");
  1720. const auto &file = req.form.get_file("file1");
  1721. file_name = file.name;
  1722. file_filename = file.filename;
  1723. res.set_content("ok", "text/plain");
  1724. });
  1725. auto port = svr.bind_to_any_port(HOST);
  1726. thread t = thread([&] { svr.listen_after_bind(); });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. t.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. UploadFormDataItems items = {
  1734. {"x=y", "field-value", "", ""},
  1735. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1736. };
  1737. Client cli(HOST, port);
  1738. auto res = cli.Post("/quoted", items);
  1739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1740. ASSERT_EQ(StatusCode::OK_200, res->status);
  1741. EXPECT_TRUE(has_field);
  1742. EXPECT_EQ("field-value", field_value);
  1743. EXPECT_TRUE(has_file);
  1744. EXPECT_EQ("file1", file_name);
  1745. EXPECT_EQ("a;b=report.pdf", file_filename);
  1746. }
  1747. TEST(GetHeaderValueTest, DefaultValue) {
  1748. Headers headers = {{"Dummy", "Dummy"}};
  1749. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1750. EXPECT_STREQ("text/plain", val);
  1751. }
  1752. TEST(GetHeaderValueTest, DefaultValueInt) {
  1753. Headers headers = {{"Dummy", "Dummy"}};
  1754. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1755. EXPECT_EQ(100ull, val);
  1756. }
  1757. TEST(GetHeaderValueTest, RegularValue) {
  1758. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1759. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1760. EXPECT_STREQ("text/html", val);
  1761. }
  1762. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1763. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1764. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1765. EXPECT_STREQ("text/html", val);
  1766. }
  1767. TEST(GetHeaderValueTest, SetContent) {
  1768. Response res;
  1769. res.set_content("html", "text/html");
  1770. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1771. res.set_content("text", "text/plain");
  1772. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1773. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueInt) {
  1776. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1778. EXPECT_EQ(100ull, val);
  1779. }
  1780. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1781. Headers headers = {{"Content-Length", "x"}};
  1782. auto is_invalid_value = false;
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1784. is_invalid_value);
  1785. EXPECT_EQ(0ull, val);
  1786. EXPECT_TRUE(is_invalid_value);
  1787. }
  1788. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1789. // An all-digit value that overflows size_t must be reported as invalid, not
  1790. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1791. // a large length to a small one on 32-bit builds, leaving the framing length
  1792. // wrong while is_invalid_value stayed false.
  1793. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1794. auto is_invalid_value = false;
  1795. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1796. is_invalid_value);
  1797. EXPECT_TRUE(is_invalid_value);
  1798. // A well-formed length is unaffected.
  1799. Headers ok = {{"Content-Length", "1234"}};
  1800. is_invalid_value = false;
  1801. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_EQ(1234ull, val);
  1804. EXPECT_FALSE(is_invalid_value);
  1805. }
  1806. TEST(GetHeaderValueTest, Range) {
  1807. {
  1808. Headers headers = {make_range_header({{1, -1}})};
  1809. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1810. EXPECT_STREQ("bytes=1-", val);
  1811. }
  1812. {
  1813. Headers headers = {make_range_header({{-1, 1}})};
  1814. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1815. EXPECT_STREQ("bytes=-1", val);
  1816. }
  1817. {
  1818. Headers headers = {make_range_header({{1, 10}})};
  1819. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1820. EXPECT_STREQ("bytes=1-10", val);
  1821. }
  1822. {
  1823. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1824. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1825. EXPECT_STREQ("bytes=1-10, 100-", val);
  1826. }
  1827. {
  1828. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1829. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1830. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1831. }
  1832. {
  1833. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1834. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1835. EXPECT_STREQ("bytes=0-0, -1", val);
  1836. }
  1837. }
  1838. TEST(BearerTokenAuthTest, SchemeValidation) {
  1839. // A value shorter than "Bearer " must not throw from the fixed-length
  1840. // substr, and a non-Bearer scheme must not be reported as a token.
  1841. struct {
  1842. const char *value;
  1843. const char *expected;
  1844. } cases[] = {
  1845. {"x", ""},
  1846. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1847. {"Bearer abc123", "abc123"},
  1848. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1849. };
  1850. for (const auto &c : cases) {
  1851. Request req;
  1852. req.set_header("Authorization", c.value);
  1853. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1854. }
  1855. }
  1856. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1857. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1858. // to depend on the standard library (libstdc++ handed back duplicates in
  1859. // reverse insertion order, libc++ in insertion order).
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "gzip");
  1862. req.set_header("Accept-Encoding", "deflate");
  1863. req.set_header("Accept-Encoding", "br");
  1864. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1866. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1867. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1868. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1869. }
  1870. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1871. Request req;
  1872. req.set_header("X-Test", "only");
  1873. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1875. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1876. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1877. }
  1878. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1879. Request req;
  1880. req.set_header("X-First", "1");
  1881. req.set_header("X-Test", "2");
  1882. req.params.emplace("first", "1");
  1883. req.params.emplace("test", "2");
  1884. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1885. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1886. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1887. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1888. // The second one is negative when read as a signed value
  1889. const auto max_id = (std::numeric_limits<size_t>::max)();
  1890. for (auto id : {max_id / 2, max_id}) {
  1891. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1892. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1893. EXPECT_EQ("", req.get_param_value("test", id));
  1894. EXPECT_EQ("", req.form.get_field("test", id));
  1895. EXPECT_EQ("", req.form.get_file("test", id).content);
  1896. }
  1897. }
  1898. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1899. Headers headers;
  1900. headers.emplace("Host", "example.com");
  1901. headers.emplace("Accept-Encoding", "gzip");
  1902. headers.emplace("User-Agent", "test");
  1903. headers.emplace("Accept-Encoding", "deflate");
  1904. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1905. "Accept-Encoding=deflate ",
  1906. entries_to_string(headers));
  1907. }
  1908. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1909. Headers headers = {{"Content-Type", "text/html"},
  1910. {"CONTENT-TYPE", "text/xml"}};
  1911. EXPECT_EQ(2U, headers.count("content-type"));
  1912. auto it = headers.find("content-type");
  1913. ASSERT_TRUE(it != headers.end());
  1914. EXPECT_EQ("text/html", it->second);
  1915. }
  1916. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1917. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1918. // drop only those fields and leave everything positioned between them.
  1919. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1920. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1921. auto rng = headers.equal_range("a");
  1922. headers.erase(rng.first, rng.second);
  1923. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1924. }
  1925. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1926. Headers headers = {
  1927. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1928. EXPECT_EQ(3U, headers.erase("A"));
  1929. EXPECT_EQ(0U, headers.count("A"));
  1930. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1933. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1934. headers.emplace_front("Host", "example.com");
  1935. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1936. entries_to_string(headers));
  1937. }
  1938. TEST(ParseHeaderValueTest, Range) {
  1939. {
  1940. Ranges ranges;
  1941. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1944. }
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1960. EXPECT_FALSE(ret);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1965. EXPECT_TRUE(ret);
  1966. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret =
  1971. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,,,", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1990. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1991. EXPECT_FALSE(
  1992. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1993. EXPECT_TRUE(ranges.empty());
  1994. }
  1995. {
  1996. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1997. // remainder of the representation, so it stays accepted.
  1998. Ranges ranges;
  1999. auto ret =
  2000. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2001. EXPECT_TRUE(ret);
  2002. ASSERT_EQ(1u, ranges.size());
  2003. EXPECT_EQ(0, ranges[0].first);
  2004. EXPECT_EQ(-1, ranges[0].second);
  2005. }
  2006. // RFC 9110 14.1: range unit names are case-insensitive.
  2007. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2008. Ranges ranges;
  2009. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2010. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2011. }
  2012. }
  2013. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding", "gzip");
  2016. Response res;
  2017. res.set_header("Content-Type", "text/plain");
  2018. auto ret = detail::encoding_type(req, res);
  2019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2020. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2021. #else
  2022. EXPECT_TRUE(ret == detail::EncodingType::None);
  2023. #endif
  2024. }
  2025. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2033. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2034. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2035. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2036. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2037. #else
  2038. EXPECT_TRUE(ret == detail::EncodingType::None);
  2039. #endif
  2040. }
  2041. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2042. Request req;
  2043. req.set_header("Accept-Encoding",
  2044. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2045. Response res;
  2046. res.set_header("Content-Type", "text/plain");
  2047. auto ret = detail::encoding_type(req, res);
  2048. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2050. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2052. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2053. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2054. #else
  2055. EXPECT_TRUE(ret == detail::EncodingType::None);
  2056. #endif
  2057. }
  2058. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2059. // All supported encodings rejected with q=0 should return None
  2060. Request req;
  2061. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2062. Response res;
  2063. res.set_header("Content-Type", "text/plain");
  2064. auto ret = detail::encoding_type(req, res);
  2065. EXPECT_TRUE(ret == detail::EncodingType::None);
  2066. }
  2067. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2068. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2069. Request req;
  2070. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2071. Response res;
  2072. res.set_header("Content-Type", "text/plain");
  2073. auto ret = detail::encoding_type(req, res);
  2074. EXPECT_TRUE(ret == detail::EncodingType::None);
  2075. }
  2076. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2077. Request req;
  2078. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2079. Response res;
  2080. res.set_header("Content-Type", "text/plain");
  2081. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2082. }
  2083. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2084. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2085. Request req;
  2086. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2087. Response res;
  2088. res.set_header("Content-Type", "text/plain");
  2089. auto ret = detail::encoding_type(req, res);
  2090. EXPECT_TRUE(ret == detail::EncodingType::None);
  2091. }
  2092. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2093. // RFC 7231: Accept-Encoding values are case-insensitive
  2094. Request req;
  2095. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2096. Response res;
  2097. res.set_header("Content-Type", "text/plain");
  2098. auto ret = detail::encoding_type(req, res);
  2099. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2100. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2101. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2102. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2103. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2104. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2105. #else
  2106. EXPECT_TRUE(ret == detail::EncodingType::None);
  2107. #endif
  2108. }
  2109. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2110. // q value should determine priority, not hardcoded order
  2111. Request req;
  2112. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2113. Response res;
  2114. res.set_header("Content-Type", "text/plain");
  2115. auto ret = detail::encoding_type(req, res);
  2116. // gzip has highest q=1.0, so it should be selected even though
  2117. // br and zstd are also supported
  2118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2120. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2121. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2122. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2123. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2124. #else
  2125. EXPECT_TRUE(ret == detail::EncodingType::None);
  2126. #endif
  2127. }
  2128. TEST(BufferStreamTest, read) {
  2129. detail::BufferStream strm1;
  2130. Stream &strm = strm1;
  2131. EXPECT_EQ(5, strm.write("hello"));
  2132. char buf[512];
  2133. EXPECT_EQ(2, strm.read(buf, 2));
  2134. EXPECT_EQ('h', buf[0]);
  2135. EXPECT_EQ('e', buf[1]);
  2136. EXPECT_EQ(2, strm.read(buf, 2));
  2137. EXPECT_EQ('l', buf[0]);
  2138. EXPECT_EQ('l', buf[1]);
  2139. EXPECT_EQ(1, strm.read(buf, 1));
  2140. EXPECT_EQ('o', buf[0]);
  2141. EXPECT_EQ(0, strm.read(buf, 1));
  2142. }
  2143. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2144. auto host = "www.httpwatch.com";
  2145. auto ip = hosted_at(host);
  2146. EXPECT_EQ("23.96.13.243", ip);
  2147. std::vector<std::string> addrs;
  2148. hosted_at(host, addrs);
  2149. EXPECT_EQ(1u, addrs.size());
  2150. }
  2151. #if 0 // It depends on each test environment...
  2152. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2153. auto host = "www.youtube.com";
  2154. std::vector<std::string> addrs;
  2155. hosted_at(host, addrs);
  2156. EXPECT_EQ(20u, addrs.size());
  2157. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2158. EXPECT_TRUE(it != addrs.end());
  2159. }
  2160. #endif
  2161. class ChunkedEncodingTest : public ::testing::Test {
  2162. protected:
  2163. ChunkedEncodingTest()
  2164. : cli_(HOST, PORT)
  2165. #ifdef CPPHTTPLIB_SSL_ENABLED
  2166. ,
  2167. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2168. #endif
  2169. {
  2170. cli_.set_connection_timeout(2);
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. cli_.enable_server_certificate_verification(false);
  2173. #endif
  2174. }
  2175. virtual void SetUp() {
  2176. read_file("./image.jpg", image_data_);
  2177. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2178. res.set_content("Hello World!", "text/plain");
  2179. });
  2180. svr_.Get(
  2181. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2182. res.set_chunked_content_provider(
  2183. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2184. size_t remaining = image_data_.size() - offset;
  2185. if (remaining == 0) {
  2186. sink.done();
  2187. } else {
  2188. constexpr size_t CHUNK_SIZE = 1024;
  2189. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2190. sink.write(&image_data_[offset], send_size);
  2191. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2192. }
  2193. return true;
  2194. });
  2195. });
  2196. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2197. svr_.wait_until_ready();
  2198. }
  2199. virtual void TearDown() {
  2200. svr_.stop();
  2201. if (!request_threads_.empty()) {
  2202. std::this_thread::sleep_for(std::chrono::seconds(1));
  2203. for (auto &t : request_threads_) {
  2204. t.join();
  2205. }
  2206. }
  2207. t_.join();
  2208. }
  2209. #ifdef CPPHTTPLIB_SSL_ENABLED
  2210. SSLClient cli_;
  2211. SSLServer svr_;
  2212. #else
  2213. Client cli_;
  2214. Server svr_;
  2215. #endif
  2216. thread t_;
  2217. std::vector<thread> request_threads_;
  2218. std::string image_data_;
  2219. };
  2220. TEST_F(ChunkedEncodingTest, NormalGet) {
  2221. auto res = cli_.Get("/chunked");
  2222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2223. std::string out;
  2224. read_file("./image.jpg", out);
  2225. EXPECT_EQ(StatusCode::OK_200, res->status);
  2226. EXPECT_EQ(out, res->body);
  2227. }
  2228. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2229. std::string body;
  2230. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2231. body.append(data, data_length);
  2232. return true;
  2233. });
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get(
  2243. "/chunked",
  2244. [&](const Response &response) {
  2245. EXPECT_EQ(StatusCode::OK_200, response.status);
  2246. return true;
  2247. },
  2248. [&](const char *data, size_t data_length) {
  2249. body.append(data, data_length);
  2250. return true;
  2251. });
  2252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2253. std::string out;
  2254. read_file("./image.jpg", out);
  2255. EXPECT_EQ(StatusCode::OK_200, res->status);
  2256. EXPECT_EQ(out, body);
  2257. }
  2258. TEST(RangeTest, FromHTTPBin_Online) {
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/range/32"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(5);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. }
  2275. {
  2276. Headers headers = {make_range_header({{1, -1}})};
  2277. auto res = cli.Get(path, headers);
  2278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2279. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2281. }
  2282. {
  2283. Headers headers = {make_range_header({{1, 10}})};
  2284. auto res = cli.Get(path, headers);
  2285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2286. EXPECT_EQ("bcdefghijk", res->body);
  2287. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2288. }
  2289. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2290. // entire resource, while the original httpbin returned 200. Both are
  2291. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2292. {
  2293. Headers headers = {make_range_header({{0, 31}})};
  2294. auto res = cli.Get(path, headers);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2298. res->status == StatusCode::PartialContent_206);
  2299. }
  2300. {
  2301. Headers headers = {make_range_header({{0, -1}})};
  2302. auto res = cli.Get(path, headers);
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2306. res->status == StatusCode::PartialContent_206);
  2307. }
  2308. // go-httpbin returns 206 with clamped range for over-range requests,
  2309. // while the original httpbin returned 416. Both behaviors are observed
  2310. // in real servers, so we only verify the request succeeds.
  2311. {
  2312. Headers headers = {make_range_header({{0, 32}})};
  2313. auto res = cli.Get(path, headers);
  2314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2315. }
  2316. }
  2317. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2318. auto host = "unresolvableaddress.local";
  2319. auto path = std::string{"/"};
  2320. #ifdef CPPHTTPLIB_SSL_ENABLED
  2321. auto port = 443;
  2322. SSLClient cli(host, port);
  2323. #else
  2324. auto port = 80;
  2325. Client cli(host, port);
  2326. #endif
  2327. cli.set_connection_timeout(1);
  2328. {
  2329. auto res = cli.Get(path);
  2330. ASSERT_FALSE(res);
  2331. }
  2332. std::this_thread::sleep_for(std::chrono::seconds(8));
  2333. }
  2334. #if defined(__linux__) && defined(__GLIBC__) && \
  2335. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2336. // Forward declaration: in split builds split.py strips `inline` and moves the
  2337. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2338. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2339. // against the symbol in both header-only and split builds.
  2340. namespace httplib {
  2341. namespace detail {
  2342. int getaddrinfo_with_timeout(const char *node, const char *service,
  2343. const struct addrinfo *hints,
  2344. struct addrinfo **res, time_t timeout_sec);
  2345. } // namespace detail
  2346. } // namespace httplib
  2347. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2348. //
  2349. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2350. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2351. // gai_suspend() call hits the connection timeout the function calls
  2352. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2353. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2354. // still alive and still references the now-destroyed stack frame.
  2355. //
  2356. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2357. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2358. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2359. // and runs them in a container.
  2360. namespace {
  2361. bool should_run_issue_2431_tests() {
  2362. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2363. return v && *v && std::string(v) != "0";
  2364. }
  2365. std::string unique_unresolvable_host(int n) {
  2366. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2367. // glibc still asks the configured nameserver — which is exactly the path
  2368. // we want to exercise. A unique label per call avoids the resolver cache.
  2369. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2370. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2371. std::to_string(n) + ".invalid";
  2372. }
  2373. } // namespace
  2374. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2375. if (!should_run_issue_2431_tests()) {
  2376. GTEST_SKIP()
  2377. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2378. }
  2379. for (int i = 0; i < 8; ++i) {
  2380. struct addrinfo hints;
  2381. memset(&hints, 0, sizeof(hints));
  2382. hints.ai_family = AF_UNSPEC;
  2383. hints.ai_socktype = SOCK_STREAM;
  2384. auto host = unique_unresolvable_host(i);
  2385. struct addrinfo *result = nullptr;
  2386. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2387. &result, /*timeout_sec=*/1);
  2388. if (rc == 0 && result) { freeaddrinfo(result); }
  2389. }
  2390. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2391. // stack region they still believe holds their gaicb.
  2392. std::this_thread::sleep_for(std::chrono::seconds(3));
  2393. }
  2394. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2395. if (!should_run_issue_2431_tests()) {
  2396. GTEST_SKIP()
  2397. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2398. }
  2399. std::atomic<bool> stop{false};
  2400. std::vector<std::thread> threads;
  2401. for (int t = 0; t < 8; ++t) {
  2402. threads.emplace_back([t, &stop] {
  2403. int i = 0;
  2404. while (!stop.load(std::memory_order_relaxed)) {
  2405. struct addrinfo hints;
  2406. memset(&hints, 0, sizeof(hints));
  2407. hints.ai_family = AF_UNSPEC;
  2408. hints.ai_socktype = SOCK_STREAM;
  2409. auto host = unique_unresolvable_host(t * 100000 + i++);
  2410. struct addrinfo *result = nullptr;
  2411. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2412. &result, /*timeout_sec=*/1);
  2413. if (rc == 0 && result) { freeaddrinfo(result); }
  2414. }
  2415. });
  2416. }
  2417. std::this_thread::sleep_for(std::chrono::seconds(8));
  2418. stop.store(true, std::memory_order_relaxed);
  2419. for (auto &th : threads) {
  2420. th.join();
  2421. }
  2422. std::this_thread::sleep_for(std::chrono::seconds(3));
  2423. }
  2424. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2425. if (!should_run_issue_2431_tests()) {
  2426. GTEST_SKIP()
  2427. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2428. }
  2429. std::atomic<bool> stop{false};
  2430. std::vector<std::thread> threads;
  2431. for (int t = 0; t < 8; ++t) {
  2432. threads.emplace_back([t, &stop] {
  2433. int i = 0;
  2434. while (!stop.load(std::memory_order_relaxed)) {
  2435. auto host = unique_unresolvable_host(t * 100000 + i++);
  2436. Client cli(host, 80);
  2437. cli.set_connection_timeout(1, 0);
  2438. cli.set_read_timeout(1, 0);
  2439. cli.set_write_timeout(1, 0);
  2440. (void)cli.Get("/");
  2441. }
  2442. });
  2443. }
  2444. std::this_thread::sleep_for(std::chrono::seconds(8));
  2445. stop.store(true, std::memory_order_relaxed);
  2446. for (auto &th : threads) {
  2447. th.join();
  2448. }
  2449. std::this_thread::sleep_for(std::chrono::seconds(3));
  2450. }
  2451. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2452. TEST(ConnectionErrorTest, InvalidHost) {
  2453. auto host = "-abcde.com";
  2454. #ifdef CPPHTTPLIB_SSL_ENABLED
  2455. auto port = 443;
  2456. SSLClient cli(host, port);
  2457. #else
  2458. auto port = 80;
  2459. Client cli(host, port);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. EXPECT_EQ(Error::Connection, res.error());
  2465. }
  2466. TEST(ConnectionErrorTest, InvalidHost2) {
  2467. auto host = "httpcan.org/";
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. SSLClient cli(host);
  2470. #else
  2471. Client cli(host);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. stringstream s;
  2489. s << "error code: " << res.error();
  2490. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2491. }
  2492. TEST(ConnectionErrorTest, InvalidPort) {
  2493. auto host = "localhost";
  2494. auto port = 44380;
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host, port);
  2497. #else
  2498. Client cli(host, port);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. EXPECT_TRUE(Error::Connection == res.error() ||
  2504. Error::ConnectionTimeout == res.error());
  2505. }
  2506. TEST(ConnectionErrorTest, Timeout_Online) {
  2507. auto host = "google.com";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. auto port = 44380;
  2510. SSLClient cli(host, port);
  2511. #else
  2512. auto port = 8080;
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. // only probe one address type so that the error reason
  2517. // correlates to the timed-out IPv4, not the unsupported
  2518. // IPv6 connection attempt
  2519. cli.set_address_family(AF_INET);
  2520. auto res = cli.Get("/");
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2523. }
  2524. TEST(CancelTest, NoCancel_Online) {
  2525. auto host = "httpbingo.org";
  2526. auto path = std::string{"/range/32"};
  2527. #ifdef CPPHTTPLIB_SSL_ENABLED
  2528. auto port = 443;
  2529. SSLClient cli(host, port);
  2530. #else
  2531. auto port = 80;
  2532. Client cli(host, port);
  2533. #endif
  2534. cli.set_connection_timeout(std::chrono::seconds(5));
  2535. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2537. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2538. EXPECT_EQ(StatusCode::OK_200, res->status);
  2539. }
  2540. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2541. // Use /bytes with a large payload so that the DownloadProgress callback
  2542. // (which only fires for Content-Length responses) is invoked before the
  2543. // entire body is received, giving cancellation a chance to fire.
  2544. auto host = "httpbingo.org";
  2545. auto path = std::string{"/bytes/524288"};
  2546. #ifdef CPPHTTPLIB_SSL_ENABLED
  2547. auto port = 443;
  2548. SSLClient cli(host, port);
  2549. #else
  2550. auto port = 80;
  2551. Client cli(host, port);
  2552. #endif
  2553. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2554. cli.set_connection_timeout(std::chrono::seconds(5));
  2555. ASSERT_TRUE(!res);
  2556. EXPECT_EQ(Error::Canceled, res.error());
  2557. }
  2558. TEST(CancelTest, WithCancelLargePayload_Online) {
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. cli.set_connection_timeout(std::chrono::seconds(5));
  2569. uint32_t count = 0;
  2570. auto res =
  2571. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_EQ(Error::Canceled, res.error());
  2574. }
  2575. TEST(CancelTest, NoCancelPost) {
  2576. Server svr;
  2577. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. });
  2580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2581. auto se = detail::scope_exit([&] {
  2582. svr.stop();
  2583. thread.join();
  2584. ASSERT_FALSE(svr.is_running());
  2585. });
  2586. svr.wait_until_ready();
  2587. Client cli(HOST, PORT);
  2588. cli.set_connection_timeout(std::chrono::seconds(5));
  2589. auto res =
  2590. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2591. "application/json", [](uint64_t, uint64_t) { return true; });
  2592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2593. EXPECT_EQ("Hello World!", res->body);
  2594. EXPECT_EQ(StatusCode::OK_200, res->status);
  2595. }
  2596. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2597. Server svr;
  2598. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. Client cli(HOST, PORT);
  2609. cli.set_connection_timeout(std::chrono::seconds(5));
  2610. auto res =
  2611. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2612. "application/json", [](uint64_t, uint64_t) { return false; });
  2613. ASSERT_TRUE(!res);
  2614. EXPECT_EQ(Error::Canceled, res.error());
  2615. }
  2616. TEST(CancelTest, WithCancelLargePayloadPost) {
  2617. Server svr;
  2618. svr.set_payload_max_length(200 * 1024 * 1024);
  2619. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2620. res.set_content(LARGE_DATA, "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. Client cli(HOST, PORT);
  2630. cli.set_payload_max_length(200 * 1024 * 1024);
  2631. cli.set_connection_timeout(std::chrono::seconds(5));
  2632. auto res =
  2633. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2634. "application/json", [](uint64_t, uint64_t) { return false; });
  2635. ASSERT_TRUE(!res);
  2636. EXPECT_EQ(Error::Canceled, res.error());
  2637. }
  2638. TEST(CancelTest, NoCancelPut) {
  2639. Server svr;
  2640. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2641. res.set_content("Hello World!", "text/plain");
  2642. });
  2643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, PORT);
  2651. cli.set_connection_timeout(std::chrono::seconds(5));
  2652. auto res =
  2653. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2654. "application/json", [](uint64_t, uint64_t) { return true; });
  2655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2656. EXPECT_EQ("Hello World!", res->body);
  2657. EXPECT_EQ(StatusCode::OK_200, res->status);
  2658. }
  2659. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2660. Server svr;
  2661. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2662. res.set_content("Hello World!", "text/plain");
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. cli.set_connection_timeout(std::chrono::seconds(5));
  2673. auto res =
  2674. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2675. "application/json", [](uint64_t, uint64_t) { return false; });
  2676. ASSERT_TRUE(!res);
  2677. EXPECT_EQ(Error::Canceled, res.error());
  2678. }
  2679. TEST(CancelTest, WithCancelLargePayloadPut) {
  2680. Server svr;
  2681. svr.set_payload_max_length(200 * 1024 * 1024);
  2682. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2683. res.set_content(LARGE_DATA, "text/plain");
  2684. });
  2685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2686. auto se = detail::scope_exit([&] {
  2687. svr.stop();
  2688. thread.join();
  2689. ASSERT_FALSE(svr.is_running());
  2690. });
  2691. svr.wait_until_ready();
  2692. Client cli(HOST, PORT);
  2693. cli.set_payload_max_length(200 * 1024 * 1024);
  2694. cli.set_connection_timeout(std::chrono::seconds(5));
  2695. auto res =
  2696. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2697. "application/json", [](uint64_t, uint64_t) { return false; });
  2698. ASSERT_TRUE(!res);
  2699. EXPECT_EQ(Error::Canceled, res.error());
  2700. }
  2701. TEST(CancelTest, NoCancelPatch) {
  2702. Server svr;
  2703. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content("Hello World!", "text/plain");
  2705. });
  2706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2707. auto se = detail::scope_exit([&] {
  2708. svr.stop();
  2709. thread.join();
  2710. ASSERT_FALSE(svr.is_running());
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, PORT);
  2714. cli.set_connection_timeout(std::chrono::seconds(5));
  2715. auto res =
  2716. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2717. "application/json", [](uint64_t, uint64_t) { return true; });
  2718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2719. EXPECT_EQ("Hello World!", res->body);
  2720. EXPECT_EQ(StatusCode::OK_200, res->status);
  2721. }
  2722. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2723. Server svr;
  2724. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2725. res.set_content("Hello World!", "text/plain");
  2726. });
  2727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2728. auto se = detail::scope_exit([&] {
  2729. svr.stop();
  2730. thread.join();
  2731. ASSERT_FALSE(svr.is_running());
  2732. });
  2733. svr.wait_until_ready();
  2734. Client cli(HOST, PORT);
  2735. cli.set_connection_timeout(std::chrono::seconds(5));
  2736. auto res =
  2737. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2738. "application/json", [](uint64_t, uint64_t) { return false; });
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Canceled, res.error());
  2741. }
  2742. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2743. Server svr;
  2744. svr.set_payload_max_length(200 * 1024 * 1024);
  2745. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2746. res.set_content(LARGE_DATA, "text/plain");
  2747. });
  2748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2749. auto se = detail::scope_exit([&] {
  2750. svr.stop();
  2751. thread.join();
  2752. ASSERT_FALSE(svr.is_running());
  2753. });
  2754. svr.wait_until_ready();
  2755. Client cli(HOST, PORT);
  2756. cli.set_payload_max_length(200 * 1024 * 1024);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. auto res =
  2759. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2760. "application/json", [](uint64_t, uint64_t) { return false; });
  2761. ASSERT_TRUE(!res);
  2762. EXPECT_EQ(Error::Canceled, res.error());
  2763. }
  2764. TEST(CancelTest, NoCancelDelete) {
  2765. Server svr;
  2766. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2767. res.set_content("Hello World!", "text/plain");
  2768. });
  2769. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2770. auto se = detail::scope_exit([&] {
  2771. svr.stop();
  2772. thread.join();
  2773. ASSERT_FALSE(svr.is_running());
  2774. });
  2775. svr.wait_until_ready();
  2776. Client cli(HOST, PORT);
  2777. cli.set_connection_timeout(std::chrono::seconds(5));
  2778. auto res =
  2779. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2780. "application/json", [](uint64_t, uint64_t) { return true; });
  2781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2782. EXPECT_EQ("Hello World!", res->body);
  2783. EXPECT_EQ(StatusCode::OK_200, res->status);
  2784. }
  2785. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2786. Server svr;
  2787. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2788. res.set_content("Hello World!", "text/plain");
  2789. });
  2790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2791. auto se = detail::scope_exit([&] {
  2792. svr.stop();
  2793. thread.join();
  2794. ASSERT_FALSE(svr.is_running());
  2795. });
  2796. svr.wait_until_ready();
  2797. Client cli(HOST, PORT);
  2798. cli.set_connection_timeout(std::chrono::seconds(5));
  2799. auto res =
  2800. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2801. "application/json", [](uint64_t, uint64_t) { return false; });
  2802. ASSERT_TRUE(!res);
  2803. EXPECT_EQ(Error::Canceled, res.error());
  2804. }
  2805. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2806. Server svr;
  2807. svr.set_payload_max_length(200 * 1024 * 1024);
  2808. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2809. res.set_content(LARGE_DATA, "text/plain");
  2810. });
  2811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2812. auto se = detail::scope_exit([&] {
  2813. svr.stop();
  2814. thread.join();
  2815. ASSERT_FALSE(svr.is_running());
  2816. });
  2817. svr.wait_until_ready();
  2818. Client cli(HOST, PORT);
  2819. cli.set_payload_max_length(200 * 1024 * 1024);
  2820. cli.set_connection_timeout(std::chrono::seconds(5));
  2821. auto res =
  2822. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2823. "application/json", [](uint64_t, uint64_t) { return false; });
  2824. ASSERT_TRUE(!res);
  2825. EXPECT_EQ(Error::Canceled, res.error());
  2826. }
  2827. static std::string remove_whitespace(const std::string &input) {
  2828. std::string output;
  2829. output.reserve(input.size());
  2830. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2831. [](unsigned char c) { return !std::isspace(c); });
  2832. return output;
  2833. }
  2834. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2835. auto host = "httpbingo.org";
  2836. auto path = std::string{"/basic-auth/hello/world"};
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. auto port = 443;
  2839. SSLClient cli(host, port);
  2840. #else
  2841. auto port = 80;
  2842. Client cli(host, port);
  2843. #endif
  2844. {
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. auto res = cli.Get(
  2851. path, Headers{make_basic_authentication_header("hello", "world")});
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. auto body = remove_whitespace(res->body);
  2854. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2855. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2856. EXPECT_EQ(StatusCode::OK_200, res->status);
  2857. }
  2858. {
  2859. cli.set_basic_auth("hello", "world");
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. auto body = remove_whitespace(res->body);
  2863. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2864. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2865. EXPECT_EQ(StatusCode::OK_200, res->status);
  2866. }
  2867. {
  2868. cli.set_basic_auth("hello", "bad");
  2869. auto res = cli.Get(path);
  2870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2871. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("bad", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2878. }
  2879. }
  2880. #ifdef CPPHTTPLIB_SSL_ENABLED
  2881. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2882. auto host = "httpbingo.org";
  2883. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2884. auto paths = std::vector<std::string>{
  2885. "/digest-auth/auth/hello/world/MD5",
  2886. "/digest-auth/auth/hello/world/SHA-256",
  2887. };
  2888. auto port = 443;
  2889. SSLClient cli(host, port);
  2890. {
  2891. auto res = cli.Get(unauth_path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. cli.set_digest_auth("hello", "world");
  2897. for (const auto &path : paths) {
  2898. auto res = cli.Get(path.c_str());
  2899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2900. auto body = remove_whitespace(res->body);
  2901. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2902. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. }
  2905. cli.set_digest_auth("hello", "bad");
  2906. for (const auto &path : paths) {
  2907. auto res = cli.Get(path.c_str());
  2908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2909. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2910. }
  2911. }
  2912. }
  2913. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2914. // comma-separated list of challenges, and each challenge may itself carry a
  2915. // comma-separated auth-param list, so a server can legally offer Basic
  2916. // before Digest, either as two field lines or packed into one. Runs one 401
  2917. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2918. // value() joins them in receipt order) and checks that the retry carries a
  2919. // well-formed Digest Authorization header naming expected_realm.
  2920. static void
  2921. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2922. const std::string &expected_realm) {
  2923. std::atomic<int> hits{0};
  2924. Server svr;
  2925. svr.Get("/x", [&](const Request &req, Response &res) {
  2926. if (++hits == 1) {
  2927. res.status = StatusCode::Unauthorized_401;
  2928. for (const auto &challenge : challenges) {
  2929. res.set_header("WWW-Authenticate", challenge);
  2930. }
  2931. } else {
  2932. auto authorization = req.get_header_value("Authorization");
  2933. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2934. EXPECT_NE(std::string::npos,
  2935. authorization.find("realm=\"" + expected_realm + "\""));
  2936. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2937. res.set_content("ok", "text/plain");
  2938. }
  2939. });
  2940. auto port = svr.bind_to_any_port(HOST);
  2941. std::thread t([&]() { svr.listen_after_bind(); });
  2942. auto se = detail::scope_exit([&] {
  2943. svr.stop();
  2944. t.join();
  2945. });
  2946. svr.wait_until_ready();
  2947. Client cli(HOST, port);
  2948. cli.set_digest_auth("hello", "world");
  2949. auto res = cli.Get("/x");
  2950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2951. EXPECT_EQ(2, hits.load());
  2952. }
  2953. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2954. static const char *kDigestChallenge =
  2955. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2956. "algorithm=MD5";
  2957. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2958. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2959. "testrealm");
  2960. }
  2961. // Same challenge list with the schemes in the opposite order, to make sure
  2962. // the fix above didn't just special-case "Basic first".
  2963. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2964. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2965. "testrealm");
  2966. }
  2967. // A comma inside a quoted auth-param value must not be mistaken for the
  2968. // separator between two challenges (or two auth-params).
  2969. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2970. run_digest_challenge_list_test(
  2971. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2972. "algorithm=MD5"},
  2973. "test,realm");
  2974. }
  2975. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2976. // the params and leaves out the fragment.
  2977. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2978. Server svr;
  2979. std::string uri, target;
  2980. svr.Get("/a b", [&](const Request &req, Response &res) {
  2981. auto auth = req.get_header_value("Authorization");
  2982. if (auth.empty()) {
  2983. res.status = StatusCode::Unauthorized_401;
  2984. res.set_header("WWW-Authenticate",
  2985. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2986. return;
  2987. }
  2988. auto b = auth.find("uri=\"") + 5;
  2989. uri = auth.substr(b, auth.find('"', b) - b);
  2990. target = req.target;
  2991. });
  2992. auto port = svr.bind_to_any_port(HOST);
  2993. std::thread t([&]() { svr.listen_after_bind(); });
  2994. auto se = detail::scope_exit([&] {
  2995. svr.stop();
  2996. t.join();
  2997. });
  2998. svr.wait_until_ready();
  2999. Client cli(HOST, port);
  3000. cli.set_digest_auth("hello", "world");
  3001. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ("/a%20b?x=1", target);
  3004. EXPECT_EQ(target, uri);
  3005. }
  3006. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3007. // make_digest_authentication_header() dereferences both unconditionally, so
  3008. // a server sending a challenge missing either one must not be treated as
  3009. // usable -- doing so used to crash the client with std::out_of_range.
  3010. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3011. Server svr;
  3012. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3013. res.status = StatusCode::Unauthorized_401;
  3014. res.set_header("WWW-Authenticate", challenge);
  3015. });
  3016. auto port = svr.bind_to_any_port(HOST);
  3017. std::thread t([&]() { svr.listen_after_bind(); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. t.join();
  3021. });
  3022. svr.wait_until_ready();
  3023. Client cli(HOST, port);
  3024. cli.set_digest_auth("hello", "world");
  3025. auto res = cli.Get("/x");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3028. }
  3029. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3030. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3031. }
  3032. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3033. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3034. }
  3035. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3036. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3037. }
  3038. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3039. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3040. // when storing the values, so the header builder has to re-escape them (and
  3041. // keep algorithm a bare token); otherwise the value breaks out of its
  3042. // quoted-string and injects extra auth-params into the client's Authorization.
  3043. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3044. std::atomic<int> hits{0};
  3045. std::string authorization;
  3046. Server svr;
  3047. svr.Get("/x", [&](const Request &req, Response &res) {
  3048. if (++hits == 1) {
  3049. res.status = StatusCode::Unauthorized_401;
  3050. // On the wire the quotes embedded in the values are backslash-escaped.
  3051. res.set_header("WWW-Authenticate",
  3052. "Digest realm=\"testrealm\", "
  3053. "nonce=\"n\\\"; injected=\\\"x\", "
  3054. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3055. } else {
  3056. authorization = req.get_header_value("Authorization");
  3057. res.set_content("ok", "text/plain");
  3058. }
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. std::thread t([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. t.join();
  3065. });
  3066. svr.wait_until_ready();
  3067. Client cli(HOST, port);
  3068. cli.set_digest_auth("hello", "world");
  3069. auto res = cli.Get("/x");
  3070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3071. EXPECT_EQ(2, hits.load());
  3072. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3073. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3074. // inside its quoted-string rather than starting an "injected" auth-param.
  3075. EXPECT_NE(std::string::npos,
  3076. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3077. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3078. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3079. }
  3080. #endif
  3081. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3082. auto host = "google.com";
  3083. auto another_host = "example.com";
  3084. auto wrong_ip = "0.0.0.0";
  3085. #ifdef CPPHTTPLIB_SSL_ENABLED
  3086. SSLClient cli(host);
  3087. #else
  3088. Client cli(host);
  3089. #endif
  3090. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3091. auto res = cli.Get("/");
  3092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3093. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3094. }
  3095. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3096. auto host = "google.com";
  3097. auto wrong_ip = "0.0.0.0";
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. SSLClient cli(host);
  3100. #else
  3101. Client cli(host);
  3102. #endif
  3103. cli.set_hostname_addr_map({{host, wrong_ip}});
  3104. auto res = cli.Get("/");
  3105. ASSERT_TRUE(!res);
  3106. EXPECT_EQ(Error::Connection, res.error());
  3107. }
  3108. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3109. // A mapped value that is not an IP literal must be resolved. "localhost"
  3110. // resolves from the hosts file, so this test needs no external DNS.
  3111. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3112. auto host = "target.invalid";
  3113. Server svr;
  3114. std::string received_host;
  3115. svr.Get("/hi", [&](const Request &req, Response &res) {
  3116. received_host = req.get_header_value("Host");
  3117. res.set_content("Hello World!", "text/plain");
  3118. });
  3119. auto port = svr.bind_to_any_port(HOST);
  3120. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3121. auto se = detail::scope_exit([&] {
  3122. svr.stop();
  3123. thread.join();
  3124. ASSERT_FALSE(svr.is_running());
  3125. });
  3126. svr.wait_until_ready();
  3127. Client cli(host, port);
  3128. cli.set_hostname_addr_map({{host, HOST}});
  3129. auto res = cli.Get("/hi");
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. // The mapping only redirects the connection; the identity stays host_.
  3133. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3134. }
  3135. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3136. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3137. auto host = "target.invalid";
  3138. Server svr;
  3139. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3140. res.set_content("Hello World!", "text/plain");
  3141. });
  3142. auto port = svr.bind_to_any_port("127.0.0.1");
  3143. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3144. auto se = detail::scope_exit([&] {
  3145. svr.stop();
  3146. thread.join();
  3147. ASSERT_FALSE(svr.is_running());
  3148. });
  3149. svr.wait_until_ready();
  3150. Client cli(host, port);
  3151. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3152. auto res = cli.Get("/hi");
  3153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3154. EXPECT_EQ(StatusCode::OK_200, res->status);
  3155. }
  3156. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3157. // An empty mapped value must leave host_ as the connection target. Without
  3158. // that guard the empty value would become the host argument, getaddrinfo
  3159. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3160. // loopback - silently connecting somewhere the caller never asked for.
  3161. // The server listens on loopback, so such a fallback would succeed and is
  3162. // therefore observable as a failure of this test.
  3163. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3164. Server svr;
  3165. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3166. res.set_content("Hello World!", "text/plain");
  3167. });
  3168. auto port = svr.bind_to_any_port(HOST);
  3169. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3170. auto se = detail::scope_exit([&] {
  3171. svr.stop();
  3172. thread.join();
  3173. ASSERT_FALSE(svr.is_running());
  3174. });
  3175. svr.wait_until_ready();
  3176. Client cli(blackhole, port);
  3177. cli.set_hostname_addr_map({{blackhole, ""}});
  3178. cli.set_connection_timeout(1);
  3179. auto res = cli.Get("/hi");
  3180. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3181. }
  3182. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3183. auto host = "httpbingo.org";
  3184. auto path = std::string{"/absolute-redirect/3"};
  3185. #ifdef CPPHTTPLIB_SSL_ENABLED
  3186. SSLClient cli(host);
  3187. #else
  3188. Client cli(host);
  3189. #endif
  3190. cli.set_follow_location(true);
  3191. auto res = cli.Get(path);
  3192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3193. EXPECT_EQ(StatusCode::OK_200, res->status);
  3194. }
  3195. TEST(RedirectTest, Redirect_Online) {
  3196. auto host = "httpbingo.org";
  3197. auto path = std::string{"/redirect/3"};
  3198. #ifdef CPPHTTPLIB_SSL_ENABLED
  3199. SSLClient cli(host);
  3200. #else
  3201. Client cli(host);
  3202. #endif
  3203. cli.set_follow_location(true);
  3204. auto res = cli.Get(path);
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(RelativeRedirectTest, Redirect_Online) {
  3209. auto host = "httpbingo.org";
  3210. auto path = std::string{"/relative-redirect/3"};
  3211. #ifdef CPPHTTPLIB_SSL_ENABLED
  3212. SSLClient cli(host);
  3213. #else
  3214. Client cli(host);
  3215. #endif
  3216. cli.set_follow_location(true);
  3217. auto res = cli.Get(path);
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(TooManyRedirectTest, Redirect_Online) {
  3222. auto host = "httpbingo.org";
  3223. auto path = std::string{"/redirect/21"};
  3224. #ifdef CPPHTTPLIB_SSL_ENABLED
  3225. SSLClient cli(host);
  3226. #else
  3227. Client cli(host);
  3228. #endif
  3229. cli.set_follow_location(true);
  3230. auto res = cli.Get(path);
  3231. ASSERT_TRUE(!res);
  3232. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3233. }
  3234. #ifdef CPPHTTPLIB_SSL_ENABLED
  3235. TEST(YahooRedirectTest, Redirect_Online) {
  3236. Client cli("yahoo.com");
  3237. auto res = cli.Get("/");
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3240. cli.set_follow_location(true);
  3241. res = cli.Get("/");
  3242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3245. }
  3246. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3247. #define REDIR_HOST "httpbingo.org"
  3248. #define REDIR_PATH "/redirect-to"
  3249. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3250. SSLClient cli(REDIR_HOST);
  3251. cli.set_follow_location(true);
  3252. auto res =
  3253. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. }
  3257. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3258. SSLClient cli(REDIR_HOST);
  3259. cli.set_follow_location(true);
  3260. Params params;
  3261. params.emplace("url", "http://example.com");
  3262. params.emplace("status_code", "302");
  3263. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. }
  3267. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3268. SSLClient cli(REDIR_HOST);
  3269. cli.set_follow_location(true);
  3270. Params params;
  3271. params.emplace("url", "http://example.com");
  3272. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::OK_200, res->status);
  3275. }
  3276. TEST(UrlWithSpace, Redirect_Online) {
  3277. SSLClient cli("edge.forgecdn.net");
  3278. cli.set_follow_location(true);
  3279. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3281. EXPECT_EQ(StatusCode::OK_200, res->status);
  3282. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3283. }
  3284. #endif
  3285. #if !defined(_WIN32) && !defined(_WIN64)
  3286. TEST(ReceiveSignals, Signal) {
  3287. auto setupSignalHandlers = []() {
  3288. struct sigaction act;
  3289. sigemptyset(&act.sa_mask);
  3290. act.sa_flags = SA_SIGINFO;
  3291. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3292. switch (sig) {
  3293. case SIGINT:
  3294. default: break;
  3295. }
  3296. };
  3297. ::sigaction(SIGINT, &act, nullptr);
  3298. };
  3299. Server svr;
  3300. int port = 0;
  3301. auto thread = std::thread([&]() {
  3302. setupSignalHandlers();
  3303. port = svr.bind_to_any_port(HOST);
  3304. svr.listen_after_bind();
  3305. });
  3306. auto se = detail::scope_exit([&] {
  3307. svr.stop();
  3308. thread.join();
  3309. ASSERT_FALSE(svr.is_running());
  3310. });
  3311. svr.wait_until_ready();
  3312. ASSERT_TRUE(svr.is_running());
  3313. pthread_kill(thread.native_handle(), SIGINT);
  3314. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3315. ASSERT_TRUE(svr.is_running());
  3316. }
  3317. #endif
  3318. TEST(RedirectToDifferentPort, Redirect) {
  3319. Server svr1;
  3320. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3321. res.set_content("Hello World!", "text/plain");
  3322. });
  3323. int svr1_port = 0;
  3324. auto thread1 = std::thread([&]() {
  3325. svr1_port = svr1.bind_to_any_port(HOST);
  3326. svr1.listen_after_bind();
  3327. });
  3328. Server svr2;
  3329. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3330. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3331. });
  3332. int svr2_port = 0;
  3333. auto thread2 = std::thread([&]() {
  3334. svr2_port = svr2.bind_to_any_port(HOST);
  3335. svr2.listen_after_bind();
  3336. });
  3337. auto se = detail::scope_exit([&] {
  3338. svr2.stop();
  3339. thread2.join();
  3340. svr1.stop();
  3341. thread1.join();
  3342. ASSERT_FALSE(svr2.is_running());
  3343. ASSERT_FALSE(svr1.is_running());
  3344. });
  3345. svr1.wait_until_ready();
  3346. svr2.wait_until_ready();
  3347. Client cli("localhost", svr2_port);
  3348. cli.set_follow_location(true);
  3349. auto res = cli.Get("/2");
  3350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ("Hello World!", res->body);
  3353. }
  3354. // GET /redir on one server redirects to /target on another port, so the
  3355. // client follows it with a new client.
  3356. static Result
  3357. GetThroughRedirectToDifferentPort(Server::Handler target,
  3358. const std::function<void(Client &)> &setup,
  3359. const Headers &headers = Headers()) {
  3360. Server target_svr;
  3361. target_svr.Get("/target", target);
  3362. int target_port = 0;
  3363. auto target_thread = std::thread([&]() {
  3364. target_port = target_svr.bind_to_any_port(HOST);
  3365. target_svr.listen_after_bind();
  3366. });
  3367. Server origin_svr;
  3368. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3369. res.set_redirect(
  3370. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3371. });
  3372. int origin_port = 0;
  3373. auto origin_thread = std::thread([&]() {
  3374. origin_port = origin_svr.bind_to_any_port(HOST);
  3375. origin_svr.listen_after_bind();
  3376. });
  3377. auto se = detail::scope_exit([&] {
  3378. origin_svr.stop();
  3379. origin_thread.join();
  3380. target_svr.stop();
  3381. target_thread.join();
  3382. });
  3383. target_svr.wait_until_ready();
  3384. origin_svr.wait_until_ready();
  3385. Client cli("localhost", origin_port);
  3386. cli.set_follow_location(true);
  3387. setup(cli);
  3388. return cli.Get("/redir", headers);
  3389. }
  3390. static void
  3391. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3392. std::string captured_authorization;
  3393. auto result = GetThroughRedirectToDifferentPort(
  3394. [&](const Request &req, Response &res) {
  3395. captured_authorization = req.get_header_value("Authorization");
  3396. res.set_content("OK", "text/plain");
  3397. },
  3398. set_auth);
  3399. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3400. EXPECT_EQ(StatusCode::OK_200, result->status);
  3401. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3402. EXPECT_TRUE(captured_authorization.empty());
  3403. }
  3404. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3405. TestDoNotForwardCredentialsOnRedirect(
  3406. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3407. }
  3408. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3409. TestDoNotForwardCredentialsOnRedirect(
  3410. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3411. }
  3412. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3413. std::string captured_cookie;
  3414. auto result = GetThroughRedirectToDifferentPort(
  3415. [&](const Request &req, Response &res) {
  3416. captured_cookie = req.get_header_value("Cookie");
  3417. res.set_content("OK", "text/plain");
  3418. },
  3419. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3420. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3421. EXPECT_EQ(StatusCode::OK_200, result->status);
  3422. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3423. EXPECT_TRUE(captured_cookie.empty());
  3424. }
  3425. TEST(RedirectToSamePort, ForwardCookie) {
  3426. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3427. // header so that ordinary session flows keep working.
  3428. Server svr;
  3429. std::string captured_cookie;
  3430. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3431. res.set_redirect("/target", 302);
  3432. });
  3433. svr.Get("/target", [&](const Request &req, Response &res) {
  3434. captured_cookie = req.get_header_value("Cookie");
  3435. res.set_content("OK", "text/plain");
  3436. });
  3437. auto port = svr.bind_to_any_port(HOST);
  3438. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3439. auto se = detail::scope_exit([&] {
  3440. svr.stop();
  3441. thread.join();
  3442. ASSERT_FALSE(svr.is_running());
  3443. });
  3444. svr.wait_until_ready();
  3445. Client cli(HOST, port);
  3446. cli.set_follow_location(true);
  3447. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3448. auto res = cli.Get("/redir", headers);
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3452. }
  3453. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3454. std::string authorization;
  3455. std::string trace_id;
  3456. auto result = GetThroughRedirectToDifferentPort(
  3457. [&](const Request &req, Response &res) {
  3458. authorization = req.get_header_value("Authorization");
  3459. trace_id = req.get_header_value("X-Trace-Id");
  3460. res.set_content("OK", "text/plain");
  3461. },
  3462. [](Client &cli) {
  3463. cli.set_default_headers(
  3464. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3465. });
  3466. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3467. EXPECT_EQ(StatusCode::OK_200, result->status);
  3468. // Like a header given with the request, a default one goes along unless it
  3469. // carries credentials (RFC 9110 15.4).
  3470. EXPECT_TRUE(authorization.empty());
  3471. EXPECT_EQ("42", trace_id);
  3472. }
  3473. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3474. auto result = GetThroughRedirectToDifferentPort(
  3475. [](const Request &, Response &res) {
  3476. res.set_content(std::string(2048, 'x'), "text/plain");
  3477. },
  3478. [](Client &cli) { cli.set_payload_max_length(1024); });
  3479. EXPECT_FALSE(result);
  3480. }
  3481. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3482. auto result = GetThroughRedirectToDifferentPort(
  3483. [](const Request &req, Response &res) {
  3484. // Answer after a second, or once the client gives up.
  3485. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3486. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3487. }
  3488. res.set_content("late", "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3491. ASSERT_FALSE(result);
  3492. EXPECT_EQ(Error::Read, result.error());
  3493. }
  3494. #ifdef CPPHTTPLIB_SSL_ENABLED
  3495. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3496. auto result = GetThroughRedirectToDifferentPort(
  3497. [](const Request &, Response &res) {
  3498. res.status = StatusCode::Unauthorized_401;
  3499. res.set_header("WWW-Authenticate",
  3500. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3501. },
  3502. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3503. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3504. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3505. }
  3506. #endif
  3507. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3508. Server svr;
  3509. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3510. // Port number that overflows int — should not crash
  3511. res.set_redirect("http://localhost:99999999999999999999/target");
  3512. });
  3513. auto port = svr.bind_to_any_port(HOST);
  3514. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3515. auto se = detail::scope_exit([&] {
  3516. svr.stop();
  3517. thread.join();
  3518. ASSERT_FALSE(svr.is_running());
  3519. });
  3520. svr.wait_until_ready();
  3521. Client cli(HOST, port);
  3522. cli.set_follow_location(true);
  3523. auto res = cli.Get("/redir");
  3524. // Should fail gracefully, not crash (no valid response due to bad port)
  3525. EXPECT_FALSE(res);
  3526. }
  3527. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3528. Server svr;
  3529. auto port = svr.bind_to_any_port(HOST);
  3530. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3531. // The server's own port followed by junk must not be followed
  3532. res.set_redirect("http://" + std::string(HOST) + ":" +
  3533. std::to_string(port) + "junk/target");
  3534. });
  3535. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3536. res.set_content("target", "text/plain");
  3537. });
  3538. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3539. auto se = detail::scope_exit([&] {
  3540. svr.stop();
  3541. thread.join();
  3542. ASSERT_FALSE(svr.is_running());
  3543. });
  3544. svr.wait_until_ready();
  3545. Client cli(HOST, port);
  3546. cli.set_follow_location(true);
  3547. auto res = cli.Get("/redir");
  3548. EXPECT_FALSE(res);
  3549. }
  3550. TEST(RedirectFromPageWithContent, Redirect) {
  3551. Server svr;
  3552. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3553. res.set_content("___", "text/plain");
  3554. res.set_redirect("/2");
  3555. });
  3556. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3557. res.set_content("Hello World!", "text/plain");
  3558. });
  3559. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3560. auto se = detail::scope_exit([&] {
  3561. svr.stop();
  3562. th.join();
  3563. ASSERT_FALSE(svr.is_running());
  3564. });
  3565. svr.wait_until_ready();
  3566. {
  3567. Client cli("localhost", PORT);
  3568. cli.set_follow_location(true);
  3569. std::string body;
  3570. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3571. body.append(data, data_length);
  3572. return true;
  3573. });
  3574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3575. EXPECT_EQ(StatusCode::OK_200, res->status);
  3576. EXPECT_EQ("Hello World!", body);
  3577. }
  3578. {
  3579. Client cli("localhost", PORT);
  3580. std::string body;
  3581. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3582. body.append(data, data_length);
  3583. return true;
  3584. });
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ(StatusCode::Found_302, res->status);
  3587. EXPECT_EQ("___", body);
  3588. }
  3589. }
  3590. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3591. Server svr;
  3592. auto port_str = std::to_string(PORT);
  3593. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3594. auto expected_host = "[::1]:" + port_str;
  3595. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3596. res.set_content("___", "text/plain");
  3597. // res.set_redirect("/2");
  3598. res.set_redirect(redirect_url);
  3599. });
  3600. svr.Get("/2", [&](const Request &req, Response &res) {
  3601. auto host_header = req.headers.find("Host");
  3602. ASSERT_TRUE(host_header != req.headers.end());
  3603. EXPECT_EQ(expected_host, host_header->second);
  3604. res.set_content("Hello World!", "text/plain");
  3605. });
  3606. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3607. auto se = detail::scope_exit([&] {
  3608. svr.stop();
  3609. th.join();
  3610. ASSERT_FALSE(svr.is_running());
  3611. });
  3612. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3613. // actually starts anything, so the condition !svr.is_running() will
  3614. // always remain true, and the loop never stops.
  3615. // This basically counts how many milliseconds have passed since the
  3616. // call to svr.listen(), and if after 5 seconds nothing started yet
  3617. // aborts the test.
  3618. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3619. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3620. ASSERT_LT(milliseconds, 5000U);
  3621. }
  3622. {
  3623. Client cli("::1", PORT);
  3624. cli.set_follow_location(true);
  3625. std::string body;
  3626. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3627. body.append(data, data_length);
  3628. return true;
  3629. });
  3630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. EXPECT_EQ("Hello World!", body);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. std::string body;
  3637. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3638. body.append(data, data_length);
  3639. return true;
  3640. });
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::Found_302, res->status);
  3643. EXPECT_EQ("___", body);
  3644. }
  3645. }
  3646. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3647. Server svr;
  3648. svr.Get("/foo", [](const Request &req, Response &res) {
  3649. auto a = req.params.find("a");
  3650. if (a != req.params.end()) {
  3651. res.set_content((*a).second, "text/plain");
  3652. res.status = StatusCode::OK_200;
  3653. } else {
  3654. res.status = StatusCode::BadRequest_400;
  3655. }
  3656. });
  3657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3658. auto se = detail::scope_exit([&] {
  3659. svr.stop();
  3660. thread.join();
  3661. ASSERT_FALSE(svr.is_running());
  3662. });
  3663. svr.wait_until_ready();
  3664. {
  3665. Client cli(HOST, PORT);
  3666. cli.set_path_encode(false);
  3667. auto res = cli.Get("/foo?a=explicitly+encoded");
  3668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3669. EXPECT_EQ(StatusCode::OK_200, res->status);
  3670. // This expects it back with a space, as the `+` won't have been
  3671. // url-encoded, and server-side the params get decoded turning `+`
  3672. // into spaces.
  3673. EXPECT_EQ("explicitly encoded", res->body);
  3674. }
  3675. }
  3676. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3677. // When path encoding is disabled the client must transmit the supplied
  3678. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3679. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3680. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3681. // than a space (0x20). Assert on the raw wire target to catch this.
  3682. Server svr;
  3683. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3684. svr.Get("/foo", [&](const Request &req, Response &res) {
  3685. EXPECT_EQ(expected_target, req.target);
  3686. res.status = StatusCode::OK_200;
  3687. });
  3688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3689. auto se = detail::scope_exit([&] {
  3690. svr.stop();
  3691. thread.join();
  3692. ASSERT_FALSE(svr.is_running());
  3693. });
  3694. svr.wait_until_ready();
  3695. {
  3696. Client cli(HOST, PORT);
  3697. cli.set_path_encode(false);
  3698. auto res = cli.Get(expected_target.c_str());
  3699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. }
  3702. }
  3703. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3704. // `open_stream()` used to skip the path encoding that the buffered send
  3705. // path applies, so the same `path` produced different bytes in the request
  3706. // line depending on which API was used. Assert the two agree.
  3707. Server svr;
  3708. std::string target;
  3709. svr.Get(".*", [&](const Request &req, Response &res) {
  3710. target = req.target;
  3711. res.status = StatusCode::OK_200;
  3712. });
  3713. auto port = svr.bind_to_any_port(HOST);
  3714. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3715. auto se = detail::scope_exit([&] {
  3716. svr.stop();
  3717. thread.join();
  3718. ASSERT_FALSE(svr.is_running());
  3719. });
  3720. svr.wait_until_ready();
  3721. struct {
  3722. const char *path;
  3723. const char *expected;
  3724. } cases[] = {
  3725. {"/a b?x=1", "/a%20b?x=1"},
  3726. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3727. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3728. };
  3729. for (const auto &c : cases) {
  3730. Client cli(HOST, port);
  3731. target.clear();
  3732. auto res = cli.Get(c.path);
  3733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3734. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3735. auto buffered_target = target;
  3736. target.clear();
  3737. auto handle = cli.open_stream("GET", c.path);
  3738. EXPECT_TRUE(handle.is_valid())
  3739. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3740. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3744. // The `set_path_encode(false)` contract — transmit the supplied target
  3745. // verbatim — must hold for the streaming API too.
  3746. Server svr;
  3747. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3748. std::string target;
  3749. svr.Get("/foo", [&](const Request &req, Response &res) {
  3750. target = req.target;
  3751. res.status = StatusCode::OK_200;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. cli.set_path_encode(false);
  3764. auto handle = cli.open_stream("GET", expected_target);
  3765. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3766. EXPECT_EQ(expected_target, target);
  3767. }
  3768. }
  3769. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3770. // With path encoding enabled a CR/LF in the target is percent-encoded
  3771. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3772. // write_request_line still backstops `set_path_encode(false)`, which is
  3773. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3774. Server svr;
  3775. // Captured before routing: the decoded path contains a newline, which a
  3776. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3777. std::string target;
  3778. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3779. target = req.target;
  3780. res.status = StatusCode::OK_200;
  3781. return Server::HandlerResponse::Handled;
  3782. });
  3783. auto port = svr.bind_to_any_port(HOST);
  3784. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3785. auto se = detail::scope_exit([&] {
  3786. svr.stop();
  3787. thread.join();
  3788. ASSERT_FALSE(svr.is_running());
  3789. });
  3790. svr.wait_until_ready();
  3791. {
  3792. Client cli(HOST, port);
  3793. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3794. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3795. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3796. }
  3797. }
  3798. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3799. // Every control character is percent-encoded, not just CR/LF, so the target
  3800. // passes the request-target check in write_request_line.
  3801. Server svr;
  3802. std::string target;
  3803. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3804. target = req.target;
  3805. res.status = StatusCode::OK_200;
  3806. return Server::HandlerResponse::Handled;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. Client cli(HOST, port);
  3818. auto res = cli.Get("/a\tb\x1b\x7f");
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ("/a%09b%1B%7F", target);
  3821. }
  3822. }
  3823. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3824. // Nothing may reach the wire: a raw CR/LF target would split the request
  3825. // line and inject headers.
  3826. Server svr;
  3827. // Pre-routing so that "not called" means nothing reached the server at all,
  3828. // rather than merely failing to match a handler pattern.
  3829. auto handler_called = false;
  3830. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3831. handler_called = true;
  3832. res.status = StatusCode::OK_200;
  3833. return Server::HandlerResponse::Handled;
  3834. });
  3835. auto port = svr.bind_to_any_port(HOST);
  3836. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. {
  3844. Client cli(HOST, port);
  3845. cli.set_path_encode(false);
  3846. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3847. EXPECT_FALSE(handle.is_valid());
  3848. EXPECT_EQ(Error::Write, handle.error);
  3849. EXPECT_FALSE(handler_called);
  3850. }
  3851. }
  3852. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3853. // Which of the two branches runs is decided by whether the query component
  3854. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3855. // an empty query and must still fall back to building one from
  3856. // `req.params`, while a non-empty query must win over `req.params`.
  3857. Server svr;
  3858. std::string target;
  3859. svr.Get("/foo", [&](const Request &req, Response &res) {
  3860. target = req.target;
  3861. res.status = StatusCode::OK_200;
  3862. });
  3863. auto port = svr.bind_to_any_port(HOST);
  3864. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3865. auto se = detail::scope_exit([&] {
  3866. svr.stop();
  3867. thread.join();
  3868. ASSERT_FALSE(svr.is_running());
  3869. });
  3870. svr.wait_until_ready();
  3871. {
  3872. // Trailing `?` -> empty query component -> `req.params` is used.
  3873. Client cli(HOST, port);
  3874. Request req;
  3875. req.method = "GET";
  3876. req.path = "/foo?";
  3877. req.params.emplace("a", "1");
  3878. target.clear();
  3879. auto res = cli.send(req);
  3880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3881. EXPECT_EQ("/foo?a=1", target);
  3882. }
  3883. {
  3884. // Non-empty query in `req.path` -> `req.params` is not appended.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?b=2";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?b=2", target);
  3894. }
  3895. }
  3896. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3897. Server svr;
  3898. svr.Get("/", [](const Request &req, Response &) {
  3899. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3900. });
  3901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3902. auto se = detail::scope_exit([&] {
  3903. svr.stop();
  3904. thread.join();
  3905. ASSERT_FALSE(svr.is_running());
  3906. });
  3907. svr.wait_until_ready();
  3908. {
  3909. Client cli(HOST, PORT);
  3910. cli.set_path_encode(false);
  3911. auto res = cli.Get("/?something=%0A");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::OK_200, res->status);
  3914. }
  3915. }
  3916. TEST(BindServerTest, BindDualStack) {
  3917. Server svr;
  3918. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3919. res.set_content("Hello World!", "text/plain");
  3920. });
  3921. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3922. auto se = detail::scope_exit([&] {
  3923. svr.stop();
  3924. thread.join();
  3925. ASSERT_FALSE(svr.is_running());
  3926. });
  3927. svr.wait_until_ready();
  3928. {
  3929. Client cli("127.0.0.1", PORT);
  3930. auto res = cli.Get("/1");
  3931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3932. EXPECT_EQ(StatusCode::OK_200, res->status);
  3933. EXPECT_EQ("Hello World!", res->body);
  3934. }
  3935. {
  3936. Client cli("::1", PORT);
  3937. auto res = cli.Get("/1");
  3938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3939. EXPECT_EQ(StatusCode::OK_200, res->status);
  3940. EXPECT_EQ("Hello World!", res->body);
  3941. }
  3942. }
  3943. TEST(BindServerTest, BindAndListenSeparately) {
  3944. Server svr;
  3945. int port = svr.bind_to_any_port("0.0.0.0");
  3946. ASSERT_TRUE(svr.is_valid());
  3947. ASSERT_TRUE(port > 0);
  3948. svr.stop();
  3949. }
  3950. // Reports whether anything is still listening on a loopback port. A plain
  3951. // connect() is used instead of a Client request because a socket left bound by
  3952. // mistake accepts the connection into its backlog and never answers, which
  3953. // would hang the test instead of failing it.
  3954. static bool is_loopback_port_accepting(int port) {
  3955. sockaddr_in addr{};
  3956. addr.sin_family = AF_INET;
  3957. addr.sin_port = htons(static_cast<uint16_t>(port));
  3958. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3959. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3960. EXPECT_NE(sock, INVALID_SOCKET);
  3961. if (sock == INVALID_SOCKET) { return false; }
  3962. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3963. static_cast<socklen_t>(sizeof(addr)));
  3964. detail::close_socket(sock);
  3965. return ret == 0;
  3966. }
  3967. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3968. Server svr;
  3969. auto port = svr.bind_to_any_port("127.0.0.1");
  3970. ASSERT_TRUE(port > 0);
  3971. svr.stop();
  3972. // bind_to_any_port() already called listen(2), so until stop() closed the
  3973. // descriptor the port kept accepting connections into the backlog. ASSERT
  3974. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3975. // below blocks forever in the accept loop.
  3976. ASSERT_FALSE(is_loopback_port_accepting(port));
  3977. // Nothing is left to accept on, so listen_after_bind() must report failure
  3978. // instead of returning success without ever serving.
  3979. EXPECT_FALSE(svr.listen_after_bind());
  3980. // The failed listen marks the server decommissioned, so a waiter returns
  3981. // instead of spinning forever.
  3982. svr.wait_until_ready();
  3983. }
  3984. #ifdef CPPHTTPLIB_SSL_ENABLED
  3985. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3987. CLIENT_CA_CERT_DIR);
  3988. int port = svr.bind_to_any_port("0.0.0.0");
  3989. ASSERT_TRUE(svr.is_valid());
  3990. ASSERT_TRUE(port > 0);
  3991. svr.stop();
  3992. }
  3993. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3994. // or a rejected CustomRoute() registration would not stop the server binding.
  3995. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3997. CLIENT_CA_CERT_DIR);
  3998. ASSERT_TRUE(svr.is_valid());
  3999. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4000. EXPECT_FALSE(svr.is_valid());
  4001. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4002. }
  4003. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4004. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4005. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4006. int port = svr.bind_to_any_port("0.0.0.0");
  4007. ASSERT_TRUE(svr.is_valid());
  4008. ASSERT_TRUE(port > 0);
  4009. svr.stop();
  4010. }
  4011. TEST(BindServerTest, UpdateCertsPem) {
  4012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4013. int port = svr.bind_to_any_port("0.0.0.0");
  4014. ASSERT_TRUE(svr.is_valid());
  4015. ASSERT_TRUE(port > 0);
  4016. // Read PEM files
  4017. std::string cert_pem, key_pem, ca_pem;
  4018. read_file(SERVER_CERT_FILE, cert_pem);
  4019. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4020. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4021. // Update server certificates using PEM API
  4022. ASSERT_TRUE(
  4023. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4024. ASSERT_TRUE(svr.is_valid());
  4025. svr.stop();
  4026. }
  4027. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4028. // Start server with client CA (enables client auth)
  4029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4030. ASSERT_TRUE(svr.is_valid());
  4031. bool handler_called = false;
  4032. svr.Get("/test", [&](const Request &req, Response &res) {
  4033. handler_called = true;
  4034. // Verify client certificate is present
  4035. auto cert = req.peer_cert();
  4036. EXPECT_TRUE(static_cast<bool>(cert));
  4037. res.set_content("ok", "text/plain");
  4038. });
  4039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. t.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. // Read PEM files
  4047. std::string cert_pem, key_pem, ca_pem;
  4048. read_file(SERVER_CERT_FILE, cert_pem);
  4049. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4050. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4051. // Update server certificates and client CA using PEM API while server running
  4052. ASSERT_TRUE(
  4053. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4054. // Connect with client certificate
  4055. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4056. cli.enable_server_certificate_verification(false);
  4057. cli.set_connection_timeout(30);
  4058. auto res = cli.Get("/test");
  4059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4060. ASSERT_EQ(StatusCode::OK_200, res->status);
  4061. ASSERT_TRUE(handler_called);
  4062. EXPECT_EQ("ok", res->body);
  4063. }
  4064. // Puts a CA that did not sign the client's certificate in the old one's place.
  4065. static bool replace_client_ca(SSLServer &svr) {
  4066. std::string cert_pem, key_pem, ca_pem;
  4067. read_file(SERVER_CERT_FILE, cert_pem);
  4068. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4069. read_file(SERVER_CERT2_FILE, ca_pem);
  4070. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4071. ca_pem.c_str());
  4072. }
  4073. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4075. ASSERT_TRUE(svr.is_valid());
  4076. svr.Get("/test", [](const Request &, Response &res) {
  4077. res.set_content("ok", "text/plain");
  4078. });
  4079. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. t.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. auto get = [] {
  4087. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4088. cli.enable_server_certificate_verification(false);
  4089. return cli.Get("/test");
  4090. };
  4091. ASSERT_TRUE(get());
  4092. ASSERT_TRUE(replace_client_ca(svr));
  4093. EXPECT_FALSE(get());
  4094. }
  4095. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4096. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4098. ASSERT_TRUE(svr.is_valid());
  4099. tls::set_verify_callback(svr.tls_context(),
  4100. [](const tls::VerifyContext &) -> bool {
  4101. throw std::runtime_error("verify");
  4102. });
  4103. svr.Get("/test", [](const Request &, Response &res) {
  4104. res.set_content("ok", "text/plain");
  4105. });
  4106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4107. auto se = detail::scope_exit([&] {
  4108. svr.stop();
  4109. t.join();
  4110. ASSERT_FALSE(svr.is_running());
  4111. });
  4112. svr.wait_until_ready();
  4113. auto get = [] {
  4114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4115. cli.enable_server_certificate_verification(false);
  4116. return cli.Get("/test");
  4117. };
  4118. EXPECT_FALSE(get());
  4119. // The handshake is over, so an update does not wait for it.
  4120. std::string cert_pem, key_pem;
  4121. read_file(SERVER_CERT_FILE, cert_pem);
  4122. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4123. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4124. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4125. return v.preverify_ok;
  4126. });
  4127. auto res = get();
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ("ok", res->body);
  4130. }
  4131. #endif
  4132. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4133. // Sends each request over a new connection with a client certificate,
  4134. // resuming the session of the one before when there is one.
  4135. class ResumingClient {
  4136. public:
  4137. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4138. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4139. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4140. SSL_FILETYPE_PEM);
  4141. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4142. // callback, not through SSL_get1_session().
  4143. SSL_CTX_set_app_data(ctx_, this);
  4144. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4145. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4146. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4147. auto self = static_cast<ResumingClient *>(
  4148. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4149. SSL_SESSION_free(self->session_);
  4150. self->session_ = session;
  4151. return 1; // Keeps the reference
  4152. });
  4153. }
  4154. ~ResumingClient() {
  4155. SSL_SESSION_free(session_);
  4156. SSL_CTX_free(ctx_);
  4157. }
  4158. // Tells whether the request was answered.
  4159. bool get() {
  4160. auto error = Error::Success;
  4161. auto sock = detail::create_client_socket(
  4162. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4163. /*connection_timeout_sec=*/5, 0,
  4164. /*read_timeout_sec=*/5, 0,
  4165. /*write_timeout_sec=*/5, 0, std::string(), error);
  4166. if (sock == INVALID_SOCKET) { return false; }
  4167. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4168. auto ssl = SSL_new(ctx_);
  4169. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4170. SSL_set_fd(ssl, static_cast<int>(sock));
  4171. if (session_) { SSL_set_session(ssl, session_); }
  4172. if (SSL_connect(ssl) != 1) { return false; }
  4173. reused_ = SSL_session_reused(ssl) == 1;
  4174. // Reading the response also takes in a TLS 1.3 session ticket.
  4175. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4176. "Connection: close\r\n\r\n";
  4177. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4178. std::string res;
  4179. char buf[256];
  4180. int n;
  4181. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4182. res.append(buf, static_cast<size_t>(n));
  4183. }
  4184. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4185. SSL_shutdown(ssl);
  4186. return res.find("200 OK") != std::string::npos;
  4187. }
  4188. // Whether the last connection resumed a session
  4189. bool reused() const { return reused_; }
  4190. private:
  4191. SSL_CTX *ctx_;
  4192. SSL_SESSION *session_ = nullptr;
  4193. bool reused_ = false;
  4194. };
  4195. // A client that resumes its session gets through, but not once the client CA
  4196. // has changed, as a resumed session does not show the certificate again.
  4197. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4199. ASSERT_TRUE(svr.is_valid());
  4200. svr.Get("/test", [](const Request &, Response &res) {
  4201. res.set_content("ok", "text/plain");
  4202. });
  4203. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. t.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. ResumingClient cli;
  4211. ASSERT_TRUE(cli.get());
  4212. ASSERT_TRUE(cli.get());
  4213. EXPECT_TRUE(cli.reused());
  4214. ASSERT_TRUE(replace_client_ca(svr));
  4215. EXPECT_FALSE(cli.get());
  4216. }
  4217. // A resumed session does not show the certificate again, so the server does
  4218. // not resume one with a verify callback to run on it.
  4219. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4221. ASSERT_TRUE(svr.is_valid());
  4222. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4223. return v.preverify_ok;
  4224. });
  4225. svr.Get("/test", [](const Request &, Response &res) {
  4226. res.set_content("ok", "text/plain");
  4227. });
  4228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4229. auto se = detail::scope_exit([&] {
  4230. svr.stop();
  4231. t.join();
  4232. ASSERT_FALSE(svr.is_running());
  4233. });
  4234. svr.wait_until_ready();
  4235. ResumingClient cli;
  4236. ASSERT_TRUE(cli.get());
  4237. ASSERT_TRUE(cli.get());
  4238. EXPECT_FALSE(cli.reused());
  4239. }
  4240. #endif
  4241. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4242. // wolfSSL shares its session cache between contexts, so a resumed session
  4243. // could carry a client certificate checked against another server's CA, or
  4244. // against a client CA since replaced.
  4245. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4247. ASSERT_TRUE(svr.is_valid());
  4248. // Trusts a CA that did not sign the client's certificate.
  4249. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4250. ASSERT_TRUE(other.is_valid());
  4251. for (auto s : {&svr, &other}) {
  4252. s->Get("/test", [](const Request &, Response &res) {
  4253. res.set_content("ok", "text/plain");
  4254. });
  4255. }
  4256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4257. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4258. auto se = detail::scope_exit([&] {
  4259. other.stop();
  4260. svr.stop();
  4261. t2.join();
  4262. t.join();
  4263. });
  4264. svr.wait_until_ready();
  4265. other.wait_until_ready();
  4266. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4267. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4268. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4269. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4270. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4271. ASSERT_EQ(WOLFSSL_SUCCESS,
  4272. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4273. WOLFSSL_FILETYPE_PEM));
  4274. WOLFSSL_SESSION *session = nullptr;
  4275. auto session_se = detail::scope_exit([&] {
  4276. if (session) { wolfSSL_SESSION_free(session); }
  4277. });
  4278. // A request over a new connection, resuming `session` when there is one and
  4279. // keeping the connection's own in its place. Tells whether it was answered.
  4280. auto get = [&](int port) {
  4281. auto error = Error::Success;
  4282. auto sock = detail::create_client_socket(
  4283. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4284. /*connection_timeout_sec=*/5, 0,
  4285. /*read_timeout_sec=*/5, 0,
  4286. /*write_timeout_sec=*/5, 0, std::string(), error);
  4287. if (sock == INVALID_SOCKET) { return false; }
  4288. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4289. auto ssl = wolfSSL_new(ctx);
  4290. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4291. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4292. if (session) { wolfSSL_set_session(ssl, session); }
  4293. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4294. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4295. "Connection: close\r\n\r\n";
  4296. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4297. std::string res;
  4298. char buf[256];
  4299. int n;
  4300. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4301. res.append(buf, static_cast<size_t>(n));
  4302. }
  4303. wolfSSL_shutdown(ssl);
  4304. if (session) { wolfSSL_SESSION_free(session); }
  4305. session = wolfSSL_get1_session(ssl);
  4306. return res.find("200 OK") != std::string::npos;
  4307. };
  4308. ASSERT_TRUE(get(PORT));
  4309. EXPECT_FALSE(get(PORT + 1));
  4310. ASSERT_TRUE(get(PORT));
  4311. ASSERT_TRUE(replace_client_ca(svr));
  4312. EXPECT_FALSE(get(PORT));
  4313. }
  4314. #endif
  4315. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4317. ASSERT_TRUE(svr.is_valid());
  4318. svr.Get("/test", [](const Request &, Response &res) {
  4319. res.set_content("ok", "text/plain");
  4320. });
  4321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4322. auto se = detail::scope_exit([&] {
  4323. svr.stop();
  4324. t.join();
  4325. ASSERT_FALSE(svr.is_running());
  4326. });
  4327. svr.wait_until_ready();
  4328. // A connection that sends no ClientHello keeps its handshake in progress,
  4329. // once the server has had a moment to start it.
  4330. auto error = Error::Success;
  4331. auto sock = detail::create_client_socket(
  4332. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4333. /*connection_timeout_sec=*/5, 0,
  4334. /*read_timeout_sec=*/5, 0,
  4335. /*write_timeout_sec=*/5, 0, std::string(), error);
  4336. ASSERT_NE(INVALID_SOCKET, sock);
  4337. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4338. std::string cert_pem, key_pem;
  4339. read_file(SERVER_CERT_FILE, cert_pem);
  4340. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4341. auto update = std::async(std::launch::async, [&]() {
  4342. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4343. });
  4344. EXPECT_EQ(std::future_status::timeout,
  4345. update.wait_for(std::chrono::milliseconds(200)));
  4346. detail::close_socket(sock);
  4347. EXPECT_TRUE(update.get());
  4348. SSLClient cli(HOST, PORT);
  4349. cli.enable_server_certificate_verification(false);
  4350. auto res = cli.Get("/test");
  4351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. }
  4354. #endif
  4355. TEST(ErrorHandlerTest, ContentLength) {
  4356. Server svr;
  4357. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4358. res.status = StatusCode::OK_200;
  4359. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4360. "text/html"); // <= Content-Length still 13
  4361. });
  4362. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4363. res.set_content("Hello World!\n", "text/plain");
  4364. res.status = 524;
  4365. });
  4366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4367. auto se = detail::scope_exit([&] {
  4368. svr.stop();
  4369. thread.join();
  4370. ASSERT_FALSE(svr.is_running());
  4371. });
  4372. svr.wait_until_ready();
  4373. {
  4374. Client cli(HOST, PORT);
  4375. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4379. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4380. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4381. }
  4382. }
  4383. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4384. TEST(ExceptionTest, WithoutExceptionHandler) {
  4385. Server svr;
  4386. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4387. throw std::runtime_error("exception...");
  4388. });
  4389. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4390. throw std::runtime_error("exception\r\n...");
  4391. });
  4392. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4393. auto se = detail::scope_exit([&] {
  4394. svr.stop();
  4395. listen_thread.join();
  4396. ASSERT_FALSE(svr.is_running());
  4397. });
  4398. svr.wait_until_ready();
  4399. Client cli("localhost", PORT);
  4400. {
  4401. auto res = cli.Get("/exception");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4404. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4405. }
  4406. {
  4407. auto res = cli.Get("/unknown");
  4408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4409. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4410. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4411. }
  4412. }
  4413. TEST(ExceptionTest, WithExceptionHandler) {
  4414. Server svr;
  4415. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4416. std::exception_ptr ep) {
  4417. EXPECT_FALSE(ep == nullptr);
  4418. try {
  4419. std::rethrow_exception(ep);
  4420. } catch (std::exception &e) {
  4421. EXPECT_EQ("abc", std::string(e.what()));
  4422. } catch (...) {}
  4423. res.status = StatusCode::InternalServerError_500;
  4424. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4425. "text/html"); // <= Content-Length still 13 at this point
  4426. });
  4427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("Hello World!\n", "text/plain");
  4429. throw std::runtime_error("abc");
  4430. });
  4431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. for (size_t i = 0; i < 10; i++) {
  4439. Client cli(HOST, PORT);
  4440. for (size_t j = 0; j < 100; j++) {
  4441. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4443. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4444. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4445. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4446. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4447. }
  4448. cli.set_keep_alive(true);
  4449. for (size_t j = 0; j < 100; j++) {
  4450. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4453. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4454. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4455. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4456. }
  4457. }
  4458. }
  4459. TEST(ExceptionTest, AndErrorHandler) {
  4460. Server svr;
  4461. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4462. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4463. });
  4464. svr.set_exception_handler(
  4465. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4466. EXPECT_FALSE(ep == nullptr);
  4467. try {
  4468. std::rethrow_exception(ep);
  4469. } catch (std::exception &e) {
  4470. res.set_content(e.what(), "text/html");
  4471. } catch (...) {}
  4472. res.status = StatusCode::InternalServerError_500;
  4473. });
  4474. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4475. throw std::runtime_error("EXCEPTION");
  4476. });
  4477. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4478. res.set_content("ERROR", "text/html");
  4479. res.status = StatusCode::InternalServerError_500;
  4480. });
  4481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4482. auto se = detail::scope_exit([&] {
  4483. svr.stop();
  4484. thread.join();
  4485. ASSERT_FALSE(svr.is_running());
  4486. });
  4487. svr.wait_until_ready();
  4488. Client cli(HOST, PORT);
  4489. {
  4490. auto res = cli.Get("/exception");
  4491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4492. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4493. EXPECT_EQ("EXCEPTION", res->body);
  4494. }
  4495. {
  4496. auto res = cli.Get("/error");
  4497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4498. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4499. EXPECT_EQ("ERROR", res->body);
  4500. }
  4501. {
  4502. auto res = cli.Get("/invalid");
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4505. EXPECT_EQ("NOT_FOUND", res->body);
  4506. }
  4507. }
  4508. #endif
  4509. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4510. // process_request() wraps only routing() in a try/catch, so an exception from
  4511. // any other user callback used to unwind into the task queue - which does not
  4512. // catch - and terminate the process. Each test below runs the server on a
  4513. // single worker thread: a guard that catches the exception but still loses the
  4514. // thread would otherwise be hidden by a spare worker serving the follow-up
  4515. // request. Note that a regression here aborts the whole test binary rather
  4516. // than failing one test.
  4517. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4518. Server svr;
  4519. svr.new_task_queue = [] { return new ThreadPool(1); };
  4520. std::atomic<int> reported{0};
  4521. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4522. if (err == Error::UserCallbackException) { reported++; }
  4523. });
  4524. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4525. res.set_content_provider(
  4526. 1024, "text/plain",
  4527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4528. sink.write("hello", 5);
  4529. throw std::runtime_error("from the content provider");
  4530. });
  4531. });
  4532. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4533. res.set_content("ok", "text/plain");
  4534. });
  4535. auto port = svr.bind_to_any_port(HOST);
  4536. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4537. auto se = detail::scope_exit([&] {
  4538. svr.stop();
  4539. listen_thread.join();
  4540. ASSERT_FALSE(svr.is_running());
  4541. });
  4542. svr.wait_until_ready();
  4543. {
  4544. Client cli(HOST, port);
  4545. cli.set_read_timeout(5, 0);
  4546. EXPECT_FALSE(cli.Get("/throw"));
  4547. }
  4548. EXPECT_TRUE(svr.is_running());
  4549. EXPECT_EQ(1, reported.load());
  4550. // A request on a fresh connection is still served.
  4551. {
  4552. Client cli(HOST, port);
  4553. auto res = cli.Get("/ok");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::OK_200, res->status);
  4556. EXPECT_EQ("ok", res->body);
  4557. }
  4558. }
  4559. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4560. Server svr;
  4561. svr.new_task_queue = [] { return new ThreadPool(1); };
  4562. std::atomic<bool> should_throw{true};
  4563. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4564. res.set_content("hi", "text/plain");
  4565. });
  4566. svr.set_post_routing_handler(
  4567. [&](const Request & /*req*/, Response & /*res*/) {
  4568. if (should_throw) {
  4569. throw std::runtime_error("from the post-routing handler");
  4570. }
  4571. });
  4572. auto port = svr.bind_to_any_port(HOST);
  4573. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4574. auto se = detail::scope_exit([&] {
  4575. svr.stop();
  4576. listen_thread.join();
  4577. ASSERT_FALSE(svr.is_running());
  4578. });
  4579. svr.wait_until_ready();
  4580. {
  4581. Client cli(HOST, port);
  4582. cli.set_read_timeout(5, 0);
  4583. EXPECT_FALSE(cli.Get("/hi"));
  4584. }
  4585. EXPECT_TRUE(svr.is_running());
  4586. should_throw = false;
  4587. {
  4588. Client cli(HOST, port);
  4589. auto res = cli.Get("/hi");
  4590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ("hi", res->body);
  4593. }
  4594. }
  4595. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4596. // The guard reports the caught exception through the error logger, which is
  4597. // a user callback too. A logger that throws has to be contained as well, or
  4598. // the process would terminate from inside the catch.
  4599. Server svr;
  4600. svr.new_task_queue = [] { return new ThreadPool(1); };
  4601. std::atomic<int> reported{0};
  4602. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4603. if (err == Error::UserCallbackException) {
  4604. reported++;
  4605. throw std::runtime_error("from the error logger");
  4606. }
  4607. });
  4608. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4609. res.set_content_provider(
  4610. 1024, "text/plain",
  4611. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4612. sink.write("hello", 5);
  4613. throw std::runtime_error("from the content provider");
  4614. });
  4615. });
  4616. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4617. res.set_content("ok", "text/plain");
  4618. });
  4619. auto port = svr.bind_to_any_port(HOST);
  4620. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4621. auto se = detail::scope_exit([&] {
  4622. svr.stop();
  4623. listen_thread.join();
  4624. ASSERT_FALSE(svr.is_running());
  4625. });
  4626. svr.wait_until_ready();
  4627. {
  4628. Client cli(HOST, port);
  4629. cli.set_read_timeout(5, 0);
  4630. EXPECT_FALSE(cli.Get("/throw"));
  4631. }
  4632. EXPECT_TRUE(svr.is_running());
  4633. EXPECT_EQ(1, reported.load());
  4634. {
  4635. Client cli(HOST, port);
  4636. auto res = cli.Get("/ok");
  4637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. EXPECT_EQ("ok", res->body);
  4640. }
  4641. }
  4642. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4643. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4644. // so the exception unwinds through the ws::WebSocket object on its way to
  4645. // the guard. None of the HTTP cases above cross that.
  4646. Server svr;
  4647. svr.new_task_queue = [] { return new ThreadPool(1); };
  4648. std::atomic<int> reported{0};
  4649. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4650. if (err == Error::UserCallbackException) { reported++; }
  4651. });
  4652. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4653. throw std::runtime_error("from the WebSocket handler");
  4654. });
  4655. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4656. res.set_content("ok", "text/plain");
  4657. });
  4658. auto port = svr.bind_to_any_port(HOST);
  4659. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4660. auto se = detail::scope_exit([&] {
  4661. svr.stop();
  4662. listen_thread.join();
  4663. ASSERT_FALSE(svr.is_running());
  4664. });
  4665. svr.wait_until_ready();
  4666. {
  4667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4668. "/ws");
  4669. auto res = client.connect();
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. // The server dropped the connection instead of dying.
  4672. std::string msg;
  4673. EXPECT_FALSE(client.read(msg));
  4674. client.close();
  4675. }
  4676. EXPECT_TRUE(svr.is_running());
  4677. EXPECT_EQ(1, reported.load());
  4678. {
  4679. Client cli(HOST, port);
  4680. auto res = cli.Get("/ok");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ(StatusCode::OK_200, res->status);
  4683. EXPECT_EQ("ok", res->body);
  4684. }
  4685. }
  4686. #ifdef CPPHTTPLIB_SSL_ENABLED
  4687. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4688. // SSLServer::process_and_close_socket() is a separate overload with its own
  4689. // guard, so it is exercised on its own.
  4690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4691. ASSERT_TRUE(svr.is_valid());
  4692. svr.new_task_queue = [] { return new ThreadPool(1); };
  4693. std::atomic<int> reported{0};
  4694. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4695. if (err == Error::UserCallbackException) { reported++; }
  4696. });
  4697. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4698. res.set_content_provider(
  4699. 1024, "text/plain",
  4700. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4701. sink.write("hello", 5);
  4702. throw std::runtime_error("from the content provider");
  4703. });
  4704. });
  4705. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4706. res.set_content("ok", "text/plain");
  4707. });
  4708. auto port = svr.bind_to_any_port(HOST);
  4709. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. listen_thread.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. {
  4717. SSLClient cli(HOST, port);
  4718. cli.enable_server_certificate_verification(false);
  4719. cli.set_read_timeout(5, 0);
  4720. EXPECT_FALSE(cli.Get("/throw"));
  4721. }
  4722. EXPECT_TRUE(svr.is_running());
  4723. EXPECT_EQ(1, reported.load());
  4724. {
  4725. SSLClient cli(HOST, port);
  4726. cli.enable_server_certificate_verification(false);
  4727. auto res = cli.Get("/ok");
  4728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("ok", res->body);
  4731. }
  4732. }
  4733. #endif
  4734. #endif
  4735. TEST(NoContentTest, ContentLength) {
  4736. Server svr;
  4737. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4738. res.status = StatusCode::NoContent_204;
  4739. });
  4740. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4741. auto se = detail::scope_exit([&] {
  4742. svr.stop();
  4743. thread.join();
  4744. ASSERT_FALSE(svr.is_running());
  4745. });
  4746. svr.wait_until_ready();
  4747. {
  4748. Client cli(HOST, PORT);
  4749. auto res = cli.Get("/hi");
  4750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4751. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4752. // RFC 9110 8.6: none in a 204 response
  4753. EXPECT_FALSE(res->has_header("Content-Length"));
  4754. }
  4755. }
  4756. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4757. Server svr;
  4758. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4759. res.set_header("Content-Length", "5");
  4760. res.set_content("hello world", "text/plain");
  4761. });
  4762. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4763. // A body that reads as the last chunk, were it taken as chunked
  4764. res.set_header("Transfer-Encoding", "chunked");
  4765. res.set_content("0\r\n\r\n", "text/plain");
  4766. });
  4767. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4768. res.set_header("Content-Length", "2");
  4769. res.set_content_provider(5, "text/plain",
  4770. [](size_t offset, size_t length, DataSink &sink) {
  4771. sink.write(&"hello"[offset], length);
  4772. return true;
  4773. });
  4774. });
  4775. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4776. res.set_header("Content-Length", "1234");
  4777. });
  4778. thread t = thread([&] { svr.listen(HOST, PORT); });
  4779. auto se = detail::scope_exit([&] {
  4780. svr.stop();
  4781. t.join();
  4782. ASSERT_FALSE(svr.is_running());
  4783. });
  4784. svr.wait_until_ready();
  4785. Client cli(HOST, PORT);
  4786. cli.set_read_timeout(1, 0);
  4787. auto expect_body = [&](const Result &res, const std::string &body) {
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(body, res->body);
  4790. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4791. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4792. };
  4793. Headers identity{{"Accept-Encoding", ""}};
  4794. expect_body(cli.Get("/body", identity), "hello world");
  4795. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4796. expect_body(cli.Get("/body",
  4797. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4798. "he");
  4799. expect_body(cli.Get("/provider", identity), "hello");
  4800. expect_body(cli.Get("/empty", identity), "");
  4801. // A HEAD response may give the length of the body a GET would get.
  4802. auto res = cli.Head("/empty");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4805. }
  4806. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4807. Server svr;
  4808. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4809. res.set_content("short", "text/plain");
  4810. });
  4811. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4812. res.body += " with a footer";
  4813. res.set_header("Transfer-Encoding", "chunked");
  4814. });
  4815. thread t = thread([&] { svr.listen(HOST, PORT); });
  4816. auto se = detail::scope_exit([&] {
  4817. svr.stop();
  4818. t.join();
  4819. ASSERT_FALSE(svr.is_running());
  4820. });
  4821. svr.wait_until_ready();
  4822. Client cli(HOST, PORT);
  4823. cli.set_read_timeout(1, 0);
  4824. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. EXPECT_EQ("short with a footer", res->body);
  4827. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4828. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4829. }
  4830. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4831. Server svr;
  4832. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4833. res.set_header("Content-Length", "3");
  4834. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4835. sink.write("abc", 3);
  4836. sink.done();
  4837. return true;
  4838. });
  4839. });
  4840. thread t = thread([&] { svr.listen(HOST, PORT); });
  4841. auto se = detail::scope_exit([&] {
  4842. svr.stop();
  4843. t.join();
  4844. ASSERT_FALSE(svr.is_running());
  4845. });
  4846. svr.wait_until_ready();
  4847. Client cli(HOST, PORT);
  4848. cli.set_keep_alive(true);
  4849. auto res = cli.Get("/");
  4850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4851. EXPECT_EQ("abc", res->body);
  4852. EXPECT_FALSE(res->has_header("Content-Length"));
  4853. EXPECT_EQ("close", res->get_header_value("Connection"));
  4854. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4855. // No body to delimit
  4856. auto head = cli.Head("/");
  4857. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4858. EXPECT_FALSE(head->has_header("Connection"));
  4859. }
  4860. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4861. #ifdef CPPHTTPLIB_SSL_ENABLED
  4862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4863. ASSERT_TRUE(svr.is_valid());
  4864. #else
  4865. Server svr;
  4866. #endif
  4867. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4868. if (req.path == "/routing_handler") {
  4869. res.set_header("PRE_ROUTING", "on");
  4870. res.set_content("Routing Handler", "text/plain");
  4871. return httplib::Server::HandlerResponse::Handled;
  4872. }
  4873. return httplib::Server::HandlerResponse::Unhandled;
  4874. });
  4875. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4876. res.set_content("Error", "text/html");
  4877. });
  4878. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4879. if (req.path == "/routing_handler") {
  4880. res.set_header("POST_ROUTING", "on");
  4881. }
  4882. });
  4883. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4884. res.set_content("Hello World!\n", "text/plain");
  4885. });
  4886. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4887. auto se = detail::scope_exit([&] {
  4888. svr.stop();
  4889. thread.join();
  4890. ASSERT_FALSE(svr.is_running());
  4891. });
  4892. svr.wait_until_ready();
  4893. {
  4894. #ifdef CPPHTTPLIB_SSL_ENABLED
  4895. SSLClient cli(HOST, PORT);
  4896. cli.enable_server_certificate_verification(false);
  4897. #else
  4898. Client cli(HOST, PORT);
  4899. #endif
  4900. auto res = cli.Get("/routing_handler");
  4901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4902. EXPECT_EQ(StatusCode::OK_200, res->status);
  4903. EXPECT_EQ("Routing Handler", res->body);
  4904. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4905. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4906. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4907. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4908. }
  4909. {
  4910. #ifdef CPPHTTPLIB_SSL_ENABLED
  4911. SSLClient cli(HOST, PORT);
  4912. cli.enable_server_certificate_verification(false);
  4913. #else
  4914. Client cli(HOST, PORT);
  4915. #endif
  4916. auto res = cli.Get("/hi");
  4917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("Hello World!\n", res->body);
  4920. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4921. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4922. }
  4923. {
  4924. #ifdef CPPHTTPLIB_SSL_ENABLED
  4925. SSLClient cli(HOST, PORT);
  4926. cli.enable_server_certificate_verification(false);
  4927. #else
  4928. Client cli(HOST, PORT);
  4929. #endif
  4930. auto res = cli.Get("/aaa");
  4931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4932. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4933. EXPECT_EQ("Error", res->body);
  4934. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4935. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4936. }
  4937. }
  4938. TEST(RequestHandlerTest, PreRequestHandler) {
  4939. auto route_path = "/user/:user";
  4940. Server svr;
  4941. svr.Get("/hi", [](const Request &, Response &res) {
  4942. res.set_content("hi", "text/plain");
  4943. });
  4944. svr.Get(route_path, [](const Request &req, Response &res) {
  4945. res.set_content(req.path_params.at("user"), "text/plain");
  4946. });
  4947. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4948. if (req.matched_route == route_path) {
  4949. auto user = req.path_params.at("user");
  4950. if (user != "john") {
  4951. res.status = StatusCode::Forbidden_403;
  4952. res.set_content("error", "text/html");
  4953. return Server::HandlerResponse::Handled;
  4954. }
  4955. }
  4956. return Server::HandlerResponse::Unhandled;
  4957. });
  4958. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4959. auto se = detail::scope_exit([&] {
  4960. svr.stop();
  4961. thread.join();
  4962. ASSERT_FALSE(svr.is_running());
  4963. });
  4964. svr.wait_until_ready();
  4965. Client cli(HOST, PORT);
  4966. {
  4967. auto res = cli.Get("/hi");
  4968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("hi", res->body);
  4971. }
  4972. {
  4973. auto res = cli.Get("/user/john");
  4974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ("john", res->body);
  4977. }
  4978. {
  4979. auto res = cli.Get("/user/invalid-user");
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4982. EXPECT_EQ("error", res->body);
  4983. }
  4984. }
  4985. // The pre-request handler must run before the request body is read, so a
  4986. // rejected request never forces the server to buffer a (potentially large)
  4987. // body. Here the posted body is larger than the payload limit: if the body
  4988. // were read first the server would answer 413, but because the pre-request
  4989. // handler runs first it answers 403 and the body is never read.
  4990. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4991. Server svr;
  4992. svr.set_payload_max_length(8);
  4993. auto handler_ran = false;
  4994. svr.Post("/reject", [&](const Request &req, Response &res) {
  4995. handler_ran = true;
  4996. res.set_content(req.body, "text/plain");
  4997. });
  4998. svr.Post("/accept", [](const Request &req, Response &res) {
  4999. res.set_content(req.body, "text/plain");
  5000. });
  5001. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5002. if (req.matched_route == "/reject") {
  5003. res.status = StatusCode::Forbidden_403;
  5004. res.set_content("denied", "text/plain");
  5005. return Server::HandlerResponse::Handled;
  5006. }
  5007. return Server::HandlerResponse::Unhandled;
  5008. });
  5009. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5010. auto se = detail::scope_exit([&] {
  5011. svr.stop();
  5012. thread.join();
  5013. ASSERT_FALSE(svr.is_running());
  5014. });
  5015. svr.wait_until_ready();
  5016. Client cli(HOST, PORT);
  5017. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5018. // rejects with 403 before the body is read, so 413 is never reached.
  5019. {
  5020. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5022. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5023. EXPECT_EQ("denied", res->body);
  5024. EXPECT_FALSE(handler_ran);
  5025. }
  5026. // An approved route still reads the body and enforces the payload limit.
  5027. {
  5028. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5030. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5031. }
  5032. }
  5033. TEST(UserDataTest, BasicOperations) {
  5034. httplib::UserData ud;
  5035. // Initially empty
  5036. EXPECT_FALSE(ud.has("key"));
  5037. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5038. // set and get
  5039. ud.set("key", 42);
  5040. EXPECT_TRUE(ud.has("key"));
  5041. auto *p = ud.get<int>("key");
  5042. ASSERT_NE(nullptr, p);
  5043. EXPECT_EQ(42, *p);
  5044. // Type mismatch → nullptr
  5045. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5046. // Overwrite with different type
  5047. ud.set("key", std::string("hello"));
  5048. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5049. auto *s = ud.get<std::string>("key");
  5050. ASSERT_NE(nullptr, s);
  5051. EXPECT_EQ("hello", *s);
  5052. // erase
  5053. ud.erase("key");
  5054. EXPECT_FALSE(ud.has("key"));
  5055. // clear
  5056. ud.set("a", 1);
  5057. ud.set("b", 2);
  5058. ud.clear();
  5059. EXPECT_FALSE(ud.has("a"));
  5060. EXPECT_FALSE(ud.has("b"));
  5061. }
  5062. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5063. struct AuthCtx {
  5064. std::string user_id;
  5065. };
  5066. Server svr;
  5067. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5068. res.user_data.set("auth", AuthCtx{"alice"});
  5069. return Server::HandlerResponse::Unhandled;
  5070. });
  5071. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5072. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5073. ASSERT_NE(nullptr, ctx);
  5074. res.set_content("Hello " + ctx->user_id, "text/plain");
  5075. });
  5076. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5077. auto se = detail::scope_exit([&] {
  5078. svr.stop();
  5079. thread.join();
  5080. ASSERT_FALSE(svr.is_running());
  5081. });
  5082. svr.wait_until_ready();
  5083. Client cli(HOST, PORT);
  5084. auto res = cli.Get("/me");
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::OK_200, res->status);
  5087. EXPECT_EQ("Hello alice", res->body);
  5088. }
  5089. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5090. struct RoleCtx {
  5091. std::string role;
  5092. };
  5093. Server svr;
  5094. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5095. res.user_data.set("role", RoleCtx{"admin"});
  5096. return Server::HandlerResponse::Unhandled;
  5097. });
  5098. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5099. auto *ctx = res.user_data.get<RoleCtx>("role");
  5100. ASSERT_NE(nullptr, ctx);
  5101. res.set_content(ctx->role, "text/plain");
  5102. });
  5103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5104. auto se = detail::scope_exit([&] {
  5105. svr.stop();
  5106. thread.join();
  5107. ASSERT_FALSE(svr.is_running());
  5108. });
  5109. svr.wait_until_ready();
  5110. Client cli(HOST, PORT);
  5111. auto res = cli.Get("/role");
  5112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5113. EXPECT_EQ(StatusCode::OK_200, res->status);
  5114. EXPECT_EQ("admin", res->body);
  5115. }
  5116. TEST(InvalidFormatTest, StatusCode) {
  5117. Server svr;
  5118. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5119. res.set_content("Hello World!\n", "text/plain");
  5120. res.status = 9999; // Status should be a three-digit code...
  5121. });
  5122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5123. auto se = detail::scope_exit([&] {
  5124. svr.stop();
  5125. thread.join();
  5126. ASSERT_FALSE(svr.is_running());
  5127. });
  5128. svr.wait_until_ready();
  5129. {
  5130. Client cli(HOST, PORT);
  5131. auto res = cli.Get("/hi");
  5132. ASSERT_FALSE(res);
  5133. }
  5134. }
  5135. TEST(URLFragmentTest, WithFragment) {
  5136. Server svr;
  5137. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5138. EXPECT_TRUE(req.target == "/hi");
  5139. });
  5140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5141. auto se = detail::scope_exit([&] {
  5142. svr.stop();
  5143. thread.join();
  5144. ASSERT_FALSE(svr.is_running());
  5145. });
  5146. svr.wait_until_ready();
  5147. {
  5148. Client cli(HOST, PORT);
  5149. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5150. EXPECT_TRUE(res);
  5151. EXPECT_EQ(StatusCode::OK_200, res->status);
  5152. res = cli.Get("/hi%23key1=val1=key2=val2");
  5153. EXPECT_TRUE(res);
  5154. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5155. }
  5156. }
  5157. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5158. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5159. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5160. Server svr;
  5161. std::vector<std::string> targets;
  5162. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5163. targets.push_back(req.target);
  5164. });
  5165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5166. auto se = detail::scope_exit([&] {
  5167. svr.stop();
  5168. thread.join();
  5169. ASSERT_FALSE(svr.is_running());
  5170. });
  5171. svr.wait_until_ready();
  5172. Client cli(HOST, PORT);
  5173. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5175. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5176. // A '?' after the '#' belongs to the fragment, not to the query.
  5177. Request req;
  5178. req.method = "GET";
  5179. req.path = "/hi#f?x=1";
  5180. req.params.emplace("a", "1");
  5181. Response res;
  5182. auto error = Error::Success;
  5183. EXPECT_TRUE(cli.send(req, res, error));
  5184. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5185. "/hi?a=1"}),
  5186. targets);
  5187. }
  5188. TEST(HeaderWriter, SetHeaderWriter) {
  5189. Server svr;
  5190. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5191. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5192. return detail::write_headers(strm, hdrs);
  5193. });
  5194. svr.Get("/hi", [](const Request &req, Response &res) {
  5195. auto it = req.headers.find("CustomClientHeader");
  5196. EXPECT_TRUE(it != req.headers.end());
  5197. EXPECT_EQ(it->second, "CustomClientValue");
  5198. res.set_content("Hello World!\n", "text/plain");
  5199. });
  5200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5201. auto se = detail::scope_exit([&] {
  5202. svr.stop();
  5203. thread.join();
  5204. ASSERT_FALSE(svr.is_running());
  5205. });
  5206. svr.wait_until_ready();
  5207. {
  5208. Client cli(HOST, PORT);
  5209. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5210. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5211. return detail::write_headers(strm, hdrs);
  5212. });
  5213. auto res = cli.Get("/hi");
  5214. EXPECT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. auto it = res->headers.find("CustomServerHeader");
  5217. EXPECT_TRUE(it != res->headers.end());
  5218. EXPECT_EQ(it->second, "CustomServerValue");
  5219. }
  5220. }
  5221. class ServerTest : public ::testing::Test {
  5222. protected:
  5223. ServerTest()
  5224. : cli_(HOST, PORT)
  5225. #ifdef CPPHTTPLIB_SSL_ENABLED
  5226. ,
  5227. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5228. #endif
  5229. {
  5230. #ifdef CPPHTTPLIB_SSL_ENABLED
  5231. cli_.enable_server_certificate_verification(false);
  5232. #endif
  5233. // Allow LARGE_DATA (100MB) responses
  5234. cli_.set_payload_max_length(200 * 1024 * 1024);
  5235. }
  5236. virtual void SetUp() {
  5237. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5238. svr_.set_payload_max_length(200 * 1024 * 1024);
  5239. svr_.set_mount_point("/", "./www");
  5240. svr_.set_mount_point("/mount", "./www2");
  5241. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5242. svr_.Get("/hi",
  5243. [&](const Request & /*req*/, Response &res) {
  5244. res.set_content("Hello World!", "text/plain");
  5245. })
  5246. .Get("/file_content",
  5247. [&](const Request & /*req*/, Response &res) {
  5248. res.set_file_content("./www/dir/test.html");
  5249. })
  5250. .Get("/file_content_with_content_type",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_file_content("./www/file", "text/plain");
  5253. })
  5254. .Get("/invalid_file_content",
  5255. [&](const Request & /*req*/, Response &res) {
  5256. res.set_file_content("./www/dir/invalid_file_path");
  5257. })
  5258. .Get("/http_response_splitting",
  5259. [&](const Request & /*req*/, Response &res) {
  5260. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5261. EXPECT_EQ(0U, res.headers.size());
  5262. EXPECT_FALSE(res.has_header("a"));
  5263. res.set_header("a", "1\nSet-Cookie: a=1");
  5264. EXPECT_EQ(0U, res.headers.size());
  5265. EXPECT_FALSE(res.has_header("a"));
  5266. res.set_header("a", "1\rSet-Cookie: a=1");
  5267. EXPECT_EQ(0U, res.headers.size());
  5268. EXPECT_FALSE(res.has_header("a"));
  5269. res.set_header("a\r\nb", "0");
  5270. EXPECT_EQ(0U, res.headers.size());
  5271. EXPECT_FALSE(res.has_header("a"));
  5272. res.set_header("a\rb", "0");
  5273. EXPECT_EQ(0U, res.headers.size());
  5274. EXPECT_FALSE(res.has_header("a"));
  5275. res.set_header("a\nb", "0");
  5276. EXPECT_EQ(0U, res.headers.size());
  5277. EXPECT_FALSE(res.has_header("a"));
  5278. res.set_redirect("1\r\nSet-Cookie: a=1");
  5279. EXPECT_EQ(0U, res.headers.size());
  5280. EXPECT_FALSE(res.has_header("Location"));
  5281. })
  5282. .Get("/slow",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. std::this_thread::sleep_for(std::chrono::seconds(4));
  5285. res.set_content("slow", "text/plain");
  5286. })
  5287. #if 0
  5288. .Post("/slowpost",
  5289. [&](const Request & /*req*/, Response &res) {
  5290. std::this_thread::sleep_for(std::chrono::seconds(2));
  5291. res.set_content("slow", "text/plain");
  5292. })
  5293. #endif
  5294. .Get("/remote_addr",
  5295. [&](const Request &req, Response &res) {
  5296. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5297. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5300. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5301. #endif
  5302. res.set_content(req.remote_addr, "text/plain");
  5303. })
  5304. .Get("/local_addr",
  5305. [&](const Request &req, Response &res) {
  5306. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5307. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5308. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5310. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5311. #endif
  5312. auto local_addr = req.local_addr;
  5313. auto local_port = std::to_string(req.local_port);
  5314. res.set_content(local_addr.append(":").append(local_port),
  5315. "text/plain");
  5316. })
  5317. .Get("/endwith%",
  5318. [&](const Request & /*req*/, Response &res) {
  5319. res.set_content("Hello World!", "text/plain");
  5320. })
  5321. .Get("/a\\+\\+b",
  5322. [&](const Request &req, Response &res) {
  5323. ASSERT_TRUE(req.has_param("a +b"));
  5324. auto val = req.get_param_value("a +b");
  5325. res.set_content(val, "text/plain");
  5326. })
  5327. .Get("/", [&](const Request & /*req*/,
  5328. Response &res) { res.set_redirect("/hi"); })
  5329. .Post("/1",
  5330. [](const Request & /*req*/, Response &res) {
  5331. res.set_redirect("/2", StatusCode::SeeOther_303);
  5332. })
  5333. .Get("/2",
  5334. [](const Request & /*req*/, Response &res) {
  5335. res.set_content("redirected.", "text/plain");
  5336. res.status = StatusCode::OK_200;
  5337. })
  5338. .Post("/person",
  5339. [&](const Request &req, Response &res) {
  5340. if (req.has_param("name") && req.has_param("note")) {
  5341. persons_[req.get_param_value("name")] =
  5342. req.get_param_value("note");
  5343. } else {
  5344. res.status = StatusCode::BadRequest_400;
  5345. }
  5346. })
  5347. .Put("/person",
  5348. [&](const Request &req, Response &res) {
  5349. if (req.has_param("name") && req.has_param("note")) {
  5350. persons_[req.get_param_value("name")] =
  5351. req.get_param_value("note");
  5352. } else {
  5353. res.status = StatusCode::BadRequest_400;
  5354. }
  5355. })
  5356. .Get("/person/(.*)",
  5357. [&](const Request &req, Response &res) {
  5358. string name = req.matches[1];
  5359. if (persons_.find(name) != persons_.end()) {
  5360. auto note = persons_[name];
  5361. res.set_content(note, "text/plain");
  5362. } else {
  5363. res.status = StatusCode::NotFound_404;
  5364. }
  5365. })
  5366. .Delete("/person",
  5367. [&](const Request &req, Response &res) {
  5368. if (req.has_param("name")) {
  5369. string name = req.get_param_value("name");
  5370. if (persons_.find(name) != persons_.end()) {
  5371. persons_.erase(name);
  5372. res.set_content("DELETED", "text/plain");
  5373. } else {
  5374. res.status = StatusCode::NotFound_404;
  5375. }
  5376. } else {
  5377. res.status = StatusCode::BadRequest_400;
  5378. }
  5379. })
  5380. .Post("/x-www-form-urlencoded-json",
  5381. [&](const Request &req, Response &res) {
  5382. auto json = req.get_param_value("json");
  5383. ASSERT_EQ(JSON_DATA, json);
  5384. res.set_content(json, "appliation/json");
  5385. res.status = StatusCode::OK_200;
  5386. })
  5387. .Get("/streamed-chunked",
  5388. [&](const Request & /*req*/, Response &res) {
  5389. res.set_chunked_content_provider(
  5390. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5391. sink.os << "123";
  5392. sink.os << "456";
  5393. sink.os << "789";
  5394. sink.done();
  5395. return true;
  5396. });
  5397. })
  5398. .Get("/streamed-chunked-with-prohibited-trailer",
  5399. [&](const Request & /*req*/, Response &res) {
  5400. auto i = new int(0);
  5401. // Declare both a prohibited trailer (Content-Length) and an
  5402. // allowed one
  5403. res.set_header("Trailer", "Content-Length, X-Allowed");
  5404. res.set_chunked_content_provider(
  5405. "text/plain",
  5406. [i](size_t /*offset*/, DataSink &sink) {
  5407. switch (*i) {
  5408. case 0: sink.os << "123"; break;
  5409. case 1: sink.os << "456"; break;
  5410. case 2: sink.os << "789"; break;
  5411. case 3: {
  5412. sink.done_with_trailer(
  5413. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5414. } break;
  5415. }
  5416. (*i)++;
  5417. return true;
  5418. },
  5419. [i](bool success) {
  5420. EXPECT_TRUE(success);
  5421. delete i;
  5422. });
  5423. })
  5424. .Get("/streamed-chunked2",
  5425. [&](const Request & /*req*/, Response &res) {
  5426. auto i = new int(0);
  5427. res.set_chunked_content_provider(
  5428. "text/plain",
  5429. [i](size_t /*offset*/, DataSink &sink) {
  5430. switch (*i) {
  5431. case 0: sink.os << "123"; break;
  5432. case 1: sink.os << "456"; break;
  5433. case 2: sink.os << "789"; break;
  5434. case 3: sink.done(); break;
  5435. }
  5436. (*i)++;
  5437. return true;
  5438. },
  5439. [i](bool success) {
  5440. EXPECT_TRUE(success);
  5441. delete i;
  5442. });
  5443. })
  5444. .Get("/streamed-chunked-with-trailer",
  5445. [&](const Request & /*req*/, Response &res) {
  5446. auto i = new int(0);
  5447. res.set_header("Trailer", "Dummy1, Dummy2");
  5448. res.set_chunked_content_provider(
  5449. "text/plain",
  5450. [i](size_t /*offset*/, DataSink &sink) {
  5451. switch (*i) {
  5452. case 0: sink.os << "123"; break;
  5453. case 1: sink.os << "456"; break;
  5454. case 2: sink.os << "789"; break;
  5455. case 3: {
  5456. sink.done_with_trailer(
  5457. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5458. } break;
  5459. }
  5460. (*i)++;
  5461. return true;
  5462. },
  5463. [i](bool success) {
  5464. EXPECT_TRUE(success);
  5465. delete i;
  5466. });
  5467. })
  5468. .Get("/streamed",
  5469. [&](const Request & /*req*/, Response &res) {
  5470. res.set_content_provider(
  5471. 6, "text/plain",
  5472. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5473. sink.os << (offset < 3 ? "a" : "b");
  5474. return true;
  5475. });
  5476. })
  5477. .Get("/streamed-without-length",
  5478. [&](const Request & /*req*/, Response &res) {
  5479. auto data = new std::string("abcdefg");
  5480. res.set_content_provider(
  5481. "text/plain",
  5482. [data](size_t offset, DataSink &sink) {
  5483. if (offset < data->size()) {
  5484. sink.os << data->substr(offset);
  5485. }
  5486. sink.done();
  5487. return true;
  5488. },
  5489. [data](bool success) {
  5490. EXPECT_TRUE(success);
  5491. delete data;
  5492. });
  5493. })
  5494. .Get("/streamed-with-range",
  5495. [&](const Request &req, Response &res) {
  5496. auto data = new std::string("abcdefg");
  5497. // An explicit status keeps the server from picking the 206 it
  5498. // would otherwise choose for a ranged request, so the response
  5499. // is not a partial representation.
  5500. auto status = req.get_param_value("status");
  5501. if (status == "200") {
  5502. res.status = StatusCode::OK_200;
  5503. } else if (status == "403") {
  5504. res.status = StatusCode::Forbidden_403;
  5505. }
  5506. res.set_content_provider(
  5507. data->size(), "text/plain",
  5508. [data](size_t offset, size_t length, DataSink &sink) {
  5509. size_t DATA_CHUNK_SIZE = 4;
  5510. const auto &d = *data;
  5511. auto out_len =
  5512. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5513. auto ret =
  5514. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5515. EXPECT_TRUE(ret);
  5516. return true;
  5517. },
  5518. [data, &req](bool success) {
  5519. EXPECT_EQ(success, !req.has_param("error"));
  5520. delete data;
  5521. });
  5522. })
  5523. .Get("/streamed-cancel",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_content_provider(
  5526. size_t(-1), "text/plain",
  5527. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5528. sink.os << "data_chunk";
  5529. return true;
  5530. });
  5531. })
  5532. .Get("/regex-with-delimiter",
  5533. [&](const Request &req, Response & /*res*/) {
  5534. ASSERT_TRUE(req.has_param("key"));
  5535. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5536. })
  5537. .Get("/with-range",
  5538. [&](const Request & /*req*/, Response &res) {
  5539. res.set_content("abcdefg", "text/plain");
  5540. })
  5541. .Get("/test-start-time",
  5542. [&](const Request &req, Response & /*res*/) {
  5543. EXPECT_NE(req.start_time_,
  5544. std::chrono::steady_clock::time_point::min());
  5545. })
  5546. .Get("/with-range-customized-response",
  5547. [&](const Request & /*req*/, Response &res) {
  5548. res.status = StatusCode::BadRequest_400;
  5549. res.set_content(JSON_DATA, "application/json");
  5550. })
  5551. .Post("/chunked",
  5552. [&](const Request &req, Response & /*res*/) {
  5553. EXPECT_EQ(req.body, "dechunked post body");
  5554. })
  5555. .Post("/large-chunked",
  5556. [&](const Request &req, Response & /*res*/) {
  5557. std::string expected(6 * 30 * 1024u, 'a');
  5558. EXPECT_EQ(req.body, expected);
  5559. })
  5560. .Post("/multipart",
  5561. [&](const Request &req, Response & /*res*/) {
  5562. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5563. req.form.get_field_count("text2") +
  5564. req.form.get_field_count("file3") +
  5565. req.form.get_field_count("file4"));
  5566. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5567. req.form.get_file_count("file2"));
  5568. ASSERT_TRUE(!req.form.has_file("???"));
  5569. ASSERT_TRUE(!req.form.has_field("???"));
  5570. ASSERT_TRUE(req.body.empty());
  5571. {
  5572. const auto &text = req.form.get_field("text1");
  5573. EXPECT_EQ("text default", text);
  5574. }
  5575. {
  5576. const auto &text = req.form.get_field("text2");
  5577. EXPECT_EQ("aωb", text);
  5578. }
  5579. {
  5580. const auto &file = req.form.get_file("file1");
  5581. EXPECT_EQ("hello.txt", file.filename);
  5582. EXPECT_EQ("text/plain", file.content_type);
  5583. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5584. }
  5585. {
  5586. const auto &file = req.form.get_file("file2");
  5587. EXPECT_EQ("world.json", file.filename);
  5588. EXPECT_EQ("application/json", file.content_type);
  5589. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5590. }
  5591. {
  5592. const auto &text = req.form.get_field("file3");
  5593. EXPECT_EQ(0u, text.size());
  5594. }
  5595. {
  5596. const auto &text = req.form.get_field("file4");
  5597. EXPECT_EQ(0u, text.size());
  5598. }
  5599. })
  5600. .Post("/multipart/multi_file_values",
  5601. [&](const Request &req, Response & /*res*/) {
  5602. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5603. req.form.get_field_count("multi_text1"));
  5604. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5605. ASSERT_TRUE(!req.form.has_file("???"));
  5606. ASSERT_TRUE(!req.form.has_field("???"));
  5607. ASSERT_TRUE(req.body.empty());
  5608. {
  5609. const auto &text = req.form.get_field("text");
  5610. EXPECT_EQ("default text", text);
  5611. }
  5612. {
  5613. const auto &text1_values = req.form.get_fields("multi_text1");
  5614. EXPECT_EQ(2u, text1_values.size());
  5615. EXPECT_EQ("aaaaa", text1_values[0]);
  5616. EXPECT_EQ("bbbbb", text1_values[1]);
  5617. }
  5618. {
  5619. const auto &file1_values = req.form.get_files("multi_file1");
  5620. EXPECT_EQ(2u, file1_values.size());
  5621. auto file1 = file1_values[0];
  5622. EXPECT_EQ(file1.filename, "hello.txt");
  5623. EXPECT_EQ(file1.content_type, "text/plain");
  5624. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5625. auto file2 = file1_values[1];
  5626. EXPECT_EQ(file2.filename, "world.json");
  5627. EXPECT_EQ(file2.content_type, "application/json");
  5628. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5629. }
  5630. })
  5631. .Post("/empty",
  5632. [&](const Request &req, Response &res) {
  5633. EXPECT_EQ(req.body, "");
  5634. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5635. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5636. res.set_content("empty", "text/plain");
  5637. })
  5638. .Post("/empty-no-content-type",
  5639. [&](const Request &req, Response &res) {
  5640. EXPECT_EQ(req.body, "");
  5641. EXPECT_FALSE(req.has_header("Content-Type"));
  5642. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5643. res.set_content("empty-no-content-type", "text/plain");
  5644. })
  5645. .Post("/path-only",
  5646. [&](const Request &req, Response &res) {
  5647. EXPECT_EQ(req.body, "");
  5648. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5649. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5650. res.set_content("path-only", "text/plain");
  5651. })
  5652. .Post("/path-headers-only",
  5653. [&](const Request &req, Response &res) {
  5654. EXPECT_EQ(req.body, "");
  5655. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5656. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5657. EXPECT_EQ("world", req.get_header_value("hello"));
  5658. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5659. res.set_content("path-headers-only", "text/plain");
  5660. })
  5661. .Post("/post-large",
  5662. [&](const Request &req, Response &res) {
  5663. EXPECT_EQ(req.body, LARGE_DATA);
  5664. res.set_content(req.body, "text/plain");
  5665. })
  5666. .Post("/post-loopback",
  5667. [&](const Request &, Response &res,
  5668. ContentReader const &content_reader) {
  5669. std::string body;
  5670. content_reader([&](const char *data, size_t data_length) {
  5671. body.append(data, data_length);
  5672. return true;
  5673. });
  5674. res.set_content(body, "text/plain");
  5675. })
  5676. .Put("/put-loopback",
  5677. [&](const Request &, Response &res,
  5678. ContentReader const &content_reader) {
  5679. std::string body;
  5680. content_reader([&](const char *data, size_t data_length) {
  5681. body.append(data, data_length);
  5682. return true;
  5683. });
  5684. res.set_content(body, "text/plain");
  5685. })
  5686. .Patch("/patch-loopback",
  5687. [&](const Request &, Response &res,
  5688. ContentReader const &content_reader) {
  5689. std::string body;
  5690. content_reader([&](const char *data, size_t data_length) {
  5691. body.append(data, data_length);
  5692. return true;
  5693. });
  5694. res.set_content(body, "text/plain");
  5695. })
  5696. .Put("/empty-no-content-type",
  5697. [&](const Request &req, Response &res) {
  5698. EXPECT_EQ(req.body, "");
  5699. EXPECT_FALSE(req.has_header("Content-Type"));
  5700. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5701. res.set_content("empty-no-content-type", "text/plain");
  5702. })
  5703. .Put("/put",
  5704. [&](const Request &req, Response &res) {
  5705. EXPECT_EQ(req.body, "PUT");
  5706. res.set_content(req.body, "text/plain");
  5707. })
  5708. .Put("/put-large",
  5709. [&](const Request &req, Response &res) {
  5710. EXPECT_EQ(req.body, LARGE_DATA);
  5711. res.set_content(req.body, "text/plain");
  5712. })
  5713. .Patch("/patch",
  5714. [&](const Request &req, Response &res) {
  5715. EXPECT_EQ(req.body, "PATCH");
  5716. res.set_content(req.body, "text/plain");
  5717. })
  5718. .Delete("/delete",
  5719. [&](const Request & /*req*/, Response &res) {
  5720. res.set_content("DELETE", "text/plain");
  5721. })
  5722. .Delete("/delete-body",
  5723. [&](const Request &req, Response &res) {
  5724. EXPECT_EQ(req.body, "content");
  5725. res.set_content(req.body, "text/plain");
  5726. })
  5727. .Options(R"(\*)",
  5728. [&](const Request & /*req*/, Response &res) {
  5729. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5730. })
  5731. .CustomRoute("PROPFIND", "/dav/:id",
  5732. [&](const Request &req, Response &res) {
  5733. res.set_header("x-body-size",
  5734. std::to_string(req.body.size()));
  5735. res.set_header("x-matched-route", req.matched_route);
  5736. res.set_header("x-dav-id", req.path_params.at("id"));
  5737. res.status = StatusCode::MultiStatus_207;
  5738. res.set_content(req.body, "application/xml");
  5739. })
  5740. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5741. [&](const Request &req, Response &res) {
  5742. res.set_header("x-dav-match", req.matches[1]);
  5743. res.status = StatusCode::MultiStatus_207;
  5744. })
  5745. .CustomRoute("MKCOL", "/dav-mkcol",
  5746. [&](const Request &req, Response &res) {
  5747. EXPECT_TRUE(req.body.empty());
  5748. res.status = StatusCode::Created_201;
  5749. })
  5750. .CustomRoute(
  5751. "REPORT", "/dav-report",
  5752. [&](const Request & /*req*/, Response &res,
  5753. const ContentReader &content_reader) {
  5754. std::string body;
  5755. content_reader([&](const char *data, size_t data_length) {
  5756. body.append(data, data_length);
  5757. return true;
  5758. });
  5759. res.set_header("x-body-size", std::to_string(body.size()));
  5760. res.status = StatusCode::MultiStatus_207;
  5761. res.set_content(body, "application/xml");
  5762. })
  5763. .Get("/request-target",
  5764. [&](const Request &req, Response & /*res*/) {
  5765. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5766. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5767. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5768. })
  5769. .Get("/long-query-value",
  5770. [&](const Request &req, Response & /*res*/) {
  5771. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5772. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5773. })
  5774. .Get("/too-long-query-value",
  5775. [&](const Request &req, Response & /*res*/) {
  5776. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5777. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5778. })
  5779. .Get("/array-param",
  5780. [&](const Request &req, Response & /*res*/) {
  5781. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5782. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5783. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5784. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5785. })
  5786. .Get("/array-param-values",
  5787. [&](const Request &req, Response & /*res*/) {
  5788. auto values = req.get_param_values("array");
  5789. EXPECT_EQ(3u, values.size());
  5790. EXPECT_EQ("value1", values[0]);
  5791. EXPECT_EQ("value2", values[1]);
  5792. EXPECT_EQ("value3", values[2]);
  5793. auto empty = req.get_param_values("nonexistent");
  5794. EXPECT_TRUE(empty.empty());
  5795. })
  5796. .Post("/validate-no-multiple-headers",
  5797. [&](const Request &req, Response & /*res*/) {
  5798. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5799. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5800. })
  5801. .Post("/content_receiver",
  5802. [&](const Request &req, Response &res,
  5803. const ContentReader &content_reader) {
  5804. if (req.is_multipart_form_data()) {
  5805. std::vector<FormData> items;
  5806. content_reader(
  5807. [&](const FormData &file) {
  5808. items.push_back(file);
  5809. return true;
  5810. },
  5811. [&](const char *data, size_t data_length) {
  5812. items.back().content.append(data, data_length);
  5813. return true;
  5814. });
  5815. EXPECT_EQ(5u, items.size());
  5816. {
  5817. const auto &file = get_file_value(items, "text1");
  5818. EXPECT_TRUE(file.filename.empty());
  5819. EXPECT_EQ("text default", file.content);
  5820. }
  5821. {
  5822. const auto &file = get_file_value(items, "text2");
  5823. EXPECT_TRUE(file.filename.empty());
  5824. EXPECT_EQ("aωb", file.content);
  5825. }
  5826. {
  5827. const auto &file = get_file_value(items, "file1");
  5828. EXPECT_EQ("hello.txt", file.filename);
  5829. EXPECT_EQ("text/plain", file.content_type);
  5830. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5831. }
  5832. {
  5833. const auto &file = get_file_value(items, "file2");
  5834. EXPECT_EQ("world.json", file.filename);
  5835. EXPECT_EQ("application/json", file.content_type);
  5836. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5837. }
  5838. {
  5839. const auto &file = get_file_value(items, "file3");
  5840. EXPECT_TRUE(file.filename.empty());
  5841. EXPECT_EQ("application/octet-stream", file.content_type);
  5842. EXPECT_EQ(0u, file.content.size());
  5843. }
  5844. } else {
  5845. std::string body;
  5846. content_reader([&](const char *data, size_t data_length) {
  5847. EXPECT_EQ(7U, data_length);
  5848. body.append(data, data_length);
  5849. return true;
  5850. });
  5851. EXPECT_EQ(body, "content");
  5852. res.set_content(body, "text/plain");
  5853. }
  5854. })
  5855. .Put("/content_receiver",
  5856. [&](const Request & /*req*/, Response &res,
  5857. const ContentReader &content_reader) {
  5858. std::string body;
  5859. content_reader([&](const char *data, size_t data_length) {
  5860. body.append(data, data_length);
  5861. return true;
  5862. });
  5863. EXPECT_EQ(body, "content");
  5864. res.set_content(body, "text/plain");
  5865. })
  5866. .Patch("/content_receiver",
  5867. [&](const Request & /*req*/, Response &res,
  5868. const ContentReader &content_reader) {
  5869. std::string body;
  5870. content_reader([&](const char *data, size_t data_length) {
  5871. body.append(data, data_length);
  5872. return true;
  5873. });
  5874. EXPECT_EQ(body, "content");
  5875. res.set_content(body, "text/plain");
  5876. })
  5877. .Post("/query-string-and-body",
  5878. [&](const Request &req, Response & /*res*/) {
  5879. ASSERT_TRUE(req.has_param("key"));
  5880. EXPECT_EQ(req.get_param_value("key"), "value");
  5881. EXPECT_EQ(req.body, "content");
  5882. })
  5883. .Get("/last-request",
  5884. [&](const Request &req, Response & /*res*/) {
  5885. EXPECT_EQ("close", req.get_header_value("Connection"));
  5886. })
  5887. .Get(R"(/redirect/(\d+))",
  5888. [&](const Request &req, Response &res) {
  5889. auto num = std::stoi(req.matches[1]) + 1;
  5890. std::string url = "/redirect/" + std::to_string(num);
  5891. res.set_redirect(url);
  5892. })
  5893. .Post("/binary",
  5894. [&](const Request &req, Response &res) {
  5895. EXPECT_EQ(4U, req.body.size());
  5896. EXPECT_EQ("application/octet-stream",
  5897. req.get_header_value("Content-Type"));
  5898. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5899. res.set_content(req.body, "application/octet-stream");
  5900. })
  5901. .Put("/binary",
  5902. [&](const Request &req, Response &res) {
  5903. EXPECT_EQ(4U, req.body.size());
  5904. EXPECT_EQ("application/octet-stream",
  5905. req.get_header_value("Content-Type"));
  5906. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5907. res.set_content(req.body, "application/octet-stream");
  5908. })
  5909. .Patch("/binary",
  5910. [&](const Request &req, Response &res) {
  5911. EXPECT_EQ(4U, req.body.size());
  5912. EXPECT_EQ("application/octet-stream",
  5913. req.get_header_value("Content-Type"));
  5914. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5915. res.set_content(req.body, "application/octet-stream");
  5916. })
  5917. .Delete("/binary",
  5918. [&](const Request &req, Response &res) {
  5919. EXPECT_EQ(4U, req.body.size());
  5920. EXPECT_EQ("application/octet-stream",
  5921. req.get_header_value("Content-Type"));
  5922. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5923. res.set_content(req.body, "application/octet-stream");
  5924. })
  5925. .Get("/issue1772",
  5926. [&](const Request & /*req*/, Response &res) {
  5927. res.status = 401;
  5928. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5929. })
  5930. .Delete("/issue609",
  5931. [](const httplib::Request &, httplib::Response &res,
  5932. const httplib::ContentReader &) {
  5933. res.set_content("ok", "text/plain");
  5934. })
  5935. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5936. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5937. .Get("/compress",
  5938. [&](const Request & /*req*/, Response &res) {
  5939. res.set_content(
  5940. "12345678901234567890123456789012345678901234567890123456789"
  5941. "01234567890123456789012345678901234567890",
  5942. "text/plain");
  5943. })
  5944. .Get("/compress-with-charset",
  5945. [&](const Request & /*req*/, Response &res) {
  5946. res.set_content(
  5947. "12345678901234567890123456789012345678901234567890123456789"
  5948. "01234567890123456789012345678901234567890",
  5949. "application/json; charset=utf-8");
  5950. })
  5951. .Get("/nocompress",
  5952. [&](const Request & /*req*/, Response &res) {
  5953. res.set_content(
  5954. "12345678901234567890123456789012345678901234567890123456789"
  5955. "01234567890123456789012345678901234567890",
  5956. "application/octet-stream");
  5957. })
  5958. .Post("/compress-multipart",
  5959. [&](const Request &req, Response & /*res*/) {
  5960. EXPECT_EQ(2u, req.form.fields.size());
  5961. ASSERT_TRUE(!req.form.has_field("???"));
  5962. {
  5963. const auto &text = req.form.get_field("key1");
  5964. EXPECT_EQ("test", text);
  5965. }
  5966. {
  5967. const auto &text = req.form.get_field("key2");
  5968. EXPECT_EQ("--abcdefg123", text);
  5969. }
  5970. })
  5971. #endif
  5972. ;
  5973. persons_["john"] = "programmer";
  5974. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5975. svr_.wait_until_ready();
  5976. }
  5977. virtual void TearDown() {
  5978. svr_.stop();
  5979. if (!request_threads_.empty()) {
  5980. std::this_thread::sleep_for(std::chrono::seconds(1));
  5981. for (auto &t : request_threads_) {
  5982. t.join();
  5983. }
  5984. }
  5985. t_.join();
  5986. }
  5987. map<string, string> persons_;
  5988. #ifdef CPPHTTPLIB_SSL_ENABLED
  5989. SSLClient cli_;
  5990. SSLServer svr_;
  5991. #else
  5992. Client cli_;
  5993. Server svr_;
  5994. #endif
  5995. thread t_;
  5996. std::vector<thread> request_threads_;
  5997. };
  5998. TEST_F(ServerTest, GetMethod200) {
  5999. auto res = cli_.Get("/hi");
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ("HTTP/1.1", res->version);
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. EXPECT_EQ("OK", res->reason);
  6004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6005. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6006. EXPECT_EQ("Hello World!", res->body);
  6007. }
  6008. TEST_F(ServerTest, GetEmptyFile) {
  6009. auto res = cli_.Get("/empty_file");
  6010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6011. EXPECT_EQ(StatusCode::OK_200, res->status);
  6012. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6013. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6014. EXPECT_EQ("", res->body);
  6015. }
  6016. TEST_F(ServerTest, GetFileContent) {
  6017. auto res = cli_.Get("/file_content");
  6018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6021. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6022. EXPECT_EQ("test.html", res->body);
  6023. }
  6024. TEST_F(ServerTest, GetFileContentWithRange) {
  6025. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6028. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6030. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6031. EXPECT_EQ("est", res->body);
  6032. }
  6033. TEST_F(ServerTest, GetFileContentWithContentType) {
  6034. auto res = cli_.Get("/file_content_with_content_type");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6038. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6039. EXPECT_EQ("file\n", res->body);
  6040. }
  6041. TEST_F(ServerTest, GetInvalidFileContent) {
  6042. auto res = cli_.Get("/invalid_file_content");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6045. }
  6046. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6047. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. EXPECT_EQ("HTTP/1.1", res->version);
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6052. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6053. EXPECT_EQ("Hello World!", res->body);
  6054. }
  6055. TEST_F(ServerTest, GetMethod302) {
  6056. auto res = cli_.Get("/");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. EXPECT_EQ(StatusCode::Found_302, res->status);
  6059. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6060. }
  6061. TEST_F(ServerTest, GetMethod302Redirect) {
  6062. cli_.set_follow_location(true);
  6063. auto res = cli_.Get("/");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. EXPECT_EQ(StatusCode::OK_200, res->status);
  6066. EXPECT_EQ("Hello World!", res->body);
  6067. EXPECT_EQ("/hi", res->location);
  6068. }
  6069. TEST_F(ServerTest, GetMethod404) {
  6070. auto res = cli_.Get("/invalid");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, HeadMethod200) {
  6075. auto res = cli_.Head("/hi");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6079. EXPECT_TRUE(res->body.empty());
  6080. }
  6081. TEST_F(ServerTest, HeadMethod200Static) {
  6082. auto res = cli_.Head("/mount/dir/index.html");
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6086. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6087. EXPECT_TRUE(res->body.empty());
  6088. }
  6089. TEST_F(ServerTest, HeadMethod404) {
  6090. auto res = cli_.Head("/invalid");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6093. EXPECT_TRUE(res->body.empty());
  6094. }
  6095. TEST_F(ServerTest, GetMethodPersonJohn) {
  6096. auto res = cli_.Get("/person/john");
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::OK_200, res->status);
  6099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6100. EXPECT_EQ("programmer", res->body);
  6101. }
  6102. TEST_F(ServerTest, PostMethod1) {
  6103. auto res = cli_.Get("/person/john1");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6106. res = cli_.Post("/person", "name=john1&note=coder",
  6107. "application/x-www-form-urlencoded");
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. ASSERT_EQ(StatusCode::OK_200, res->status);
  6110. res = cli_.Get("/person/john1");
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. ASSERT_EQ(StatusCode::OK_200, res->status);
  6113. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6114. ASSERT_EQ("coder", res->body);
  6115. }
  6116. TEST_F(ServerTest, PostMethod2) {
  6117. auto res = cli_.Get("/person/john2");
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6120. Params params;
  6121. params.emplace("name", "john2");
  6122. params.emplace("note", "coder");
  6123. res = cli_.Post("/person", params);
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. ASSERT_EQ(StatusCode::OK_200, res->status);
  6126. res = cli_.Get("/person/john2");
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. ASSERT_EQ(StatusCode::OK_200, res->status);
  6129. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6130. ASSERT_EQ("coder", res->body);
  6131. }
  6132. TEST_F(ServerTest, PutMethod3) {
  6133. auto res = cli_.Get("/person/john3");
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6136. Params params;
  6137. params.emplace("name", "john3");
  6138. params.emplace("note", "coder");
  6139. res = cli_.Put("/person", params);
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. ASSERT_EQ(StatusCode::OK_200, res->status);
  6142. res = cli_.Get("/person/john3");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. ASSERT_EQ(StatusCode::OK_200, res->status);
  6145. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6146. ASSERT_EQ("coder", res->body);
  6147. }
  6148. TEST_F(ServerTest, DeleteMethod1) {
  6149. auto res = cli_.Get("/person/john4");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6152. Params params;
  6153. params.emplace("name", "john4");
  6154. params.emplace("note", "coder");
  6155. res = cli_.Post("/person", params);
  6156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6157. ASSERT_EQ(StatusCode::OK_200, res->status);
  6158. res = cli_.Get("/person/john4");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. ASSERT_EQ(StatusCode::OK_200, res->status);
  6161. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6162. ASSERT_EQ("coder", res->body);
  6163. Params delete_params;
  6164. delete_params.emplace("name", "john4");
  6165. res = cli_.Delete("/person", delete_params);
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. ASSERT_EQ(StatusCode::OK_200, res->status);
  6168. ASSERT_EQ("DELETED", res->body);
  6169. res = cli_.Get("/person/john4");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6172. }
  6173. TEST_F(ServerTest, DeleteMethod2) {
  6174. auto res = cli_.Get("/person/john5");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6177. Params params;
  6178. params.emplace("name", "john5");
  6179. params.emplace("note", "developer");
  6180. res = cli_.Post("/person", params);
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. res = cli_.Get("/person/john5");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::OK_200, res->status);
  6186. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6187. ASSERT_EQ("developer", res->body);
  6188. Params delete_params;
  6189. delete_params.emplace("name", "john5");
  6190. Headers headers;
  6191. headers.emplace("Custom-Header", "test-value");
  6192. res = cli_.Delete("/person", headers, delete_params);
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. ASSERT_EQ(StatusCode::OK_200, res->status);
  6195. ASSERT_EQ("DELETED", res->body);
  6196. res = cli_.Get("/person/john5");
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6199. }
  6200. TEST_F(ServerTest, DeleteMethod3) {
  6201. auto res = cli_.Get("/person/john6");
  6202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6203. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6204. Params params;
  6205. params.emplace("name", "john6");
  6206. params.emplace("note", "tester");
  6207. res = cli_.Post("/person", params);
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. ASSERT_EQ(StatusCode::OK_200, res->status);
  6210. res = cli_.Get("/person/john6");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. ASSERT_EQ(StatusCode::OK_200, res->status);
  6213. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6214. ASSERT_EQ("tester", res->body);
  6215. Params delete_params;
  6216. delete_params.emplace("name", "john6");
  6217. Headers headers;
  6218. headers.emplace("Custom-Header", "test-value");
  6219. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. ASSERT_EQ("DELETED", res->body);
  6223. res = cli_.Get("/person/john6");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6226. }
  6227. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6228. Params params;
  6229. params.emplace("json", JSON_DATA);
  6230. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::OK_200, res->status);
  6233. ASSERT_EQ(JSON_DATA, res->body);
  6234. }
  6235. TEST_F(ServerTest, PostEmptyContent) {
  6236. auto res = cli_.Post("/empty", "", "text/plain");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. ASSERT_EQ("empty", res->body);
  6240. }
  6241. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6242. auto res = cli_.Post("/empty-no-content-type");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("empty-no-content-type", res->body);
  6246. }
  6247. TEST_F(ServerTest, PostPathOnly) {
  6248. auto res = cli_.Post("/path-only");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. ASSERT_EQ(StatusCode::OK_200, res->status);
  6251. ASSERT_EQ("path-only", res->body);
  6252. }
  6253. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6254. auto res = cli_.Post("/path-headers-only",
  6255. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. ASSERT_EQ(StatusCode::OK_200, res->status);
  6258. ASSERT_EQ("path-headers-only", res->body);
  6259. }
  6260. TEST_F(ServerTest, PostLarge) {
  6261. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6263. ASSERT_EQ(StatusCode::OK_200, res->status);
  6264. EXPECT_EQ(LARGE_DATA, res->body);
  6265. }
  6266. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6267. auto res = cli_.Put("/empty-no-content-type");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. ASSERT_EQ(StatusCode::OK_200, res->status);
  6270. ASSERT_EQ("empty-no-content-type", res->body);
  6271. }
  6272. TEST_F(ServerTest, GetMethodDir) {
  6273. auto res = cli_.Get("/dir/");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::OK_200, res->status);
  6276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6277. auto body = R"(<html>
  6278. <head>
  6279. </head>
  6280. <body>
  6281. <a href="/dir/test.html">Test</a>
  6282. <a href="/hi">hi</a>
  6283. </body>
  6284. </html>
  6285. )";
  6286. EXPECT_EQ(body, res->body);
  6287. }
  6288. TEST_F(ServerTest, GetMethodDirTest) {
  6289. auto res = cli_.Get("/dir/test.html");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::OK_200, res->status);
  6292. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6293. EXPECT_EQ("test.html", res->body);
  6294. }
  6295. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6296. auto res = cli_.Get("/dir/../dir/test.html");
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6299. }
  6300. TEST_F(ServerTest, GetMethodInvalidPath) {
  6301. auto res = cli_.Get("/dir/../test.html");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6304. }
  6305. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6306. auto res = cli_.Get("/../www/dir/test.html");
  6307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6309. }
  6310. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6311. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6314. }
  6315. TEST_F(ServerTest, GetMethodDirMountTest) {
  6316. auto res = cli_.Get("/mount/dir/test.html");
  6317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6320. EXPECT_EQ("test.html", res->body);
  6321. }
  6322. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6323. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6328. auto res = cli_.Get("/mount/dir/../test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6333. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6336. }
  6337. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6338. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6341. }
  6342. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6343. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6346. }
  6347. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6348. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6351. }
  6352. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6353. auto res = cli_.Get("/mount/dir");
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6356. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6357. }
  6358. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6359. auto res = cli_.Get("//dir");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6362. EXPECT_FALSE(res->has_header("Location"));
  6363. }
  6364. TEST_F(ServerTest, PostMethod303) {
  6365. auto res = cli_.Post("/1", "body", "text/plain");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6368. EXPECT_EQ("/2", res->get_header_value("Location"));
  6369. }
  6370. TEST_F(ServerTest, PostMethod303Redirect) {
  6371. cli_.set_follow_location(true);
  6372. auto res = cli_.Post("/1", "body", "text/plain");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. EXPECT_EQ("redirected.", res->body);
  6376. EXPECT_EQ("/2", res->location);
  6377. }
  6378. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6379. auto res = cli_.Get("/dir/test.abcde");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::OK_200, res->status);
  6382. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6383. EXPECT_EQ("abcde", res->body);
  6384. }
  6385. TEST_F(ServerTest, StaticFileRange) {
  6386. auto res =
  6387. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6390. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6391. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6392. EXPECT_EQ(true, res->has_header("Content-Range"));
  6393. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6394. EXPECT_EQ(std::string("cd"), res->body);
  6395. }
  6396. TEST_F(ServerTest, StaticFileRanges) {
  6397. auto res = cli_.Get("/dir/test.abcde",
  6398. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6401. EXPECT_TRUE(
  6402. res->get_header_value("Content-Type")
  6403. .find(
  6404. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6405. 0);
  6406. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6407. }
  6408. TEST_F(ServerTest, StaticFileRangeHead) {
  6409. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6412. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6413. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6414. EXPECT_EQ(true, res->has_header("Content-Range"));
  6415. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6416. }
  6417. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6418. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6422. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6423. EXPECT_EQ(true, res->has_header("Content-Range"));
  6424. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6425. res->get_header_value("Content-Range"));
  6426. EXPECT_EQ("LAST\n", res->body);
  6427. }
  6428. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6429. auto res =
  6430. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6434. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6435. EXPECT_EQ(true, res->has_header("Content-Range"));
  6436. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6437. }
  6438. TEST_F(ServerTest, StaticFileBigFile) {
  6439. auto res = cli_.Get("/dir/1MB.txt");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6443. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6444. }
  6445. TEST_F(ServerTest, InvalidBaseDirMount) {
  6446. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6447. }
  6448. TEST_F(ServerTest, Binary) {
  6449. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6450. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6451. "application/octet-stream");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::OK_200, res->status);
  6454. ASSERT_EQ(4U, res->body.size());
  6455. res = cli_.Put("/binary", binary.data(), binary.size(),
  6456. "application/octet-stream");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. ASSERT_EQ(StatusCode::OK_200, res->status);
  6459. ASSERT_EQ(4U, res->body.size());
  6460. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6461. "application/octet-stream");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. ASSERT_EQ(StatusCode::OK_200, res->status);
  6464. ASSERT_EQ(4U, res->body.size());
  6465. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6466. "application/octet-stream");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. ASSERT_EQ(StatusCode::OK_200, res->status);
  6469. ASSERT_EQ(4U, res->body.size());
  6470. }
  6471. TEST_F(ServerTest, BinaryString) {
  6472. auto binary = std::string("\x00\x01\x02\x03", 4);
  6473. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::OK_200, res->status);
  6476. ASSERT_EQ(4U, res->body.size());
  6477. res = cli_.Put("/binary", binary, "application/octet-stream");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. ASSERT_EQ(StatusCode::OK_200, res->status);
  6480. ASSERT_EQ(4U, res->body.size());
  6481. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. ASSERT_EQ(StatusCode::OK_200, res->status);
  6484. ASSERT_EQ(4U, res->body.size());
  6485. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ(4U, res->body.size());
  6489. }
  6490. TEST_F(ServerTest, EmptyRequest) {
  6491. auto res = cli_.Get("");
  6492. ASSERT_TRUE(!res);
  6493. EXPECT_EQ(Error::Connection, res.error());
  6494. }
  6495. TEST_F(ServerTest, LongRequest) {
  6496. std::string request;
  6497. for (size_t i = 0; i < 545; i++) {
  6498. request += "/TooLongRequest";
  6499. }
  6500. request += "OK";
  6501. auto res = cli_.Get(request.c_str());
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6504. }
  6505. TEST_F(ServerTest, TooLongRequest) {
  6506. std::string request;
  6507. for (size_t i = 0; i < 546; i++) {
  6508. request += "/TooLongRequest";
  6509. }
  6510. request += "_NG";
  6511. auto start = std::chrono::high_resolution_clock::now();
  6512. cli_.set_keep_alive(true);
  6513. auto res = cli_.Get(request.c_str());
  6514. auto end = std::chrono::high_resolution_clock::now();
  6515. auto elapsed =
  6516. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6517. .count();
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6520. EXPECT_LE(elapsed, 1000);
  6521. EXPECT_EQ("close", res->get_header_value("Connection"));
  6522. EXPECT_FALSE(cli_.is_socket_open());
  6523. }
  6524. TEST_F(ServerTest, AlmostTooLongRequest) {
  6525. // test for #2046 - URI length check shouldn't include other content on req
  6526. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6527. // leading /, space, HTTP/1.1)
  6528. std::string request =
  6529. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6530. auto res = cli_.Get(request.c_str());
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6533. }
  6534. TEST_F(ServerTest, LongHeader) {
  6535. Request req;
  6536. req.method = "GET";
  6537. req.path = "/hi";
  6538. std::string host_and_port;
  6539. host_and_port += HOST;
  6540. host_and_port += ":";
  6541. host_and_port += std::to_string(PORT);
  6542. req.headers.emplace("Host", host_and_port.c_str());
  6543. req.headers.emplace("Accept", "*/*");
  6544. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6545. req.headers.emplace(
  6546. "Header-Name",
  6547. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6548. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6549. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  6577. auto error = Error::Success;
  6578. auto ret = cli_.send(req, *res, error);
  6579. ASSERT_TRUE(ret);
  6580. EXPECT_EQ(StatusCode::OK_200, res->status);
  6581. }
  6582. TEST_F(ServerTest, LongQueryValue) {
  6583. auto start = std::chrono::high_resolution_clock::now();
  6584. cli_.set_keep_alive(true);
  6585. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6586. auto end = std::chrono::high_resolution_clock::now();
  6587. auto elapsed =
  6588. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6589. .count();
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6592. EXPECT_LE(elapsed, 1000);
  6593. EXPECT_EQ("close", res->get_header_value("Connection"));
  6594. EXPECT_FALSE(cli_.is_socket_open());
  6595. }
  6596. TEST_F(ServerTest, TooLongQueryValue) {
  6597. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6598. ASSERT_FALSE(res);
  6599. EXPECT_EQ(Error::Read, res.error());
  6600. }
  6601. TEST_F(ServerTest, TooLongHeader) {
  6602. Request req;
  6603. req.method = "GET";
  6604. req.path = "/hi";
  6605. std::string host_and_port;
  6606. host_and_port += HOST;
  6607. host_and_port += ":";
  6608. host_and_port += std::to_string(PORT);
  6609. req.headers.emplace("Host", host_and_port.c_str());
  6610. req.headers.emplace("Accept", "*/*");
  6611. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6612. req.headers.emplace(
  6613. "Header-Name",
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  6644. auto error = Error::Success;
  6645. auto ret = cli_.send(req, *res, error);
  6646. ASSERT_TRUE(ret);
  6647. EXPECT_EQ(StatusCode::OK_200, res->status);
  6648. }
  6649. TEST_F(ServerTest, HeaderCountAtLimit) {
  6650. // Test with headers just under the 100 limit
  6651. httplib::Headers headers;
  6652. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6653. // This should keep us just under the 100 header limit
  6654. for (int i = 0; i < 95; i++) {
  6655. std::string name = "X-Test-Header-" + std::to_string(i);
  6656. std::string value = "value" + std::to_string(i);
  6657. headers.emplace(name, value);
  6658. }
  6659. // This should work fine as we're under the limit
  6660. auto res = cli_.Get("/hi", headers);
  6661. EXPECT_TRUE(res);
  6662. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6663. }
  6664. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6665. // Test with many headers to exceed the 100 limit
  6666. httplib::Headers headers;
  6667. // Add 150 headers to definitely exceed the 100 limit
  6668. for (int i = 0; i < 150; i++) {
  6669. std::string name = "X-Test-Header-" + std::to_string(i);
  6670. std::string value = "value" + std::to_string(i);
  6671. headers.emplace(name, value);
  6672. }
  6673. // This should fail due to exceeding header count limit
  6674. cli_.set_keep_alive(true);
  6675. auto res = cli_.Get("/hi", headers);
  6676. // The server should respond with 400 Bad Request
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6679. EXPECT_EQ("close", res->get_header_value("Connection"));
  6680. EXPECT_FALSE(cli_.is_socket_open());
  6681. }
  6682. TEST_F(ServerTest, PercentEncoding) {
  6683. auto res = cli_.Get("/e%6edwith%");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, PercentEncodingUnicode) {
  6688. auto res = cli_.Get("/e%u006edwith%");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. }
  6692. TEST_F(ServerTest, InvalidPercentEncoding) {
  6693. auto res = cli_.Get("/%endwith%");
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6696. }
  6697. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6698. auto res = cli_.Get("/%uendwith%");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6701. }
  6702. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6703. auto res = cli_.Get("/hello?aaa=bbb%");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6706. }
  6707. TEST_F(ServerTest, PlusSignEncoding) {
  6708. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ("a +b", res->body);
  6712. }
  6713. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6714. // This test simulates a potential DoS attack using many headers
  6715. // to verify our security fix prevents memory exhaustion
  6716. httplib::Headers attack_headers;
  6717. // Attempt to add many headers like an attacker would (200 headers to far
  6718. // exceed limit)
  6719. for (int i = 0; i < 200; i++) {
  6720. std::string name = "X-Attack-Header-" + std::to_string(i);
  6721. std::string value = "attack_payload_" + std::to_string(i);
  6722. attack_headers.emplace(name, value);
  6723. }
  6724. // Try to POST with excessive headers
  6725. cli_.set_keep_alive(true);
  6726. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6727. // Should either fail or return 400 Bad Request due to security limit
  6728. if (res) {
  6729. // If we get a response, it should be 400 Bad Request
  6730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6731. EXPECT_EQ("close", res->get_header_value("Connection"));
  6732. }
  6733. EXPECT_FALSE(cli_.is_socket_open());
  6734. }
  6735. TEST_F(ServerTest, MultipartFormData) {
  6736. UploadFormDataItems items = {
  6737. {"text1", "text default", "", ""},
  6738. {"text2", "aωb", "", ""},
  6739. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6740. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6741. {"file3", "", "", "application/octet-stream"},
  6742. {"file4", "", "", " application/json tmp-string "}};
  6743. auto res = cli_.Post("/multipart", items);
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. }
  6747. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6748. UploadFormDataItems items = {
  6749. {"text", "default text", "", ""},
  6750. {"multi_text1", "aaaaa", "", ""},
  6751. {"multi_text1", "bbbbb", "", ""},
  6752. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6753. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6754. "application/json"},
  6755. };
  6756. auto res = cli_.Post("/multipart/multi_file_values", items);
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. }
  6760. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6761. auto res = cli_.Get("/hi");
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_EQ(StatusCode::OK_200, res->status);
  6764. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6765. EXPECT_EQ("Hello World!", res->body);
  6766. }
  6767. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6768. Request req;
  6769. req.method = "POST";
  6770. req.path = "/chunked";
  6771. std::string host_and_port;
  6772. host_and_port += HOST;
  6773. host_and_port += ":";
  6774. host_and_port += std::to_string(PORT);
  6775. req.headers.emplace("Host", host_and_port.c_str());
  6776. req.headers.emplace("Accept", "*/*");
  6777. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6778. req.headers.emplace("Content-Type", "text/plain");
  6779. req.headers.emplace("Content-Length", "0");
  6780. req.headers.emplace(
  6781. "Transfer-Encoding",
  6782. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6783. // Client does not chunk, so make a chunked body manually.
  6784. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6785. auto res = std::make_shared<Response>();
  6786. auto error = Error::Success;
  6787. auto ret = cli_.send(req, *res, error);
  6788. ASSERT_TRUE(ret);
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. }
  6791. template <typename ClientT>
  6792. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6793. int expected_status) {
  6794. Request req;
  6795. req.method = "POST";
  6796. req.path = "/chunked";
  6797. std::string host_and_port;
  6798. host_and_port += HOST;
  6799. host_and_port += ":";
  6800. host_and_port += std::to_string(PORT);
  6801. req.headers.emplace("Host", host_and_port.c_str());
  6802. req.headers.emplace("Content-Length", "0");
  6803. req.headers.emplace("Transfer-Encoding", "chunked");
  6804. req.body = body;
  6805. auto res = std::make_shared<Response>();
  6806. auto error = Error::Success;
  6807. ASSERT_TRUE(cli.send(req, *res, error));
  6808. EXPECT_EQ(expected_status, res->status);
  6809. }
  6810. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6811. // rather than treat them as valid lengths.
  6812. template <typename ClientT>
  6813. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6814. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6815. }
  6816. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6817. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6818. }
  6819. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6820. expect_chunked_body_rejected(
  6821. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6822. }
  6823. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6824. // chunk-size line carries no CR, LF or other control character ahead of its
  6825. // terminator. Such a line must be refused rather than read as extension text.
  6826. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6827. expect_chunked_body_rejected(
  6828. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6829. }
  6830. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6831. expect_chunked_body_rejected(
  6832. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6833. }
  6834. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6835. expect_chunked_body_rejected(
  6836. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6837. }
  6838. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6839. // The literal stays split: a hex escape consumes every hex digit that
  6840. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6841. expect_chunked_body_rejected(
  6842. cli_, "4;a\x01"
  6843. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6844. }
  6845. // The bytes around chunk data are no payload, so they cannot ride on the
  6846. // payload limit
  6847. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6848. // Small enough that the whole request is sent before the server turns it
  6849. // down, yet past the limit by the last chunks
  6850. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6851. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6852. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6853. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6854. SCOPED_TRACE(size_line.substr(0, 2));
  6855. std::string body;
  6856. for (auto c : std::string("dechunked post body")) {
  6857. body += size_line + "\r\n" + c + "\r\n";
  6858. }
  6859. body += "0\r\n\r\n";
  6860. expect_chunked_body_rejected(cli_, body.c_str());
  6861. }
  6862. }
  6863. TEST_F(ServerTest, AcceptsChunkExtension) {
  6864. expect_chunked_body_status(cli_,
  6865. "4;name=value\r\ndech\r\n"
  6866. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6867. "0;last\r\n\r\n",
  6868. StatusCode::OK_200);
  6869. }
  6870. TEST_F(ServerTest, GetStreamed2) {
  6871. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6874. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6875. EXPECT_EQ(true, res->has_header("Content-Range"));
  6876. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6877. EXPECT_EQ(std::string("ab"), res->body);
  6878. }
  6879. TEST_F(ServerTest, GetStreamed) {
  6880. auto res = cli_.Get("/streamed");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6884. EXPECT_EQ(std::string("aaabbb"), res->body);
  6885. }
  6886. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6887. auto res = cli_.Get("/streamed-without-length",
  6888. Headers{make_range_header({{0, -1}})});
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::OK_200, res->status);
  6891. EXPECT_EQ(false, res->has_header("Content-Length"));
  6892. EXPECT_EQ(false, res->has_header("Content-Range"));
  6893. EXPECT_EQ(std::string("abcdefg"), res->body);
  6894. }
  6895. TEST_F(ServerTest, GetStreamedWithRange1) {
  6896. auto res =
  6897. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6899. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6900. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6901. EXPECT_EQ(true, res->has_header("Content-Range"));
  6902. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6903. EXPECT_EQ(std::string("def"), res->body);
  6904. }
  6905. TEST_F(ServerTest, GetStreamedWithRange2) {
  6906. auto res =
  6907. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6909. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6910. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6911. EXPECT_EQ(true, res->has_header("Content-Range"));
  6912. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6913. EXPECT_EQ(std::string("bcdefg"), res->body);
  6914. }
  6915. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6916. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6919. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6920. EXPECT_EQ(true, res->has_header("Content-Range"));
  6921. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6922. EXPECT_EQ(std::string("efg"), res->body);
  6923. }
  6924. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6925. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6926. // the entire representation.
  6927. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6928. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6931. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6932. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6933. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6934. }
  6935. }
  6936. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6937. auto res =
  6938. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6941. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6942. EXPECT_EQ(false, res->has_header("Content-Range"));
  6943. EXPECT_EQ(0U, res->body.size());
  6944. }
  6945. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6946. // Only a 206 is served as a partial representation. Under any other status
  6947. // `apply_ranges()` reported the full content length, so the body must match
  6948. // that header, and the content provider must never be asked for an offset
  6949. // outside the representation.
  6950. auto check = [&](int status, const char *range) {
  6951. auto path =
  6952. std::string("/streamed-with-range?status=") + std::to_string(status);
  6953. auto ctx = path + " Range: " + range;
  6954. auto res = cli_.Get(path, Headers{{"Range", range}});
  6955. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6956. EXPECT_EQ(status, res->status) << ctx;
  6957. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6959. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6960. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6961. };
  6962. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6963. check(403, "bytes=3-5");
  6964. // The offset is far past the representation.
  6965. check(403, "bytes=100000-100200");
  6966. // `first_pos` is still -1 here, and the bounds asserts in
  6967. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6968. check(403, "bytes=-3");
  6969. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6970. // multipart branch would have written one that is empty.
  6971. check(403, "bytes=1-2, 4-5");
  6972. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6973. // covers the whole representation.
  6974. check(200, "bytes=3-5");
  6975. check(200, "bytes=1-2, 4-5");
  6976. }
  6977. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6978. auto res =
  6979. cli_.Get("/streamed-with-range",
  6980. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6981. "92233720368547758079223372036854775807"}});
  6982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6983. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6984. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6985. EXPECT_EQ(false, res->has_header("Content-Range"));
  6986. EXPECT_EQ(0U, res->body.size());
  6987. }
  6988. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6989. auto res = cli_.Get(
  6990. "/with-range",
  6991. Headers{{"Range",
  6992. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6993. {"Accept-Encoding", ""}});
  6994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6996. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6997. EXPECT_EQ(true, res->has_header("Content-Range"));
  6998. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6999. EXPECT_EQ(std::string("abcdefg"), res->body);
  7000. }
  7001. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7002. auto res = cli_.Get("/with-range", Headers{
  7003. {"Range", "bytes=0-"},
  7004. {"Accept-Encoding", ""},
  7005. });
  7006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7007. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7008. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7009. EXPECT_EQ(true, res->has_header("Content-Range"));
  7010. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7011. EXPECT_EQ(std::string("abcdefg"), res->body);
  7012. }
  7013. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7014. auto res = cli_.Get("/streamed-with-range",
  7015. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7018. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7019. EXPECT_EQ(false, res->has_header("Content-Range"));
  7020. EXPECT_EQ(267U, res->body.size());
  7021. // Check that both range contents are present
  7022. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7023. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7024. // Check that Content-Range headers are present for both ranges
  7025. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7026. std::string::npos);
  7027. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7028. std::string::npos);
  7029. }
  7030. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7031. Ranges ranges;
  7032. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7033. ranges.emplace_back(0, -1);
  7034. }
  7035. auto res = cli_.Get("/streamed-with-range?error",
  7036. Headers{{make_range_header(ranges)}});
  7037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7038. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7039. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7040. EXPECT_EQ(false, res->has_header("Content-Range"));
  7041. EXPECT_EQ(0U, res->body.size());
  7042. }
  7043. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7044. auto res = cli_.Get("/streamed-with-range",
  7045. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7048. EXPECT_EQ(5U, res->body.size());
  7049. // Check that overlapping ranges are coalesced into a single range
  7050. EXPECT_EQ("bcdef", res->body);
  7051. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7052. // Should be single range, not multipart
  7053. EXPECT_TRUE(res->has_header("Content-Range"));
  7054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7055. }
  7056. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7057. auto res = cli_.Get("/streamed-with-range",
  7058. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7061. EXPECT_EQ(268U, res->body.size());
  7062. // Check that both range contents are present
  7063. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7064. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7065. // Check that Content-Range headers are present for both ranges
  7066. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7067. std::string::npos);
  7068. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7069. std::string::npos);
  7070. }
  7071. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7072. auto res = cli_.Get("/streamed-with-range",
  7073. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7076. EXPECT_EQ(269U, res->body.size());
  7077. // Check that both duplicate range contents are present
  7078. size_t first_abc = res->body.find("abc\r\n");
  7079. EXPECT_TRUE(first_abc != std::string::npos);
  7080. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7081. EXPECT_TRUE(second_abc != std::string::npos);
  7082. // Check that Content-Range headers are present for both ranges
  7083. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7084. EXPECT_TRUE(first_range != std::string::npos);
  7085. size_t second_range =
  7086. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7087. EXPECT_TRUE(second_range != std::string::npos);
  7088. }
  7089. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7090. auto res =
  7091. cli_.Get("/streamed-with-range?error",
  7092. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7095. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7096. EXPECT_EQ(false, res->has_header("Content-Range"));
  7097. EXPECT_EQ(0U, res->body.size());
  7098. }
  7099. TEST_F(ServerTest, GetStreamedEndless) {
  7100. uint64_t offset = 0;
  7101. auto res = cli_.Get("/streamed-cancel",
  7102. [&](const char * /*data*/, uint64_t data_length) {
  7103. if (offset < 100) {
  7104. offset += data_length;
  7105. return true;
  7106. }
  7107. return false;
  7108. });
  7109. ASSERT_TRUE(!res);
  7110. EXPECT_EQ(Error::Canceled, res.error());
  7111. }
  7112. TEST_F(ServerTest, ClientStop) {
  7113. std::atomic_size_t count{4};
  7114. std::vector<std::thread> threads;
  7115. for (auto i = count.load(); i != 0; --i) {
  7116. threads.emplace_back([&]() {
  7117. auto res = cli_.Get("/streamed-cancel",
  7118. [&](const char *, uint64_t) { return true; });
  7119. --count;
  7120. ASSERT_TRUE(!res);
  7121. EXPECT_TRUE(res.error() == Error::Canceled ||
  7122. res.error() == Error::Read || res.error() == Error::Write);
  7123. });
  7124. }
  7125. std::this_thread::sleep_for(std::chrono::seconds(2));
  7126. while (count != 0) {
  7127. cli_.stop();
  7128. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7129. }
  7130. for (auto &t : threads) {
  7131. t.join();
  7132. }
  7133. }
  7134. TEST_F(ServerTest, GetWithRange1) {
  7135. auto res = cli_.Get("/with-range", Headers{
  7136. make_range_header({{3, 5}}),
  7137. {"Accept-Encoding", ""},
  7138. });
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7141. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7142. EXPECT_EQ(true, res->has_header("Content-Range"));
  7143. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7144. EXPECT_EQ(std::string("def"), res->body);
  7145. }
  7146. TEST_F(ServerTest, GetWithRange2) {
  7147. auto res = cli_.Get("/with-range", Headers{
  7148. make_range_header({{1, -1}}),
  7149. {"Accept-Encoding", ""},
  7150. });
  7151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7152. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7153. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7154. EXPECT_EQ(true, res->has_header("Content-Range"));
  7155. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7156. EXPECT_EQ(std::string("bcdefg"), res->body);
  7157. }
  7158. TEST_F(ServerTest, GetWithRange3) {
  7159. auto res = cli_.Get("/with-range", Headers{
  7160. make_range_header({{0, 0}}),
  7161. {"Accept-Encoding", ""},
  7162. });
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7165. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7166. EXPECT_EQ(true, res->has_header("Content-Range"));
  7167. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7168. EXPECT_EQ(std::string("a"), res->body);
  7169. }
  7170. TEST_F(ServerTest, GetWithRange4) {
  7171. auto res = cli_.Get("/with-range", Headers{
  7172. make_range_header({{-1, 2}}),
  7173. {"Accept-Encoding", ""},
  7174. });
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7177. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7178. EXPECT_EQ(true, res->has_header("Content-Range"));
  7179. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7180. EXPECT_EQ(std::string("fg"), res->body);
  7181. }
  7182. TEST_F(ServerTest, GetWithRange5) {
  7183. auto res = cli_.Get("/with-range", Headers{
  7184. make_range_header({{0, 5}}),
  7185. {"Accept-Encoding", ""},
  7186. });
  7187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7189. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7190. EXPECT_EQ(true, res->has_header("Content-Range"));
  7191. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7192. EXPECT_EQ(std::string("abcdef"), res->body);
  7193. }
  7194. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7195. auto res =
  7196. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7199. }
  7200. TEST_F(ServerTest, GetWithRangeMultipart) {
  7201. auto res =
  7202. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7205. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7206. EXPECT_EQ(false, res->has_header("Content-Range"));
  7207. EXPECT_EQ(267U, res->body.size());
  7208. }
  7209. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7210. auto res = cli_.Get("/with-range",
  7211. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7214. }
  7215. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7216. auto res = cli_.Get("/with-range-customized-response",
  7217. Headers{{make_range_header({{1, 2}})}});
  7218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7219. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7220. EXPECT_EQ(true, res->has_header("Content-Length"));
  7221. EXPECT_EQ(false, res->has_header("Content-Range"));
  7222. EXPECT_EQ(JSON_DATA, res->body);
  7223. }
  7224. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7225. auto res = cli_.Get("/with-range-customized-response",
  7226. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7228. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7229. EXPECT_EQ(true, res->has_header("Content-Length"));
  7230. EXPECT_EQ(false, res->has_header("Content-Range"));
  7231. EXPECT_EQ(JSON_DATA, res->body);
  7232. }
  7233. TEST_F(ServerTest, Issue1772) {
  7234. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7237. }
  7238. TEST_F(ServerTest, Issue609) {
  7239. auto res = cli_.Delete("/issue609");
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. EXPECT_EQ(StatusCode::OK_200, res->status);
  7242. EXPECT_EQ(std::string("ok"), res->body);
  7243. }
  7244. TEST_F(ServerTest, GetStreamedChunked) {
  7245. auto res = cli_.Get("/streamed-chunked");
  7246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7247. EXPECT_EQ(StatusCode::OK_200, res->status);
  7248. EXPECT_EQ(std::string("123456789"), res->body);
  7249. }
  7250. TEST_F(ServerTest, GetStreamedChunked2) {
  7251. auto res = cli_.Get("/streamed-chunked2");
  7252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7253. EXPECT_EQ(StatusCode::OK_200, res->status);
  7254. EXPECT_EQ(std::string("123456789"), res->body);
  7255. }
  7256. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7257. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. EXPECT_EQ(std::string("123456789"), res->body);
  7261. EXPECT_TRUE(res->has_header("Trailer"));
  7262. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7263. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7264. // Trailers are now stored separately from headers (security fix)
  7265. EXPECT_EQ(2U, res->trailers.size());
  7266. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7267. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7268. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7269. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7270. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7271. // Verify trailers are NOT in headers (security verification)
  7272. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7273. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7274. }
  7275. TEST_F(ServerTest, LargeChunkedPost) {
  7276. Request req;
  7277. req.method = "POST";
  7278. req.path = "/large-chunked";
  7279. std::string host_and_port;
  7280. host_and_port += HOST;
  7281. host_and_port += ":";
  7282. host_and_port += std::to_string(PORT);
  7283. req.headers.emplace("Host", host_and_port.c_str());
  7284. req.headers.emplace("Accept", "*/*");
  7285. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7286. req.headers.emplace("Content-Type", "text/plain");
  7287. req.headers.emplace("Content-Length", "0");
  7288. req.headers.emplace("Transfer-Encoding", "chunked");
  7289. std::string long_string(30 * 1024u, 'a');
  7290. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7291. // Attempt to make a large enough post to exceed OS buffers, to test that
  7292. // the server handles short reads if the full chunk data isn't available.
  7293. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7294. auto res = std::make_shared<Response>();
  7295. auto error = Error::Success;
  7296. auto ret = cli_.send(req, *res, error);
  7297. ASSERT_TRUE(ret);
  7298. EXPECT_EQ(StatusCode::OK_200, res->status);
  7299. }
  7300. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7301. auto res = cli_.Get("/remote_addr");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7305. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7306. }
  7307. TEST_F(ServerTest, GetMethodLocalAddr) {
  7308. auto res = cli_.Get("/local_addr");
  7309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7310. EXPECT_EQ(StatusCode::OK_200, res->status);
  7311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7312. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7313. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7314. }
  7315. TEST_F(ServerTest, HTTPResponseSplitting) {
  7316. auto res = cli_.Get("/http_response_splitting");
  7317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7318. EXPECT_EQ(StatusCode::OK_200, res->status);
  7319. }
  7320. TEST_F(ServerTest, SlowRequest) {
  7321. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7322. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7323. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7324. }
  7325. #if 0
  7326. TEST_F(ServerTest, SlowPost) {
  7327. char buffer[64 * 1024];
  7328. memset(buffer, 0x42, sizeof(buffer));
  7329. auto res = cli_.Post(
  7330. "/slowpost", 64 * 1024 * 1024,
  7331. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7332. auto ret = sink.write(buffer, sizeof(buffer));
  7333. EXPECT_TRUE(ret);
  7334. return true;
  7335. },
  7336. "text/plain");
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::OK_200, res->status);
  7339. }
  7340. TEST_F(ServerTest, SlowPostFail) {
  7341. char buffer[64 * 1024];
  7342. memset(buffer, 0x42, sizeof(buffer));
  7343. cli_.set_write_timeout(std::chrono::seconds(0));
  7344. auto res = cli_.Post(
  7345. "/slowpost", 64 * 1024 * 1024,
  7346. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7347. sink.write(buffer, sizeof(buffer));
  7348. return true;
  7349. },
  7350. "text/plain");
  7351. ASSERT_TRUE(!res);
  7352. EXPECT_EQ(Error::Write, res.error());
  7353. }
  7354. #endif
  7355. TEST_F(ServerTest, Put) {
  7356. auto res = cli_.Put("/put", "PUT", "text/plain");
  7357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7358. EXPECT_EQ(StatusCode::OK_200, res->status);
  7359. EXPECT_EQ("PUT", res->body);
  7360. }
  7361. TEST_F(ServerTest, PutWithContentProvider) {
  7362. auto res = cli_.Put(
  7363. "/put", 3,
  7364. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7365. sink.os << "PUT";
  7366. return true;
  7367. },
  7368. "text/plain");
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. EXPECT_EQ(StatusCode::OK_200, res->status);
  7371. EXPECT_EQ("PUT", res->body);
  7372. }
  7373. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7374. auto res = cli_.Post(
  7375. "/post", 42,
  7376. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7377. return false;
  7378. },
  7379. "text/plain");
  7380. ASSERT_TRUE(!res);
  7381. EXPECT_EQ(Error::Canceled, res.error());
  7382. }
  7383. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7384. auto res = cli_.Put(
  7385. "/put",
  7386. [](size_t /*offset*/, DataSink &sink) {
  7387. sink.os << "PUT";
  7388. sink.done();
  7389. return true;
  7390. },
  7391. "text/plain");
  7392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7393. EXPECT_EQ(StatusCode::OK_200, res->status);
  7394. EXPECT_EQ("PUT", res->body);
  7395. }
  7396. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7397. auto res = cli_.Post(
  7398. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7399. "text/plain");
  7400. ASSERT_TRUE(!res);
  7401. EXPECT_EQ(Error::Canceled, res.error());
  7402. }
  7403. TEST_F(ServerTest, PostLoopBack) {
  7404. std::string body;
  7405. auto res = cli_.Post(
  7406. "/post-loopback", 9,
  7407. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7408. EXPECT_EQ(9u, length);
  7409. sink.write("123", 3);
  7410. sink.write("456", 3);
  7411. sink.write("789", 3);
  7412. return true;
  7413. },
  7414. "text/plain",
  7415. [&body](const char *data, size_t data_length) {
  7416. body.append(data, data_length);
  7417. return true;
  7418. });
  7419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7420. EXPECT_EQ(StatusCode::OK_200, res->status);
  7421. EXPECT_EQ("123456789", body);
  7422. }
  7423. TEST_F(ServerTest, PutLoopBack) {
  7424. std::string body;
  7425. auto res = cli_.Put(
  7426. "/put-loopback", 9,
  7427. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7428. EXPECT_EQ(9u, length);
  7429. sink.write("123", 3);
  7430. sink.write("456", 3);
  7431. sink.write("789", 3);
  7432. return true;
  7433. },
  7434. "text/plain",
  7435. [&body](const char *data, size_t data_length) {
  7436. body.append(data, data_length);
  7437. return true;
  7438. });
  7439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7440. EXPECT_EQ(StatusCode::OK_200, res->status);
  7441. EXPECT_EQ("123456789", body);
  7442. }
  7443. TEST_F(ServerTest, PatchLoopBack) {
  7444. std::string body;
  7445. auto res = cli_.Patch(
  7446. "/patch-loopback", 9,
  7447. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7448. EXPECT_EQ(9u, length);
  7449. sink.write("123", 3);
  7450. sink.write("456", 3);
  7451. sink.write("789", 3);
  7452. return true;
  7453. },
  7454. "text/plain",
  7455. [&body](const char *data, size_t data_length) {
  7456. body.append(data, data_length);
  7457. return true;
  7458. });
  7459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7460. EXPECT_EQ(StatusCode::OK_200, res->status);
  7461. EXPECT_EQ("123456789", body);
  7462. }
  7463. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7464. std::string body;
  7465. auto res = cli_.Post(
  7466. "/post-loopback",
  7467. [](size_t /*offset*/, DataSink &sink) {
  7468. sink.write("123", 3);
  7469. sink.write("456", 3);
  7470. sink.write("789", 3);
  7471. sink.done();
  7472. return true;
  7473. },
  7474. "text/plain",
  7475. [&body](const char *data, size_t data_length) {
  7476. body.append(data, data_length);
  7477. return true;
  7478. });
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::OK_200, res->status);
  7481. EXPECT_EQ("123456789", body);
  7482. }
  7483. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7484. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7485. cli_.set_compress(true);
  7486. auto res = cli_.Put(
  7487. "/put", 3,
  7488. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7489. sink.os << "PUT";
  7490. return true;
  7491. },
  7492. "text/plain");
  7493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7494. EXPECT_EQ(StatusCode::OK_200, res->status);
  7495. EXPECT_EQ("PUT", res->body);
  7496. }
  7497. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7498. cli_.set_compress(true);
  7499. auto res = cli_.Post(
  7500. "/post", 42,
  7501. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7502. return false;
  7503. },
  7504. "text/plain");
  7505. ASSERT_TRUE(!res);
  7506. EXPECT_EQ(Error::Canceled, res.error());
  7507. }
  7508. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7509. cli_.set_compress(true);
  7510. auto res = cli_.Put(
  7511. "/put",
  7512. [](size_t /*offset*/, DataSink &sink) {
  7513. sink.os << "PUT";
  7514. sink.done();
  7515. return true;
  7516. },
  7517. "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ("PUT", res->body);
  7521. }
  7522. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7523. cli_.set_compress(true);
  7524. auto res = cli_.Post(
  7525. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7526. "text/plain");
  7527. ASSERT_TRUE(!res);
  7528. EXPECT_EQ(Error::Canceled, res.error());
  7529. }
  7530. TEST_F(ServerTest, PutLargeFileWithGzip) {
  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. }
  7537. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7538. #ifdef CPPHTTPLIB_SSL_ENABLED
  7539. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7540. Client cli(s.c_str());
  7541. cli.enable_server_certificate_verification(false);
  7542. #else
  7543. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7544. Client cli(s.c_str());
  7545. #endif
  7546. cli.set_compress(true);
  7547. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7549. EXPECT_EQ(StatusCode::OK_200, res->status);
  7550. EXPECT_EQ(LARGE_DATA, res->body);
  7551. // The compressed size should be less than a 10th of the original. May vary
  7552. // depending on the zlib library.
  7553. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7554. static_cast<uint64_t>(10 * 1024 * 1024));
  7555. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7556. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7557. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7558. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7559. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7560. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7561. #endif
  7562. }
  7563. TEST_F(ServerTest, PutContentWithDeflate) {
  7564. cli_.set_compress(false);
  7565. Headers headers;
  7566. headers.emplace("Content-Encoding", "deflate");
  7567. // PUT in deflate format:
  7568. auto res = cli_.Put("/put", headers,
  7569. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. EXPECT_EQ("PUT", res->body);
  7573. }
  7574. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7575. Headers headers;
  7576. headers.emplace("Accept-Encoding", "gzip, deflate");
  7577. auto res = cli_.Get("/streamed-chunked", headers);
  7578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7579. EXPECT_EQ(StatusCode::OK_200, res->status);
  7580. EXPECT_EQ(std::string("123456789"), res->body);
  7581. }
  7582. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7583. Headers headers;
  7584. headers.emplace("Accept-Encoding", "gzip, deflate");
  7585. auto res = cli_.Get("/streamed-chunked2", headers);
  7586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7587. EXPECT_EQ(StatusCode::OK_200, res->status);
  7588. EXPECT_EQ(std::string("123456789"), res->body);
  7589. }
  7590. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7591. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_EQ(StatusCode::OK_200, res->status);
  7594. }
  7595. TEST(GzipDecompressor, ChunkedDecompression) {
  7596. std::string data;
  7597. for (size_t i = 0; i < 32 * 1024; ++i) {
  7598. data.push_back(static_cast<char>('a' + i % 26));
  7599. }
  7600. std::string compressed_data;
  7601. {
  7602. httplib::detail::gzip_compressor compressor;
  7603. bool result = compressor.compress(
  7604. data.data(), data.size(),
  7605. /*last=*/true,
  7606. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7607. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7608. compressed_data_size);
  7609. return true;
  7610. });
  7611. ASSERT_TRUE(result);
  7612. }
  7613. std::string decompressed_data;
  7614. {
  7615. httplib::detail::gzip_decompressor decompressor;
  7616. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7617. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7618. size_t chunk_size = 130;
  7619. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7620. chunk_begin += chunk_size) {
  7621. size_t current_chunk_size =
  7622. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7623. bool result = decompressor.decompress(
  7624. compressed_data.data() + chunk_begin, current_chunk_size,
  7625. [&](const char *decompressed_data_chunk,
  7626. size_t decompressed_data_chunk_size) {
  7627. decompressed_data.insert(decompressed_data.size(),
  7628. decompressed_data_chunk,
  7629. decompressed_data_chunk_size);
  7630. return true;
  7631. });
  7632. ASSERT_TRUE(result);
  7633. }
  7634. }
  7635. ASSERT_EQ(data, decompressed_data);
  7636. }
  7637. TEST(GzipDecompressor, DeflateDecompression) {
  7638. std::string original_text = "Raw deflate without gzip";
  7639. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7640. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7641. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7642. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7643. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7644. std::string decompressed_data;
  7645. {
  7646. httplib::detail::gzip_decompressor decompressor;
  7647. bool result = decompressor.decompress(
  7648. compressed_data.data(), compressed_data.size(),
  7649. [&](const char *decompressed_data_chunk,
  7650. size_t decompressed_data_chunk_size) {
  7651. decompressed_data.insert(decompressed_data.size(),
  7652. decompressed_data_chunk,
  7653. decompressed_data_chunk_size);
  7654. return true;
  7655. });
  7656. ASSERT_TRUE(result);
  7657. }
  7658. ASSERT_EQ(original_text, decompressed_data);
  7659. }
  7660. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7661. std::string original_text = "Raw deflate without gzip";
  7662. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7663. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7664. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7665. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7666. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7667. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7668. std::string decompressed_data;
  7669. {
  7670. httplib::detail::gzip_decompressor decompressor;
  7671. bool result = decompressor.decompress(
  7672. compressed_data.data(), compressed_data.size(),
  7673. [&](const char *decompressed_data_chunk,
  7674. size_t decompressed_data_chunk_size) {
  7675. decompressed_data.insert(decompressed_data.size(),
  7676. decompressed_data_chunk,
  7677. decompressed_data_chunk_size);
  7678. return true;
  7679. });
  7680. ASSERT_TRUE(result);
  7681. }
  7682. ASSERT_EQ(original_text, decompressed_data);
  7683. }
  7684. #endif
  7685. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7686. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7687. Headers headers;
  7688. headers.emplace("Accept-Encoding", "br");
  7689. auto res = cli_.Get("/streamed-chunked", headers);
  7690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7691. EXPECT_EQ(StatusCode::OK_200, res->status);
  7692. EXPECT_EQ(std::string("123456789"), res->body);
  7693. }
  7694. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7695. Headers headers;
  7696. headers.emplace("Accept-Encoding", "br");
  7697. auto res = cli_.Get("/streamed-chunked2", headers);
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ(std::string("123456789"), res->body);
  7701. }
  7702. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7703. cli_.set_compress(true);
  7704. auto res = cli_.Put(
  7705. "/put", 3,
  7706. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7707. sink.os << "PUT";
  7708. return true;
  7709. },
  7710. "text/plain");
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::OK_200, res->status);
  7713. EXPECT_EQ("PUT", res->body);
  7714. }
  7715. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7716. cli_.set_compress(true);
  7717. auto res = cli_.Put(
  7718. "/put",
  7719. [](size_t /*offset*/, DataSink &sink) {
  7720. sink.os << "PUT";
  7721. sink.done();
  7722. return true;
  7723. },
  7724. "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PUT", res->body);
  7728. }
  7729. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7730. cli_.set_compress(true);
  7731. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::OK_200, res->status);
  7734. EXPECT_EQ(LARGE_DATA, res->body);
  7735. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7736. }
  7737. #endif
  7738. TEST_F(ServerTest, Patch) {
  7739. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res->status);
  7742. EXPECT_EQ("PATCH", res->body);
  7743. }
  7744. TEST_F(ServerTest, Delete) {
  7745. auto res = cli_.Delete("/delete");
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. EXPECT_EQ("DELETE", res->body);
  7749. }
  7750. TEST_F(ServerTest, DeleteContentReceiver) {
  7751. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_EQ("content", res->body);
  7755. }
  7756. TEST_F(ServerTest, Options) {
  7757. auto res = cli_.Options("*");
  7758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7759. EXPECT_EQ(StatusCode::OK_200, res->status);
  7760. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7761. EXPECT_TRUE(res->body.empty());
  7762. }
  7763. TEST_F(ServerTest, URL) {
  7764. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. }
  7768. TEST_F(ServerTest, ArrayParam) {
  7769. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. }
  7773. TEST_F(ServerTest, ArrayParamValues) {
  7774. auto res =
  7775. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. }
  7779. TEST_F(ServerTest, NoMultipleHeaders) {
  7780. Headers headers = {{"Content-Length", "5"}};
  7781. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7782. "text/plain");
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::OK_200, res->status);
  7785. }
  7786. TEST_F(ServerTest, PostContentReceiver) {
  7787. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. ASSERT_EQ(StatusCode::OK_200, res->status);
  7790. ASSERT_EQ("content", res->body);
  7791. }
  7792. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7793. UploadFormDataItems items = {
  7794. {"text1", "text default", "", ""},
  7795. {"text2", "aωb", "", ""},
  7796. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7797. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7798. {"file3", "", "", "application/octet-stream"},
  7799. };
  7800. auto res = cli_.Post("/content_receiver", items);
  7801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7802. EXPECT_EQ(StatusCode::OK_200, res->status);
  7803. }
  7804. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7805. UploadFormDataItems items = {
  7806. {"text1", "text default", "", ""},
  7807. {"text2", "aωb", "", ""},
  7808. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7809. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7810. {"file3", "", "", "application/octet-stream"},
  7811. };
  7812. auto boundary = std::string("+++++");
  7813. std::string body;
  7814. for (const auto &item : items) {
  7815. body += "--" + boundary + "\r\n";
  7816. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7817. if (!item.filename.empty()) {
  7818. body += "; filename=\"" + item.filename + "\"";
  7819. }
  7820. body += "\r\n";
  7821. if (!item.content_type.empty()) {
  7822. body += "Content-Type: " + item.content_type + "\r\n";
  7823. }
  7824. body += "\r\n";
  7825. body += item.content + "\r\n";
  7826. }
  7827. body += "--" + boundary + "--\r\n";
  7828. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7829. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7831. EXPECT_EQ(StatusCode::OK_200, res->status);
  7832. }
  7833. TEST(MultipartFormDataTest, FieldEscaping) {
  7834. Server svr;
  7835. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7836. const ContentReader &content_reader) {
  7837. ASSERT_TRUE(req.is_multipart_form_data());
  7838. std::vector<FormData> received;
  7839. content_reader(
  7840. [&](const FormData &file) {
  7841. received.push_back(file);
  7842. return true;
  7843. },
  7844. [&](const char *data, size_t data_length) {
  7845. received.back().content.append(data, data_length);
  7846. return true;
  7847. });
  7848. // '"', CR and LF in names and filenames are escaped following the
  7849. // WHATWG HTML standard, so each part still parses as a single part
  7850. // with no injected headers. Content types get CR/LF escaped too,
  7851. // while '"' (legal there, e.g. quoted charset) is preserved.
  7852. ASSERT_EQ(4U, received.size());
  7853. EXPECT_EQ("na%22me", received[0].name);
  7854. EXPECT_EQ("quoted name", received[0].content);
  7855. EXPECT_EQ("file", received[1].name);
  7856. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7857. received[1].filename);
  7858. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7859. EXPECT_EQ("injected", received[1].content);
  7860. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7861. EXPECT_EQ("my%22file.txt", received[2].filename);
  7862. EXPECT_EQ("cr lf name", received[2].content);
  7863. EXPECT_EQ("typed", received[3].name);
  7864. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7865. received[3].content_type);
  7866. EXPECT_EQ("typed content", received[3].content);
  7867. });
  7868. auto port = svr.bind_to_any_port("localhost");
  7869. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7870. auto se = detail::scope_exit([&] {
  7871. svr.stop();
  7872. t.join();
  7873. ASSERT_FALSE(svr.is_running());
  7874. });
  7875. svr.wait_until_ready();
  7876. Client cli("localhost", port);
  7877. UploadFormDataItems items = {
  7878. {"na\"me", "quoted name", "", ""},
  7879. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7880. "application/octet-stream"},
  7881. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7882. {"typed", "typed content", "",
  7883. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7884. };
  7885. auto res = cli.Post("/post", items);
  7886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7890. const UploadFormDataItems items = {
  7891. {"name1", "Content 1", "", ""},
  7892. {"name2", "Content 2", "file2.txt", "text/plain"},
  7893. };
  7894. Server svr;
  7895. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7896. const ContentReader &content_reader) {
  7897. ASSERT_TRUE(req.is_multipart_form_data());
  7898. std::vector<FormData> received;
  7899. content_reader(
  7900. [&](const FormData &file) {
  7901. received.push_back(file);
  7902. return true;
  7903. },
  7904. [&](const char *data, size_t data_length) {
  7905. received.back().content.append(data, data_length);
  7906. return true;
  7907. });
  7908. ASSERT_EQ(2U, received.size());
  7909. EXPECT_EQ("name1", received[0].name);
  7910. EXPECT_EQ("Content 1", received[0].content);
  7911. EXPECT_EQ("name2", received[1].name);
  7912. EXPECT_EQ("Content 2", received[1].content);
  7913. EXPECT_EQ("file2.txt", received[1].filename);
  7914. EXPECT_EQ("text/plain", received[1].content_type);
  7915. });
  7916. auto port = svr.bind_to_any_port("localhost");
  7917. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7918. auto se = detail::scope_exit([&] {
  7919. svr.stop();
  7920. t.join();
  7921. ASSERT_FALSE(svr.is_running());
  7922. });
  7923. svr.wait_until_ready();
  7924. Client cli("localhost", port);
  7925. // Whole-body serialization with a generated boundary
  7926. {
  7927. MultipartFormDataWriter writer;
  7928. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7929. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7930. writer.content_type());
  7931. auto body = writer.serialize(items);
  7932. EXPECT_EQ(body.size(), writer.content_length(items));
  7933. auto res = cli.Post("/post", body, writer.content_type());
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::OK_200, res->status);
  7936. }
  7937. // Per-part framing with a custom boundary via a content provider
  7938. {
  7939. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7940. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7941. MultipartFormDataWriter writer("custom-boundary_123");
  7942. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7943. std::string body;
  7944. for (const auto &item : items) {
  7945. body += writer.item_begin(item);
  7946. body += item.content;
  7947. body += MultipartFormDataWriter::item_end();
  7948. }
  7949. body += writer.finish();
  7950. EXPECT_EQ(body.size(), writer.content_length(items));
  7951. auto res = cli.Post(
  7952. "/post", body.size(),
  7953. [&](size_t offset, size_t length, DataSink &sink) {
  7954. sink.write(body.data() + offset, length);
  7955. return true;
  7956. },
  7957. writer.content_type());
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::OK_200, res->status);
  7960. }
  7961. }
  7962. TEST_F(ServerTest, PostContentReceiverGzip) {
  7963. cli_.set_compress(true);
  7964. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7966. ASSERT_EQ(StatusCode::OK_200, res->status);
  7967. ASSERT_EQ("content", res->body);
  7968. }
  7969. TEST_F(ServerTest, PutContentReceiver) {
  7970. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7972. ASSERT_EQ(StatusCode::OK_200, res->status);
  7973. ASSERT_EQ("content", res->body);
  7974. }
  7975. TEST_F(ServerTest, PatchContentReceiver) {
  7976. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. ASSERT_EQ(StatusCode::OK_200, res->status);
  7979. ASSERT_EQ("content", res->body);
  7980. }
  7981. template <typename ClientType>
  7982. void TestWithHeadersAndContentReceiver(
  7983. ClientType &cli,
  7984. std::function<Result(ClientType &, const std::string &, const Headers &,
  7985. const std::string &, const std::string &,
  7986. ContentReceiver, DownloadProgress)>
  7987. request_func) {
  7988. Headers headers;
  7989. headers.emplace("X-Custom-Header", "test-value");
  7990. std::string received_body;
  7991. auto res = request_func(
  7992. cli, "/content_receiver", headers, "content", "application/json",
  7993. [&](const char *data, size_t data_length) {
  7994. received_body.append(data, data_length);
  7995. return true;
  7996. },
  7997. nullptr);
  7998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7999. EXPECT_EQ(StatusCode::OK_200, res->status);
  8000. EXPECT_EQ("content", received_body);
  8001. }
  8002. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8003. #ifdef CPPHTTPLIB_SSL_ENABLED
  8004. using ClientT = SSLClient;
  8005. #else
  8006. using ClientT = Client;
  8007. #endif
  8008. TestWithHeadersAndContentReceiver<ClientT>(
  8009. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8010. const std::string &body, const std::string &content_type,
  8011. ContentReceiver receiver, DownloadProgress progress) {
  8012. return cli.Post(path, headers, body, content_type, receiver, progress);
  8013. });
  8014. }
  8015. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8016. #ifdef CPPHTTPLIB_SSL_ENABLED
  8017. using ClientT = SSLClient;
  8018. #else
  8019. using ClientT = Client;
  8020. #endif
  8021. TestWithHeadersAndContentReceiver<ClientT>(
  8022. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8023. const std::string &body, const std::string &content_type,
  8024. ContentReceiver receiver, DownloadProgress progress) {
  8025. return cli.Put(path, headers, body, content_type, receiver, progress);
  8026. });
  8027. }
  8028. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8029. #ifdef CPPHTTPLIB_SSL_ENABLED
  8030. using ClientT = SSLClient;
  8031. #else
  8032. using ClientT = Client;
  8033. #endif
  8034. TestWithHeadersAndContentReceiver<ClientT>(
  8035. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8036. const std::string &body, const std::string &content_type,
  8037. ContentReceiver receiver, DownloadProgress progress) {
  8038. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8039. });
  8040. }
  8041. template <typename ClientType>
  8042. void TestWithHeadersAndContentReceiverWithProgress(
  8043. ClientType &cli,
  8044. std::function<Result(ClientType &, const std::string &, const Headers &,
  8045. const std::string &, const std::string &,
  8046. ContentReceiver, DownloadProgress)>
  8047. request_func) {
  8048. Headers headers;
  8049. headers.emplace("X-Test-Header", "progress-test");
  8050. std::string received_body;
  8051. auto progress_called = false;
  8052. auto res = request_func(
  8053. cli, "/content_receiver", headers, "content", "text/plain",
  8054. [&](const char *data, size_t data_length) {
  8055. received_body.append(data, data_length);
  8056. return true;
  8057. },
  8058. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8059. progress_called = true;
  8060. return true;
  8061. });
  8062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8063. EXPECT_EQ(StatusCode::OK_200, res->status);
  8064. EXPECT_EQ("content", received_body);
  8065. EXPECT_TRUE(progress_called);
  8066. }
  8067. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8068. #ifdef CPPHTTPLIB_SSL_ENABLED
  8069. using ClientT = SSLClient;
  8070. #else
  8071. using ClientT = Client;
  8072. #endif
  8073. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8074. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8075. const std::string &body, const std::string &content_type,
  8076. ContentReceiver receiver, DownloadProgress progress) {
  8077. return cli.Post(path, headers, body, content_type, receiver, progress);
  8078. });
  8079. }
  8080. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8081. #ifdef CPPHTTPLIB_SSL_ENABLED
  8082. using ClientT = SSLClient;
  8083. #else
  8084. using ClientT = Client;
  8085. #endif
  8086. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8087. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8088. const std::string &body, const std::string &content_type,
  8089. ContentReceiver receiver, DownloadProgress progress) {
  8090. return cli.Put(path, headers, body, content_type, receiver, progress);
  8091. });
  8092. }
  8093. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8094. #ifdef CPPHTTPLIB_SSL_ENABLED
  8095. using ClientT = SSLClient;
  8096. #else
  8097. using ClientT = Client;
  8098. #endif
  8099. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8100. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8101. const std::string &body, const std::string &content_type,
  8102. ContentReceiver receiver, DownloadProgress progress) {
  8103. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8104. });
  8105. }
  8106. template <typename ClientType>
  8107. void TestWithHeadersAndContentReceiverError(
  8108. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8109. const Headers &, const std::string &,
  8110. const std::string &, ContentReceiver)>
  8111. request_func) {
  8112. Headers headers;
  8113. headers.emplace("X-Error-Test", "true");
  8114. std::string received_body;
  8115. auto receiver_failed = false;
  8116. auto res =
  8117. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8118. [&](const char *data, size_t data_length) {
  8119. received_body.append(data, data_length);
  8120. receiver_failed = true;
  8121. return false;
  8122. });
  8123. ASSERT_FALSE(res);
  8124. EXPECT_TRUE(receiver_failed);
  8125. }
  8126. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8127. #ifdef CPPHTTPLIB_SSL_ENABLED
  8128. using ClientT = SSLClient;
  8129. #else
  8130. using ClientT = Client;
  8131. #endif
  8132. TestWithHeadersAndContentReceiverError<ClientT>(
  8133. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8134. const std::string &body, const std::string &content_type,
  8135. ContentReceiver receiver) {
  8136. return cli.Post(path, headers, body, content_type, receiver);
  8137. });
  8138. }
  8139. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8140. #ifdef CPPHTTPLIB_SSL_ENABLED
  8141. using ClientT = SSLClient;
  8142. #else
  8143. using ClientT = Client;
  8144. #endif
  8145. TestWithHeadersAndContentReceiverError<ClientT>(
  8146. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8147. const std::string &body, const std::string &content_type,
  8148. ContentReceiver receiver) {
  8149. return cli.Put(path, headers, body, content_type, receiver);
  8150. });
  8151. }
  8152. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8153. #ifdef CPPHTTPLIB_SSL_ENABLED
  8154. using ClientT = SSLClient;
  8155. #else
  8156. using ClientT = Client;
  8157. #endif
  8158. TestWithHeadersAndContentReceiverError<ClientT>(
  8159. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8160. const std::string &body, const std::string &content_type,
  8161. ContentReceiver receiver) {
  8162. return cli.Patch(path, headers, body, content_type, receiver);
  8163. });
  8164. }
  8165. TEST_F(ServerTest, PostQueryStringAndBody) {
  8166. auto res =
  8167. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8169. ASSERT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. TEST_F(ServerTest, HTTP2Magic) {
  8172. Request req;
  8173. req.method = "PRI";
  8174. req.path = "*";
  8175. req.body = "SM";
  8176. auto res = std::make_shared<Response>();
  8177. auto error = Error::Success;
  8178. auto ret = cli_.send(req, *res, error);
  8179. ASSERT_TRUE(ret);
  8180. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8181. }
  8182. TEST_F(ServerTest, KeepAlive) {
  8183. auto res = cli_.Get("/hi");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::OK_200, res->status);
  8186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8187. EXPECT_EQ("Hello World!", res->body);
  8188. res = cli_.Get("/hi");
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8192. EXPECT_EQ("Hello World!", res->body);
  8193. res = cli_.Get("/hi");
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(StatusCode::OK_200, res->status);
  8196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8197. EXPECT_EQ("Hello World!", res->body);
  8198. res = cli_.Get("/not-exist");
  8199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8201. res = cli_.Post("/empty", "", "text/plain");
  8202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8203. EXPECT_EQ(StatusCode::OK_200, res->status);
  8204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8205. EXPECT_EQ("empty", res->body);
  8206. EXPECT_EQ("close", res->get_header_value("Connection"));
  8207. res = cli_.Post(
  8208. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8209. "text/plain");
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8213. EXPECT_EQ("empty", res->body);
  8214. cli_.set_keep_alive(false);
  8215. res = cli_.Get("/last-request");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. EXPECT_EQ("close", res->get_header_value("Connection"));
  8219. }
  8220. TEST_F(ServerTest, TooManyRedirect) {
  8221. cli_.set_follow_location(true);
  8222. auto res = cli_.Get("/redirect/0");
  8223. ASSERT_TRUE(!res);
  8224. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8225. }
  8226. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8227. Request req;
  8228. req.method = "FOOBAR";
  8229. req.path = "/hi";
  8230. cli_.set_keep_alive(true);
  8231. auto res = cli_.send(req);
  8232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8233. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8234. EXPECT_EQ("close", res->get_header_value("Connection"));
  8235. EXPECT_FALSE(cli_.is_socket_open());
  8236. }
  8237. TEST_F(ServerTest, CustomRouteReadsBody) {
  8238. const std::string xml =
  8239. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8240. Request req;
  8241. req.method = "PROPFIND";
  8242. req.path = "/dav/dir";
  8243. req.set_header("Depth", "1");
  8244. req.body = xml;
  8245. auto res = cli_.send(req);
  8246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8247. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8248. EXPECT_EQ(xml, res->body);
  8249. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8250. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8251. }
  8252. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8253. Request req;
  8254. req.method = "PROPFIND";
  8255. req.path = "/dav/42";
  8256. auto res = cli_.send(req);
  8257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8258. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8259. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8260. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8261. }
  8262. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8263. Request req;
  8264. req.method = "PROPFIND";
  8265. req.path = "/dav-re/123";
  8266. auto res = cli_.send(req);
  8267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8268. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8269. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8270. }
  8271. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8272. Request req;
  8273. req.method = "MKCOL";
  8274. req.path = "/dav-mkcol";
  8275. auto res = cli_.send(req);
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::Created_201, res->status);
  8278. }
  8279. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8280. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8281. Request req;
  8282. req.method = "REPORT";
  8283. req.path = "/dav-report";
  8284. req.body = xml;
  8285. auto res = cli_.send(req);
  8286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8287. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8288. EXPECT_EQ(xml, res->body);
  8289. }
  8290. // A content reader route must fire even when the request carries no body,
  8291. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8292. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8293. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8294. Request req;
  8295. req.method = "REPORT";
  8296. req.path = "/dav-report";
  8297. auto res = cli_.send(req);
  8298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8299. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8300. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8301. }
  8302. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8303. Request req;
  8304. req.method = "PROPFIND";
  8305. req.path = "/not-dav";
  8306. auto res = cli_.send(req);
  8307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8309. }
  8310. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8311. Request req;
  8312. req.method = "UNLOCK";
  8313. req.path = "/dav/dir";
  8314. cli_.set_keep_alive(true);
  8315. auto res = cli_.send(req);
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8318. EXPECT_EQ("close", res->get_header_value("Connection"));
  8319. EXPECT_FALSE(cli_.is_socket_open());
  8320. }
  8321. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8322. // The mount point serves this path, but only for GET and HEAD.
  8323. auto get_res = cli_.Get("/dir/index.html");
  8324. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8325. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8326. Request req;
  8327. req.method = "PROPFIND";
  8328. req.path = "/dir/index.html";
  8329. auto res = cli_.send(req);
  8330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8331. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8332. }
  8333. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8334. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8335. cli_.set_keep_alive(true);
  8336. for (auto i = 0; i < 2; i++) {
  8337. Request req;
  8338. req.method = "PROPFIND";
  8339. req.path = "/dav/dir";
  8340. req.body = xml;
  8341. auto res = cli_.send(req);
  8342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8343. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8344. EXPECT_EQ(xml, res->body);
  8345. EXPECT_TRUE(cli_.is_socket_open());
  8346. }
  8347. // A built-in method must still be served on the same connection.
  8348. cli_.set_keep_alive(false);
  8349. auto res = cli_.Get("/hi");
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ(StatusCode::OK_200, res->status);
  8352. EXPECT_EQ("close", res->get_header_value("Connection"));
  8353. }
  8354. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8355. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8356. Request req;
  8357. req.method = "PROPFIND";
  8358. req.path = "/dav/dir";
  8359. req.set_header("Expect", "100-continue");
  8360. req.body = xml;
  8361. auto res = cli_.send(req);
  8362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8363. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8364. EXPECT_EQ(xml, res->body);
  8365. }
  8366. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8367. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8368. TEST_F(ServerTest, Gzip) {
  8369. Headers headers;
  8370. headers.emplace("Accept-Encoding", "gzip, deflate");
  8371. auto res = cli_.Get("/compress", headers);
  8372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8373. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8374. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8375. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8376. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8377. "7890123456789012345678901234567890",
  8378. res->body);
  8379. EXPECT_EQ(StatusCode::OK_200, res->status);
  8380. }
  8381. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8382. Headers headers;
  8383. headers.emplace("Accept-Encoding", "gzip, deflate");
  8384. auto res = cli_.Get("/compress-with-charset", headers);
  8385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8386. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8387. EXPECT_EQ("application/json; charset=utf-8",
  8388. res->get_header_value("Content-Type"));
  8389. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8390. "7890123456789012345678901234567890",
  8391. res->body);
  8392. EXPECT_EQ(StatusCode::OK_200, res->status);
  8393. }
  8394. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8395. Headers headers;
  8396. headers.emplace("Accept-Encoding", "");
  8397. auto res = cli_.Get("/compress", headers);
  8398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8399. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8400. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8401. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8402. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8403. "7890123456789012345678901234567890",
  8404. res->body);
  8405. EXPECT_EQ(StatusCode::OK_200, res->status);
  8406. }
  8407. TEST_F(ServerTest, GzipWithContentReceiver) {
  8408. Headers headers;
  8409. headers.emplace("Accept-Encoding", "gzip, deflate");
  8410. std::string body;
  8411. auto res =
  8412. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8413. EXPECT_EQ(100U, data_length);
  8414. body.append(data, data_length);
  8415. return true;
  8416. });
  8417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8418. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8419. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8420. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8421. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8422. "7890123456789012345678901234567890",
  8423. body);
  8424. EXPECT_EQ(StatusCode::OK_200, res->status);
  8425. }
  8426. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8427. Headers headers;
  8428. headers.emplace("Accept-Encoding", "gzip, deflate");
  8429. cli_.set_decompress(false);
  8430. auto res = cli_.Get("/compress", headers);
  8431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8432. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8434. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8435. EXPECT_EQ(33U, res->body.size());
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. }
  8438. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8439. Headers headers;
  8440. headers.emplace("Accept-Encoding", "");
  8441. std::string body;
  8442. auto res =
  8443. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8444. EXPECT_EQ(100U, data_length);
  8445. body.append(data, data_length);
  8446. return true;
  8447. });
  8448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8449. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8451. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8452. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8453. "7890123456789012345678901234567890",
  8454. body);
  8455. EXPECT_EQ(StatusCode::OK_200, res->status);
  8456. }
  8457. TEST_F(ServerTest, NoGzip) {
  8458. Headers headers;
  8459. headers.emplace("Accept-Encoding", "gzip, deflate");
  8460. auto res = cli_.Get("/nocompress", headers);
  8461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8462. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8463. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8464. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8465. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8466. "7890123456789012345678901234567890",
  8467. res->body);
  8468. EXPECT_EQ(StatusCode::OK_200, res->status);
  8469. }
  8470. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8471. Headers headers;
  8472. headers.emplace("Accept-Encoding", "gzip, deflate");
  8473. std::string body;
  8474. auto res = cli_.Get("/nocompress", headers,
  8475. [&](const char *data, size_t data_length) {
  8476. EXPECT_EQ(100U, data_length);
  8477. body.append(data, data_length);
  8478. return true;
  8479. });
  8480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8481. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8482. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8483. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8484. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8485. "7890123456789012345678901234567890",
  8486. body);
  8487. EXPECT_EQ(StatusCode::OK_200, res->status);
  8488. }
  8489. TEST_F(ServerTest, MultipartFormDataGzip) {
  8490. UploadFormDataItems items = {
  8491. {"key1", "test", "", ""},
  8492. {"key2", "--abcdefg123", "", ""},
  8493. };
  8494. cli_.set_compress(true);
  8495. auto res = cli_.Post("/compress-multipart", items);
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::OK_200, res->status);
  8498. }
  8499. #endif
  8500. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8501. // Static file compression is opt-in, so these run their own server rather than
  8502. // flipping it on for the shared ServerTest fixture, which would silently
  8503. // rewrite what every other static file test is asserting.
  8504. class StaticFileCompressionTest : public ::testing::Test {
  8505. protected:
  8506. void TearDown() override {
  8507. if (t_.joinable()) {
  8508. svr_.stop();
  8509. t_.join();
  8510. }
  8511. }
  8512. int start(const std::function<void(Server &)> &configure = nullptr) {
  8513. // Serves the same tree as a directory of build-time compressed assets
  8514. // would be served: the mount point names the coding the files are already
  8515. // stored in. Registered before "/" so it is the one that matches.
  8516. svr_.set_mount_point("/pre-encoded", "./www",
  8517. {{"Content-Encoding", "gzip"}});
  8518. svr_.set_mount_point("/", "./www");
  8519. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8520. res.set_file_content("./www/dir/index.html", "text/html");
  8521. });
  8522. svr_.Get("/pre-encoded-file-content",
  8523. [](const Request & /*req*/, Response &res) {
  8524. res.set_header("Content-Encoding", "gzip");
  8525. res.set_file_content("./www/dir/index.html", "text/html");
  8526. });
  8527. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8528. res.set_content_provider(
  8529. 6, "text/plain",
  8530. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8531. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8532. return true;
  8533. });
  8534. });
  8535. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8536. res.set_content_provider(
  8537. 1000, "text/plain",
  8538. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8539. if (offset < 100) {
  8540. std::string data(100, 'A');
  8541. sink.write(data.data(), data.size());
  8542. return true;
  8543. }
  8544. std::this_thread::sleep_for(std::chrono::seconds(2));
  8545. std::string data(900, 'B');
  8546. sink.write(data.data(), data.size());
  8547. return true;
  8548. });
  8549. });
  8550. if (configure) { configure(svr_); }
  8551. auto port = svr_.bind_to_any_port(HOST);
  8552. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8553. svr_.wait_until_ready();
  8554. return port;
  8555. }
  8556. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8557. // Every file under ./www except 1MB.txt is smaller than the default
  8558. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8559. // it out of the way.
  8560. static void enable_without_floor(Server &svr) {
  8561. svr.set_static_file_compression(true);
  8562. svr.set_static_file_compression_min_length(0);
  8563. }
  8564. Server svr_;
  8565. std::thread t_;
  8566. };
  8567. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8568. auto port = start();
  8569. Client cli(HOST, port);
  8570. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8572. EXPECT_EQ(StatusCode::OK_200, res->status);
  8573. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8574. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8575. EXPECT_EQ(1048576U, res->body.size());
  8576. }
  8577. TEST_F(StaticFileCompressionTest, MountPoint) {
  8578. auto port = start(enable);
  8579. Client cli(HOST, port);
  8580. cli.set_decompress(false);
  8581. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8583. EXPECT_EQ(StatusCode::OK_200, res->status);
  8584. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8585. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8586. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8587. // The response stays self-delimiting: a length, not a chunked body.
  8588. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8589. EXPECT_EQ(std::to_string(res->body.size()),
  8590. res->get_header_value("Content-Length"));
  8591. EXPECT_LT(res->body.size(), 1048576U);
  8592. EXPECT_FALSE(res->body.empty());
  8593. }
  8594. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8595. auto port = start(enable);
  8596. Client cli(HOST, port);
  8597. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8599. EXPECT_EQ(StatusCode::OK_200, res->status);
  8600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8601. EXPECT_EQ(1048576U, res->body.size());
  8602. }
  8603. TEST_F(StaticFileCompressionTest, FileContent) {
  8604. auto port = start(enable_without_floor);
  8605. Client cli(HOST, port);
  8606. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8608. EXPECT_EQ(StatusCode::OK_200, res->status);
  8609. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8610. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8611. EXPECT_EQ(104U, res->body.size());
  8612. }
  8613. // A handler that serves an already-encoded file names the coding itself. The
  8614. // file-backed path decided its coding from Accept-Encoding and the content
  8615. // type alone, so it compressed the stored bytes a second time and appended a
  8616. // second Content-Encoding field line.
  8617. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8618. auto port = start(enable_without_floor);
  8619. Client cli(HOST, port);
  8620. cli.set_decompress(false);
  8621. auto res = cli.Get("/pre-encoded-file-content",
  8622. Headers{{"Accept-Encoding", "gzip"}});
  8623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8624. EXPECT_EQ(StatusCode::OK_200, res->status);
  8625. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8626. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8627. // Vary belongs to a coding the server chose, and it chose none here.
  8628. EXPECT_FALSE(res->has_header("Vary"));
  8629. // The file travels exactly as it is stored on disk.
  8630. EXPECT_EQ(104U, res->body.size());
  8631. }
  8632. // The 1MB file clears the default floor, so this one runs the configuration a
  8633. // deployment would actually have.
  8634. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8635. auto port = start(enable);
  8636. Client cli(HOST, port);
  8637. cli.set_decompress(false);
  8638. auto res =
  8639. cli.Get("/pre-encoded/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(1U, res->get_header_value_count("Content-Encoding"));
  8643. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8644. EXPECT_FALSE(res->has_header("Vary"));
  8645. EXPECT_EQ(1048576U, res->body.size());
  8646. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8647. }
  8648. TEST_F(StaticFileCompressionTest, Head) {
  8649. auto port = start(enable);
  8650. Client cli(HOST, port);
  8651. cli.set_decompress(false);
  8652. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8653. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8654. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8656. EXPECT_EQ(StatusCode::OK_200, res->status);
  8657. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8658. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8659. // HEAD still reports the size a GET would return.
  8660. EXPECT_EQ(get->get_header_value("Content-Length"),
  8661. res->get_header_value("Content-Length"));
  8662. EXPECT_TRUE(res->body.empty());
  8663. }
  8664. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8665. auto port = start(enable);
  8666. Client cli(HOST, port);
  8667. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8668. {"Accept-Encoding", "gzip"}});
  8669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8670. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8671. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8672. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8673. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8674. EXPECT_EQ("cd", res->body);
  8675. }
  8676. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8677. auto port = start(enable);
  8678. Client cli(HOST, port);
  8679. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8681. EXPECT_EQ(StatusCode::OK_200, res->status);
  8682. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8683. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8684. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8685. }
  8686. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8687. auto port = start(enable);
  8688. Client cli(HOST, port);
  8689. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8691. EXPECT_EQ(StatusCode::OK_200, res->status);
  8692. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8693. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8694. EXPECT_TRUE(res->body.empty());
  8695. }
  8696. TEST_F(StaticFileCompressionTest, MinLength) {
  8697. auto port = start(enable);
  8698. Client cli(HOST, port);
  8699. // 104 bytes, well under the default floor. Compressing it would add the
  8700. // gzip header and trailer to a body that already fits in one packet.
  8701. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8703. EXPECT_EQ(StatusCode::OK_200, res->status);
  8704. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8705. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8706. }
  8707. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8708. auto port = start([](Server &svr) {
  8709. svr.set_static_file_compression(true);
  8710. svr.set_static_file_compression_min_length(1);
  8711. });
  8712. Client cli(HOST, port);
  8713. cli.set_decompress(false);
  8714. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8716. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8717. // A 9-byte file comes back larger than it went in, because gzip's header and
  8718. // trailer outweigh anything deflate can save. That is the end of the range
  8719. // the floor exists to keep out.
  8720. EXPECT_GT(res->body.size(), 9U);
  8721. }
  8722. TEST_F(StaticFileCompressionTest, MaxLength) {
  8723. auto port = start([](Server &svr) {
  8724. svr.set_static_file_compression(true);
  8725. svr.set_static_file_compression_min_length(0);
  8726. svr.set_static_file_compression_max_length(1024);
  8727. });
  8728. Client cli(HOST, port);
  8729. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8730. // defines `small` as a macro on Windows.
  8731. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8732. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8733. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8734. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8735. // Under it: compressed.
  8736. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8738. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8739. }
  8740. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8741. auto port = start(enable_without_floor);
  8742. Client cli(HOST, port);
  8743. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8744. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8745. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8746. auto identity_etag = identity->get_header_value("ETag");
  8747. ASSERT_FALSE(identity_etag.empty());
  8748. auto gzipped =
  8749. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8750. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8751. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8752. auto gzip_etag = gzipped->get_header_value("ETag");
  8753. ASSERT_FALSE(gzip_etag.empty());
  8754. // Two representations, two validators.
  8755. EXPECT_NE(identity_etag, gzip_etag);
  8756. // Each one revalidates against the request that would produce it...
  8757. auto fresh =
  8758. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8759. {"If-None-Match", gzip_etag}});
  8760. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8761. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8762. auto fresh_identity =
  8763. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8764. {"If-None-Match", identity_etag}});
  8765. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8766. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8767. // ...and not against the other representation.
  8768. auto crossed =
  8769. cli.Get("/dir/index.html",
  8770. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8771. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8772. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8773. }
  8774. // The opt-in covers responses the server reads off disk itself. A caller's own
  8775. // known-length provider keeps its Content-Length and, more importantly, keeps
  8776. // delivering incrementally: routing it through a compressor would hold every
  8777. // write back until zlib's window filled.
  8778. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8779. auto port = start(enable);
  8780. Client cli(HOST, port);
  8781. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8783. EXPECT_EQ(StatusCode::OK_200, res->status);
  8784. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8785. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8786. EXPECT_EQ("aaabbb", res->body);
  8787. }
  8788. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8789. auto port = start(enable);
  8790. Client cli(HOST, port);
  8791. cli.set_read_timeout(1, 0);
  8792. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8793. Headers{{"Accept-Encoding", "gzip"}});
  8794. ASSERT_TRUE(handle.is_valid());
  8795. // The provider writes 100 bytes and then stalls for longer than the read
  8796. // timeout. Those first bytes have to arrive anyway: run the response through
  8797. // a compressor and zlib holds them until its window fills, so the read would
  8798. // come back empty instead.
  8799. char buf[256];
  8800. auto n = handle.read(buf, sizeof(buf));
  8801. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8802. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8803. }
  8804. #endif
  8805. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8806. TEST_F(ServerTest, Brotli) {
  8807. Headers headers;
  8808. headers.emplace("Accept-Encoding", "br");
  8809. auto res = cli_.Get("/compress", headers);
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8813. EXPECT_EQ("19", 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. #endif
  8820. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8821. TEST_F(ServerTest, Zstd) {
  8822. Headers headers;
  8823. headers.emplace("Accept-Encoding", "zstd");
  8824. auto res = cli_.Get("/compress", headers);
  8825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8826. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8827. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8828. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8829. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8830. "7890123456789012345678901234567890",
  8831. res->body);
  8832. EXPECT_EQ(StatusCode::OK_200, res->status);
  8833. }
  8834. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8835. Headers headers;
  8836. headers.emplace("Accept-Encoding", "");
  8837. auto res = cli_.Get("/compress", headers);
  8838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8839. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8840. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8841. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8842. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8843. "7890123456789012345678901234567890",
  8844. res->body);
  8845. EXPECT_EQ(StatusCode::OK_200, res->status);
  8846. }
  8847. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8848. Headers headers;
  8849. headers.emplace("Accept-Encoding", "zstd");
  8850. std::string body;
  8851. auto res =
  8852. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8853. EXPECT_EQ(100U, data_length);
  8854. body.append(data, data_length);
  8855. return true;
  8856. });
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8860. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8861. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8862. "7890123456789012345678901234567890",
  8863. body);
  8864. EXPECT_EQ(StatusCode::OK_200, res->status);
  8865. }
  8866. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8867. Headers headers;
  8868. headers.emplace("Accept-Encoding", "zstd");
  8869. cli_.set_decompress(false);
  8870. auto res = cli_.Get("/compress", headers);
  8871. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8872. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8873. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8874. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8877. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8878. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8879. EXPECT_EQ(StatusCode::OK_200, res->status);
  8880. ASSERT_EQ(26U, res->body.size());
  8881. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8882. 0);
  8883. }
  8884. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8885. Headers headers;
  8886. headers.emplace("Accept-Encoding", "");
  8887. std::string body;
  8888. auto res =
  8889. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8890. EXPECT_EQ(100U, data_length);
  8891. body.append(data, data_length);
  8892. return true;
  8893. });
  8894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8895. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8897. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8898. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8899. "7890123456789012345678901234567890",
  8900. body);
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. }
  8903. TEST_F(ServerTest, NoZstd) {
  8904. Headers headers;
  8905. headers.emplace("Accept-Encoding", "zstd");
  8906. auto res = cli_.Get("/nocompress", headers);
  8907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8908. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8909. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8910. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8911. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8912. "7890123456789012345678901234567890",
  8913. res->body);
  8914. EXPECT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8917. Headers headers;
  8918. headers.emplace("Accept-Encoding", "zstd");
  8919. std::string body;
  8920. auto res = cli_.Get("/nocompress", headers,
  8921. [&](const char *data, size_t data_length) {
  8922. EXPECT_EQ(100U, data_length);
  8923. body.append(data, data_length);
  8924. return true;
  8925. });
  8926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8927. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8928. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8929. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8931. "7890123456789012345678901234567890",
  8932. body);
  8933. EXPECT_EQ(StatusCode::OK_200, res->status);
  8934. }
  8935. // TODO: How to enable zstd ??
  8936. TEST_F(ServerTest, MultipartFormDataZstd) {
  8937. UploadFormDataItems items = {
  8938. {"key1", "test", "", ""},
  8939. {"key2", "--abcdefg123", "", ""},
  8940. };
  8941. Headers headers;
  8942. headers.emplace("Accept-Encoding", "zstd");
  8943. cli_.set_compress(true);
  8944. auto res = cli_.Post("/compress-multipart", headers, items);
  8945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8946. EXPECT_EQ(StatusCode::OK_200, res->status);
  8947. }
  8948. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8949. Headers headers;
  8950. headers.emplace("Accept-Encoding", "zstd");
  8951. cli_.set_compress(true);
  8952. auto res = cli_.Put(
  8953. "/put", headers, 3,
  8954. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8955. sink.os << "PUT";
  8956. return true;
  8957. },
  8958. "text/plain");
  8959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8960. EXPECT_EQ(StatusCode::OK_200, res->status);
  8961. EXPECT_EQ("PUT", res->body);
  8962. }
  8963. // Pre-compression logging tests
  8964. TEST_F(ServerTest, PreCompressionLogging) {
  8965. // Test data for compression (matches the actual /compress endpoint content)
  8966. const std::string test_content =
  8967. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8968. "3456789012345678901234567890";
  8969. // Variables to capture logging data
  8970. std::string pre_compression_body;
  8971. std::string pre_compression_content_type;
  8972. std::string pre_compression_content_encoding;
  8973. std::string post_compression_body;
  8974. std::string post_compression_content_type;
  8975. std::string post_compression_content_encoding;
  8976. // Set up pre-compression logger
  8977. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8978. const Response &res) {
  8979. pre_compression_body = res.body;
  8980. pre_compression_content_type = res.get_header_value("Content-Type");
  8981. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8982. });
  8983. // Set up post-compression logger
  8984. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8985. post_compression_body = res.body;
  8986. post_compression_content_type = res.get_header_value("Content-Type");
  8987. post_compression_content_encoding =
  8988. res.get_header_value("Content-Encoding");
  8989. });
  8990. // Test with gzip compression
  8991. Headers headers;
  8992. headers.emplace("Accept-Encoding", "gzip");
  8993. auto res = cli_.Get("/compress", headers);
  8994. // Verify response was compressed
  8995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8996. EXPECT_EQ(StatusCode::OK_200, res->status);
  8997. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8998. // Verify pre-compression logger captured uncompressed content
  8999. EXPECT_EQ(test_content, pre_compression_body);
  9000. EXPECT_EQ("text/plain", pre_compression_content_type);
  9001. EXPECT_TRUE(pre_compression_content_encoding
  9002. .empty()); // No encoding header before compression
  9003. // Verify post-compression logger captured compressed content
  9004. EXPECT_NE(test_content,
  9005. post_compression_body); // Should be different after compression
  9006. EXPECT_EQ("text/plain", post_compression_content_type);
  9007. EXPECT_EQ("gzip", post_compression_content_encoding);
  9008. // Verify compressed content is smaller
  9009. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9010. }
  9011. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9012. const std::string test_content =
  9013. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9014. "3456789012345678901234567890";
  9015. std::string pre_compression_body;
  9016. std::string post_compression_body;
  9017. svr_.set_pre_compression_logger(
  9018. [&](const Request & /*req*/, const Response &res) {
  9019. pre_compression_body = res.body;
  9020. });
  9021. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9022. post_compression_body = res.body;
  9023. });
  9024. Headers headers;
  9025. headers.emplace("Accept-Encoding", "br");
  9026. auto res = cli_.Get("/compress", headers);
  9027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9028. EXPECT_EQ(StatusCode::OK_200, res->status);
  9029. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9030. // Verify pre-compression content is uncompressed
  9031. EXPECT_EQ(test_content, pre_compression_body);
  9032. // Verify post-compression content is compressed
  9033. EXPECT_NE(test_content, post_compression_body);
  9034. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9035. }
  9036. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9037. const std::string test_content =
  9038. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9039. "3456789012345678901234567890";
  9040. std::string pre_compression_body;
  9041. std::string post_compression_body;
  9042. svr_.set_pre_compression_logger(
  9043. [&](const Request & /*req*/, const Response &res) {
  9044. pre_compression_body = res.body;
  9045. });
  9046. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9047. post_compression_body = res.body;
  9048. });
  9049. // Request without compression (use /nocompress endpoint)
  9050. Headers headers;
  9051. auto res = cli_.Get("/nocompress", headers);
  9052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9053. EXPECT_EQ(StatusCode::OK_200, res->status);
  9054. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9055. // Pre-compression logger should not be called when no compression is applied
  9056. EXPECT_TRUE(
  9057. pre_compression_body.empty()); // Pre-compression logger not called
  9058. EXPECT_EQ(
  9059. test_content,
  9060. post_compression_body); // Post-compression logger captures final content
  9061. }
  9062. TEST_F(ServerTest, LoggerSeesContentLength) {
  9063. size_t logged_content_length = 0;
  9064. std::string logged_content_length_header;
  9065. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9066. logged_content_length = res.content_length_;
  9067. logged_content_length_header = res.get_header_value("Content-Length");
  9068. });
  9069. auto res = cli_.Get("/nocompress");
  9070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9071. EXPECT_EQ(StatusCode::OK_200, res->status);
  9072. EXPECT_EQ(res->body.size(), logged_content_length);
  9073. EXPECT_EQ(std::to_string(logged_content_length),
  9074. logged_content_length_header);
  9075. }
  9076. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9077. const std::string test_content =
  9078. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9079. "3456789012345678901234567890";
  9080. std::string pre_compression_body;
  9081. bool pre_logger_called = false;
  9082. // Set only pre-compression logger
  9083. svr_.set_pre_compression_logger(
  9084. [&](const Request & /*req*/, const Response &res) {
  9085. pre_compression_body = res.body;
  9086. pre_logger_called = true;
  9087. });
  9088. Headers headers;
  9089. headers.emplace("Accept-Encoding", "gzip");
  9090. auto res = cli_.Get("/compress", headers);
  9091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9092. EXPECT_EQ(StatusCode::OK_200, res->status);
  9093. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9094. // Verify pre-compression logger was called
  9095. EXPECT_TRUE(pre_logger_called);
  9096. EXPECT_EQ(test_content, pre_compression_body);
  9097. }
  9098. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9099. {
  9100. // Test with Expect: 100-continue header - success case
  9101. // Server returns 100 Continue, client sends body, server returns 200 OK
  9102. Request req;
  9103. req.method = "POST";
  9104. req.path = "/post-large";
  9105. req.set_header("Expect", "100-continue");
  9106. req.body = LARGE_DATA;
  9107. Response res;
  9108. auto error = Error::Success;
  9109. cli_.set_keep_alive(true);
  9110. auto ret = cli_.send(req, res, error);
  9111. EXPECT_TRUE(ret);
  9112. EXPECT_EQ(StatusCode::OK_200, res.status);
  9113. EXPECT_EQ(LARGE_DATA, res.body);
  9114. }
  9115. {
  9116. // Test with Expect: 100-continue header - error case
  9117. // Client should not send the body when server returns an error
  9118. Request req;
  9119. req.method = "POST";
  9120. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9121. req.set_header("Expect", "100-continue");
  9122. req.body = LARGE_DATA;
  9123. Response res;
  9124. auto error = Error::Success;
  9125. auto start = std::chrono::high_resolution_clock::now();
  9126. cli_.set_keep_alive(true);
  9127. auto ret = cli_.send(req, res, error);
  9128. auto end = std::chrono::high_resolution_clock::now();
  9129. auto elapsed =
  9130. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9131. .count();
  9132. // With Expect: 100-continue, request completes successfully but with error
  9133. EXPECT_TRUE(ret);
  9134. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9135. EXPECT_EQ("close", res.get_header_value("Connection"));
  9136. EXPECT_FALSE(cli_.is_socket_open());
  9137. EXPECT_LE(elapsed, 2000);
  9138. }
  9139. {
  9140. // Send an extra GET request to ensure error recovery without hanging
  9141. Request req;
  9142. req.method = "GET";
  9143. req.path = "/hi";
  9144. auto start = std::chrono::high_resolution_clock::now();
  9145. auto res = cli_.send(req);
  9146. auto end = std::chrono::high_resolution_clock::now();
  9147. auto elapsed =
  9148. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9149. .count();
  9150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. EXPECT_EQ("Hello World!", res->body);
  9153. EXPECT_LE(elapsed, 500);
  9154. }
  9155. }
  9156. TEST(ZstdDecompressor, ChunkedDecompression) {
  9157. std::string data;
  9158. for (size_t i = 0; i < 32 * 1024; ++i) {
  9159. data.push_back(static_cast<char>('a' + i % 26));
  9160. }
  9161. std::string compressed_data;
  9162. {
  9163. httplib::detail::zstd_compressor compressor;
  9164. bool result = compressor.compress(
  9165. data.data(), data.size(),
  9166. /*last=*/true,
  9167. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9168. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9169. compressed_data_size);
  9170. return true;
  9171. });
  9172. ASSERT_TRUE(result);
  9173. }
  9174. std::string decompressed_data;
  9175. {
  9176. httplib::detail::zstd_decompressor decompressor;
  9177. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9178. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9179. size_t chunk_size = 130;
  9180. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9181. chunk_begin += chunk_size) {
  9182. size_t current_chunk_size =
  9183. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9184. bool result = decompressor.decompress(
  9185. compressed_data.data() + chunk_begin, current_chunk_size,
  9186. [&](const char *decompressed_data_chunk,
  9187. size_t decompressed_data_chunk_size) {
  9188. decompressed_data.insert(decompressed_data.size(),
  9189. decompressed_data_chunk,
  9190. decompressed_data_chunk_size);
  9191. return true;
  9192. });
  9193. ASSERT_TRUE(result);
  9194. }
  9195. }
  9196. ASSERT_EQ(data, decompressed_data);
  9197. }
  9198. TEST(ZstdDecompressor, Decompress) {
  9199. std::string original_text = "Compressed with ZSTD";
  9200. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9201. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9202. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9203. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9204. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9205. std::string decompressed_data;
  9206. {
  9207. httplib::detail::zstd_decompressor decompressor;
  9208. bool result = decompressor.decompress(
  9209. compressed_data.data(), compressed_data.size(),
  9210. [&](const char *decompressed_data_chunk,
  9211. size_t decompressed_data_chunk_size) {
  9212. decompressed_data.insert(decompressed_data.size(),
  9213. decompressed_data_chunk,
  9214. decompressed_data_chunk_size);
  9215. return true;
  9216. });
  9217. ASSERT_TRUE(result);
  9218. }
  9219. ASSERT_EQ(original_text, decompressed_data);
  9220. }
  9221. #endif
  9222. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9223. // separate chunks so that the server sees each part in its own read(). Used to
  9224. // place a read boundary at a specific offset of a request body.
  9225. static bool send_request_in_parts(time_t read_timeout_sec,
  9226. const std::vector<std::string> &parts,
  9227. std::string *resp = nullptr,
  9228. int port = PORT) {
  9229. auto error = Error::Success;
  9230. auto client_sock = detail::create_client_socket(
  9231. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9232. /*connection_timeout_sec=*/5, 0,
  9233. /*read_timeout_sec=*/5, 0,
  9234. /*write_timeout_sec=*/5, 0, std::string(), error);
  9235. if (client_sock == INVALID_SOCKET) { return false; }
  9236. auto ret = detail::process_client_socket(
  9237. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9238. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9239. for (size_t i = 0; i < parts.size(); i++) {
  9240. const auto &part = parts[i];
  9241. if (part.size() !=
  9242. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9243. return false;
  9244. }
  9245. if (i + 1 < parts.size()) {
  9246. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9247. }
  9248. }
  9249. char buf[512];
  9250. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9251. while (line_reader.getline()) {
  9252. if (resp) { *resp += line_reader.ptr(); }
  9253. }
  9254. return true;
  9255. });
  9256. detail::close_socket(client_sock);
  9257. return ret;
  9258. }
  9259. // Sends a raw request to a server listening at HOST:PORT.
  9260. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9261. std::string *resp = nullptr, int port = PORT) {
  9262. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9263. }
  9264. #ifdef CPPHTTPLIB_SSL_ENABLED
  9265. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9267. ASSERT_TRUE(svr.is_valid());
  9268. svr.set_read_timeout(1, 0);
  9269. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9270. auto se = detail::scope_exit([&] {
  9271. svr.stop();
  9272. t.join();
  9273. ASSERT_FALSE(svr.is_running());
  9274. });
  9275. svr.wait_until_ready();
  9276. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9277. // keeps each wait well within the read timeout. The server gives up a
  9278. // second in, so the bytes sent after that fail.
  9279. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9280. parts.resize(26, std::string(1, '\0'));
  9281. EXPECT_FALSE(send_request_in_parts(5, parts));
  9282. }
  9283. #endif
  9284. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9285. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9286. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9287. const std::vector<std::string> &parts,
  9288. std::string *resp = nullptr,
  9289. int port = PORT) {
  9290. auto error = Error::Success;
  9291. auto sock = detail::create_client_socket(
  9292. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9293. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9294. /*write_timeout_sec=*/5, 0, std::string(), error);
  9295. if (sock == INVALID_SOCKET) { return false; }
  9296. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9297. auto ctx = SSL_CTX_new(TLS_client_method());
  9298. auto ssl = SSL_new(ctx);
  9299. auto ssl_se = detail::scope_exit([&] {
  9300. SSL_free(ssl);
  9301. SSL_CTX_free(ctx);
  9302. });
  9303. SSL_set_fd(ssl, static_cast<int>(sock));
  9304. if (SSL_connect(ssl) != 1) { return false; }
  9305. for (size_t i = 0; i < parts.size(); i++) {
  9306. const auto &part = parts[i];
  9307. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9308. static_cast<int>(part.size())) {
  9309. return false;
  9310. }
  9311. if (i + 1 < parts.size()) {
  9312. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9313. }
  9314. }
  9315. char buf[512];
  9316. int n;
  9317. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9318. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9319. }
  9320. return true;
  9321. }
  9322. #endif
  9323. // The request line, then a header value a byte at a time.
  9324. static std::vector<std::string> slow_request_head_parts() {
  9325. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9326. parts.resize(26, "a");
  9327. parts.emplace_back("\r\n\r\n");
  9328. return parts;
  9329. }
  9330. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9331. // within the one-second read timeout. The server gives up a second in, before
  9332. // the head is complete.
  9333. static void
  9334. expect_slow_request_head_dropped(Server &svr,
  9335. const std::function<std::string()> &send) {
  9336. std::atomic<bool> handled(false);
  9337. svr.Get("/", [&](const Request &, Response &res) {
  9338. handled = true;
  9339. res.set_content("ok", "text/plain");
  9340. });
  9341. svr.set_read_timeout(1, 0);
  9342. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9343. auto se = detail::scope_exit([&] {
  9344. svr.stop();
  9345. t.join();
  9346. ASSERT_FALSE(svr.is_running());
  9347. });
  9348. svr.wait_until_ready();
  9349. auto resp = send();
  9350. EXPECT_FALSE(handled);
  9351. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9352. }
  9353. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9354. Server svr;
  9355. expect_slow_request_head_dropped(svr, [] {
  9356. std::string resp;
  9357. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9358. return resp;
  9359. });
  9360. }
  9361. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9362. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9364. ASSERT_TRUE(svr.is_valid());
  9365. expect_slow_request_head_dropped(svr, [] {
  9366. std::string resp;
  9367. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9368. return resp;
  9369. });
  9370. }
  9371. #endif
  9372. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9373. Server svr;
  9374. std::string header_value;
  9375. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9376. header_value = req.get_header_value("foo");
  9377. res.set_content("ok", "text/plain");
  9378. });
  9379. thread t = thread([&] { svr.listen(HOST, PORT); });
  9380. auto se = detail::scope_exit([&] {
  9381. svr.stop();
  9382. t.join();
  9383. ASSERT_FALSE(svr.is_running());
  9384. });
  9385. svr.wait_until_ready();
  9386. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9387. // like characters are not treated the same - use vertical tab and escape.
  9388. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9389. "foo: \t \v bar \x1B\t \r\n"
  9390. "Connection: close\r\n"
  9391. "\r\n";
  9392. std::string res;
  9393. ASSERT_TRUE(send_request(5, req, &res));
  9394. EXPECT_EQ(header_value, "");
  9395. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9396. }
  9397. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9398. Server svr;
  9399. std::string received;
  9400. svr.Get("/order", [&](const Request &req, Response &res) {
  9401. received = entries_to_string(req.headers);
  9402. res.set_content("ok", "text/plain");
  9403. });
  9404. auto port = svr.bind_to_any_port(HOST);
  9405. thread t = thread([&] { svr.listen_after_bind(); });
  9406. auto se = detail::scope_exit([&] {
  9407. svr.stop();
  9408. t.join();
  9409. ASSERT_FALSE(svr.is_running());
  9410. });
  9411. svr.wait_until_ready();
  9412. const std::string req = "GET /order HTTP/1.1\r\n"
  9413. "Host: localhost\r\n"
  9414. "X-First: 1\r\n"
  9415. "X-Dup: a\r\n"
  9416. "X-Second: 2\r\n"
  9417. "X-Dup: b\r\n"
  9418. "Connection: close\r\n"
  9419. "\r\n";
  9420. std::string res;
  9421. ASSERT_TRUE(send_request(5, req, &res, port));
  9422. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9423. EXPECT_EQ(
  9424. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9425. received);
  9426. }
  9427. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9428. Server svr;
  9429. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9430. res.set_header("Set-Cookie", "first=1");
  9431. res.set_header("X-Between", "y");
  9432. res.set_header("Set-Cookie", "second=2");
  9433. res.set_content("ok", "text/plain");
  9434. });
  9435. auto port = svr.bind_to_any_port(HOST);
  9436. thread t = thread([&] { svr.listen_after_bind(); });
  9437. auto se = detail::scope_exit([&] {
  9438. svr.stop();
  9439. t.join();
  9440. ASSERT_FALSE(svr.is_running());
  9441. });
  9442. svr.wait_until_ready();
  9443. Client cli(HOST, port);
  9444. auto res = cli.Get("/cookies");
  9445. ASSERT_TRUE(res);
  9446. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9447. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9448. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9449. }
  9450. // A stream may send a byte at a time with a small extension on each chunk,
  9451. // however long it runs
  9452. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9453. Server svr;
  9454. svr.Post("/count", [](const Request &req, Response &res) {
  9455. res.set_content(std::to_string(req.body.size()), "text/plain");
  9456. });
  9457. auto port = svr.bind_to_any_port(HOST);
  9458. ASSERT_LT(0, port);
  9459. thread t = thread([&] { svr.listen_after_bind(); });
  9460. auto se = detail::scope_exit([&] {
  9461. svr.stop();
  9462. t.join();
  9463. ASSERT_FALSE(svr.is_running());
  9464. });
  9465. svr.wait_until_ready();
  9466. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9467. "\r\nTransfer-Encoding: chunked\r\n"
  9468. "Connection: close\r\n\r\n";
  9469. for (auto i = 0; i < 4096; i++) {
  9470. req += "1;a=b\r\nx\r\n";
  9471. }
  9472. req += "0\r\n\r\n";
  9473. std::string res;
  9474. ASSERT_TRUE(send_request(5, req, &res, port));
  9475. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9476. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9477. }
  9478. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9479. Server svr;
  9480. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9481. auto i = new int(0);
  9482. res.set_header("Trailer", "X-Safe, X-Reflected");
  9483. res.set_chunked_content_provider(
  9484. "text/plain",
  9485. [i](size_t /*offset*/, DataSink &sink) {
  9486. if (*i == 0) {
  9487. sink.os << "body";
  9488. } else {
  9489. Headers trailer;
  9490. // A valid trailer that must survive.
  9491. trailer.emplace("X-Safe", "safe");
  9492. // Attacker-controlled value carrying CR/LF (response splitting).
  9493. trailer.emplace("X-Reflected",
  9494. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9495. // Attacker-controlled name carrying CR/LF.
  9496. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9497. sink.done_with_trailer(trailer);
  9498. }
  9499. (*i)++;
  9500. return true;
  9501. },
  9502. [i](bool /*success*/) { delete i; });
  9503. });
  9504. thread t = thread([&] { svr.listen(HOST, PORT); });
  9505. auto se = detail::scope_exit([&] {
  9506. svr.stop();
  9507. t.join();
  9508. ASSERT_FALSE(svr.is_running());
  9509. });
  9510. svr.wait_until_ready();
  9511. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9512. "Host: " + HOST +
  9513. "\r\n"
  9514. "Connection: close\r\n"
  9515. "\r\n";
  9516. std::string res;
  9517. ASSERT_TRUE(send_request(5, req, &res));
  9518. // The injected fields must not appear anywhere in the raw response.
  9519. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9520. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9521. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9522. // Invalid trailers are dropped entirely, matching set_header().
  9523. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9524. // The valid trailer still passes through.
  9525. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9526. }
  9527. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9528. // A custom header writer gets only the fields the default one writes
  9529. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9530. std::string s;
  9531. for (const auto &h : hdrs) {
  9532. s += h.first + ": " + h.second + "\r\n";
  9533. }
  9534. s += "\r\n";
  9535. return strm.write(s.data(), s.size());
  9536. };
  9537. for (auto custom_writer : {false, true}) {
  9538. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9539. Server svr;
  9540. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9541. svr.set_post_routing_handler([](const Request &, Response &res) {
  9542. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9543. });
  9544. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9545. // res.headers is a public field an application can populate directly,
  9546. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9547. // A valid header that must survive.
  9548. res.headers.emplace("X-Safe", "safe");
  9549. // Attacker-controlled value carrying CR/LF (response splitting).
  9550. res.headers.emplace("X-Reflected",
  9551. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9552. // Attacker-controlled name carrying CR/LF.
  9553. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9554. res.set_content("body", "text/plain");
  9555. });
  9556. thread t = thread([&] { svr.listen(HOST, PORT); });
  9557. auto se = detail::scope_exit([&] {
  9558. svr.stop();
  9559. t.join();
  9560. ASSERT_FALSE(svr.is_running());
  9561. });
  9562. svr.wait_until_ready();
  9563. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9564. "Host: " + HOST +
  9565. "\r\n"
  9566. "Connection: close\r\n"
  9567. "\r\n";
  9568. std::string res;
  9569. ASSERT_TRUE(send_request(5, req, &res));
  9570. // The injected fields must not appear anywhere in the raw response.
  9571. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9572. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9573. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9574. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9575. // Invalid headers are dropped entirely, matching set_header().
  9576. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9577. // The valid header still passes through.
  9578. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9579. }
  9580. }
  9581. // Forward declaration: in split builds split.py strips `inline` and moves the
  9582. // definition into httplib.cc, so detail::write_request_line is not visible from
  9583. // the public httplib.h. Re-declaring it here lets the tests link against the
  9584. // symbol in both header-only and split builds.
  9585. namespace httplib {
  9586. namespace detail {
  9587. ssize_t write_request_line(Stream &strm, const std::string &method,
  9588. const std::string &path);
  9589. } // namespace detail
  9590. } // namespace httplib
  9591. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9592. // A well-formed target is written verbatim.
  9593. {
  9594. detail::BufferStream strm;
  9595. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9596. EXPECT_GT(n, 0);
  9597. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9598. }
  9599. // A target carrying CR/LF, SP or other control octets must be rejected
  9600. // before anything reaches the wire, otherwise it splits the request line and
  9601. // injects a header or a whole request.
  9602. const std::string evil_targets[] = {
  9603. "/a\r\nInjected: pwned",
  9604. "/a\rInjected",
  9605. "/a\nInjected",
  9606. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9607. "/a b",
  9608. "/a\tb",
  9609. "/a\x7f",
  9610. };
  9611. for (const auto &evil : evil_targets) {
  9612. detail::BufferStream strm;
  9613. auto n = detail::write_request_line(strm, "GET", evil);
  9614. EXPECT_LT(n, 0);
  9615. EXPECT_TRUE(strm.get_buffer().empty());
  9616. }
  9617. }
  9618. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9619. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9620. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9621. // target reaches write_request. The client must fail cleanly with
  9622. // Error::Write instead of putting a request-line-less, header-injecting
  9623. // request on the wire.
  9624. Server svr;
  9625. svr.Get("/a", [](const Request &, Response &res) {
  9626. res.set_content("ok", "text/plain");
  9627. });
  9628. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. cli.set_path_encode(false);
  9638. // The request is rejected before anything is written, so the connection
  9639. // stays silent and the subsequent response read would otherwise block for
  9640. // the full default read timeout. Shorten it -- the assertion is on the
  9641. // error, not the timeout.
  9642. cli.set_read_timeout(1, 0);
  9643. auto res = cli.Get("/a\r\nInjected: pwned");
  9644. EXPECT_FALSE(res);
  9645. EXPECT_EQ(Error::Write, res.error());
  9646. }
  9647. }
  9648. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9649. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9650. // including extension methods.
  9651. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9652. for (const auto &method : good_methods) {
  9653. detail::BufferStream strm;
  9654. auto n = detail::write_request_line(strm, method, "/");
  9655. EXPECT_GT(n, 0);
  9656. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9657. }
  9658. // A method carrying CR/LF would split the request line and smuggle a whole
  9659. // request ahead of the real one. A space or an empty method corrupts the
  9660. // request line. All must be rejected before anything reaches the wire.
  9661. const std::string evil_methods[] = {
  9662. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9663. "GET\r\nInjected: pwned",
  9664. "GET\r",
  9665. "GET\n",
  9666. "GE T",
  9667. "",
  9668. };
  9669. for (const auto &evil : evil_methods) {
  9670. detail::BufferStream strm;
  9671. auto n = detail::write_request_line(strm, evil, "/");
  9672. EXPECT_LT(n, 0);
  9673. EXPECT_TRUE(strm.get_buffer().empty());
  9674. }
  9675. }
  9676. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9677. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9678. // through Client::send must fail with Error::Write and no request, neither
  9679. // the smuggled one nor the real one, may reach the server.
  9680. Server svr;
  9681. std::atomic<int> request_count(0);
  9682. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9683. request_count++;
  9684. res.status = StatusCode::OK_200;
  9685. return Server::HandlerResponse::Handled;
  9686. });
  9687. auto port = svr.bind_to_any_port(HOST);
  9688. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9689. auto se = detail::scope_exit([&] {
  9690. svr.stop();
  9691. thread.join();
  9692. ASSERT_FALSE(svr.is_running());
  9693. });
  9694. svr.wait_until_ready();
  9695. {
  9696. Client cli(HOST, port);
  9697. const std::string evil_methods[] = {
  9698. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9699. "GE T",
  9700. "",
  9701. };
  9702. for (const auto &evil : evil_methods) {
  9703. Request req;
  9704. req.method = evil;
  9705. req.path = "/";
  9706. auto res = cli.send(req);
  9707. EXPECT_FALSE(res);
  9708. EXPECT_EQ(Error::Write, res.error());
  9709. }
  9710. auto handle =
  9711. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9712. EXPECT_FALSE(handle.is_valid());
  9713. EXPECT_EQ(Error::Write, handle.error);
  9714. // A valid request on the same client still goes through.
  9715. auto res = cli.Get("/");
  9716. ASSERT_TRUE(res);
  9717. EXPECT_EQ(StatusCode::OK_200, res->status);
  9718. }
  9719. EXPECT_EQ(1, request_count.load());
  9720. }
  9721. // Sends a raw request and verifies that there isn't a crash or exception.
  9722. static void test_raw_request(const std::string &req,
  9723. std::string *out = nullptr) {
  9724. Server svr;
  9725. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9726. res.set_content("ok", "text/plain");
  9727. });
  9728. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9729. res.set_content("ok", "text/plain");
  9730. });
  9731. svr.Get("/header_field_value_check",
  9732. [&](const Request & /*req*/, Response &res) {
  9733. res.set_content("ok", "text/plain");
  9734. });
  9735. svr.CustomRoute("PROPFIND", "/dav",
  9736. [&](const Request & /*req*/, Response &res) {
  9737. res.status = StatusCode::MultiStatus_207;
  9738. });
  9739. // Server read timeout must be longer than the client read timeout for the
  9740. // bug to reproduce, probably to force the server to process a request
  9741. // without a trailing blank line.
  9742. const time_t client_read_timeout_sec = 1;
  9743. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9744. bool listen_thread_ok = false;
  9745. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9746. auto se = detail::scope_exit([&] {
  9747. svr.stop();
  9748. t.join();
  9749. ASSERT_FALSE(svr.is_running());
  9750. EXPECT_TRUE(listen_thread_ok);
  9751. });
  9752. svr.wait_until_ready();
  9753. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9754. }
  9755. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9756. // A certain header line causes an exception if the header property is parsed
  9757. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9758. test_raw_request(
  9759. "GET /hi HTTP/1.1\r\n"
  9760. " : "
  9761. " "
  9762. " ");
  9763. }
  9764. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9765. // A certain header line causes an exception if the header property *name* is
  9766. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9767. // greedy matcher and requires backtracking when there are a lot of ":"
  9768. // characters.
  9769. // This occurs with libc++ but not libstdc++.
  9770. test_raw_request(
  9771. "GET /hi HTTP/1.1\r\n"
  9772. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9773. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9774. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9775. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9776. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9777. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9778. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9779. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9780. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9781. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9782. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9783. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9784. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9785. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9786. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9787. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9788. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9789. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9790. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9791. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9792. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9793. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9794. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9795. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9796. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9797. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9798. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9799. "&&&%%%");
  9800. }
  9801. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9802. // Make sure this doesn't crash the server.
  9803. // In a previous version of the header line regex, the "\r" rendered the line
  9804. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9805. // a new position where the leading white space ended and the field value
  9806. // began.
  9807. // The crash occurs with libc++ but not libstdc++.
  9808. test_raw_request("GET /hi HTTP/1.1\r\n"
  9809. "a:" +
  9810. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9811. "\r\n"
  9812. "\r\n");
  9813. }
  9814. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9815. const char *rejected[] = {
  9816. // RFC 9112 §3: one SP between the parts, and nothing else
  9817. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9818. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9819. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9820. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9821. // A request-target has no fragment
  9822. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9823. // An HTTP/1.1 request needs a Host
  9824. "GET /hi HTTP/1.1\r\n\r\n",
  9825. };
  9826. for (auto request : rejected) {
  9827. std::string out;
  9828. test_raw_request(request, &out);
  9829. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9830. }
  9831. std::string out;
  9832. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9833. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9834. }
  9835. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9836. // RFC 9112 §6.1
  9837. const char *requests[] = {
  9838. "PUT /put_hi HTTP/1.1\r\n"
  9839. "Host: localhost\r\n"
  9840. "Content-Length: 0\r\n"
  9841. "Transfer-Encoding: chunked\r\n"
  9842. "\r\n"
  9843. "0\r\n\r\n",
  9844. "PUT /put_hi HTTP/1.0\r\n"
  9845. "Connection: keep-alive\r\n"
  9846. "Transfer-Encoding: chunked\r\n"
  9847. "\r\n"
  9848. "0\r\n\r\n",
  9849. };
  9850. for (auto request : requests) {
  9851. std::string out;
  9852. test_raw_request(request, &out);
  9853. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9854. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9855. }
  9856. }
  9857. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9858. std::string out;
  9859. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9860. "Content-Type: text/plain\r\n"
  9861. "Transfer-Encoding: chunked\r\n"
  9862. "\r\n"
  9863. "nothex\r\n",
  9864. &out);
  9865. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9866. }
  9867. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9868. std::string out;
  9869. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9870. "Content-Type: text/plain\r\n"
  9871. "Transfer-Encoding: chunked\r\n"
  9872. "\r\n"
  9873. "3\r\n"
  9874. "xyz\r\n"
  9875. "NaN\r\n",
  9876. &out);
  9877. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9878. }
  9879. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9880. std::string out;
  9881. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9882. "Content-Type: text/plain\r\n"
  9883. "Transfer-Encoding: chunked\r\n"
  9884. "\r\n"
  9885. // Length is too large for 64 bits.
  9886. "1ffffffffffffffff\r\n"
  9887. "xyz\r\n",
  9888. &out);
  9889. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9890. }
  9891. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9892. test_raw_request("GET /hi HTTP/1.1\r\n"
  9893. "Content-Type: text/plain\r\n\r");
  9894. }
  9895. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9896. std::string out;
  9897. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9898. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9899. }
  9900. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9901. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9902. std::string out;
  9903. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9904. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9905. }
  9906. }
  9907. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9908. std::string out;
  9909. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9910. "Host: localhost\r\n"
  9911. "Connection: close\r\n\r\n",
  9912. &out);
  9913. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9914. }
  9915. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9916. Server svr;
  9917. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9918. EXPECT_TRUE(!req.remote_addr.empty());
  9919. });
  9920. thread t = thread([&] { svr.listen(HOST, PORT); });
  9921. auto se = detail::scope_exit([&] {
  9922. svr.stop();
  9923. t.join();
  9924. ASSERT_FALSE(svr.is_running());
  9925. });
  9926. svr.wait_until_ready();
  9927. // Send an invalid request line to trigger Bad Request
  9928. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9929. std::string out;
  9930. ASSERT_TRUE(send_request(5, bad_req, &out));
  9931. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9932. }
  9933. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9934. // answered right away rather than blocking on a read that waits for EOF.
  9935. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9936. std::string out;
  9937. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9938. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9939. }
  9940. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9941. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9942. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9943. for (const auto *method : methods) {
  9944. Server svr;
  9945. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9946. EXPECT_FALSE(svr.is_valid()) << method;
  9947. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9948. }
  9949. }
  9950. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9951. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9952. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9953. for (const auto *method : methods) {
  9954. Server svr;
  9955. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9956. EXPECT_FALSE(svr.is_valid()) << method;
  9957. }
  9958. }
  9959. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9960. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9961. "COPY", "MOVE", "LOCK",
  9962. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9963. Server svr;
  9964. for (const auto *method : methods) {
  9965. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9966. }
  9967. EXPECT_TRUE(svr.is_valid());
  9968. }
  9969. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9970. Server svr;
  9971. svr.CustomRoute("POST", "/x",
  9972. [](const Request &, Response &, const ContentReader &) {});
  9973. EXPECT_FALSE(svr.is_valid());
  9974. }
  9975. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9976. Server svr;
  9977. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9978. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9979. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9980. EXPECT_FALSE(svr.is_valid());
  9981. }
  9982. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9983. Server svr;
  9984. auto captured = Error::Success;
  9985. svr.set_error_logger(
  9986. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9987. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9988. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9989. }
  9990. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9991. std::string out;
  9992. std::string request(
  9993. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9994. test_raw_request(request, &out);
  9995. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9996. }
  9997. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9998. std::string out;
  9999. std::string request(
  10000. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10001. test_raw_request(request, &out);
  10002. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10003. }
  10004. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10005. std::string out;
  10006. std::string request(
  10007. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10008. test_raw_request(request, &out);
  10009. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10010. }
  10011. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10012. std::string out;
  10013. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10014. "Host: localhost\r\n"
  10015. "Test: \r\n\r\n",
  10016. &out);
  10017. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10018. }
  10019. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10020. Server svr;
  10021. std::string x_custom;
  10022. std::string cookie;
  10023. std::string xff;
  10024. std::string x_unicode;
  10025. std::string x_iis;
  10026. svr.Get("/check", [&](const Request &req, Response &res) {
  10027. x_custom = req.get_header_value("X-Custom");
  10028. cookie = req.get_header_value("Cookie");
  10029. xff = req.get_header_value("X-Forwarded-For");
  10030. x_unicode = req.get_header_value("X-Unicode");
  10031. x_iis = req.get_header_value("X-IIS");
  10032. res.set_content("ok", "text/plain");
  10033. });
  10034. thread t = thread([&] { svr.listen(HOST, PORT); });
  10035. auto se = detail::scope_exit([&] {
  10036. svr.stop();
  10037. t.join();
  10038. ASSERT_FALSE(svr.is_running());
  10039. });
  10040. svr.wait_until_ready();
  10041. const std::string req = "GET /check HTTP/1.1\r\n"
  10042. "Host: localhost\r\n"
  10043. "X-Custom: a%0D%0AInjected: b\r\n"
  10044. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10045. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10046. "X-Unicode: %E3%81%82\r\n"
  10047. "X-IIS: %u00E9\r\n"
  10048. "Connection: close\r\n"
  10049. "\r\n";
  10050. std::string res;
  10051. ASSERT_TRUE(send_request(5, req, &res));
  10052. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10053. // Every value must be returned verbatim (wire form), with no decoding.
  10054. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10055. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10056. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10057. EXPECT_EQ("%E3%81%82", x_unicode);
  10058. EXPECT_EQ("%u00E9", x_iis);
  10059. }
  10060. // Applications that previously relied on automatic percent-decoding can
  10061. // reproduce the old behavior by explicitly calling decode_path_component()
  10062. // or, for RFC 3986 conformance, decode_uri_component().
  10063. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10064. Server svr;
  10065. std::string decoded;
  10066. svr.Get("/check", [&](const Request &req, Response &res) {
  10067. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10068. res.set_content("ok", "text/plain");
  10069. });
  10070. thread t = thread([&] { svr.listen(HOST, PORT); });
  10071. auto se = detail::scope_exit([&] {
  10072. svr.stop();
  10073. t.join();
  10074. ASSERT_FALSE(svr.is_running());
  10075. });
  10076. svr.wait_until_ready();
  10077. const std::string req = "GET /check HTTP/1.1\r\n"
  10078. "Host: localhost\r\n"
  10079. "X-Custom: hello%20world\r\n"
  10080. "Connection: close\r\n"
  10081. "\r\n";
  10082. std::string res;
  10083. ASSERT_TRUE(send_request(5, req, &res));
  10084. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10085. EXPECT_EQ("hello world", decoded);
  10086. }
  10087. // Regression test for #2033. Browsers send Referer values that include
  10088. // percent-encoded characters such as %0A inside the URL. Decoding the
  10089. // header value would either trip the post-decode CR/LF/NUL guard (the
  10090. // original bug, returning 400) or, after that guard was relaxed, silently
  10091. // store a literal LF — both unacceptable. The wire form must round-trip.
  10092. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10093. Server svr;
  10094. std::string referer;
  10095. svr.Get("/check", [&](const Request &req, Response &res) {
  10096. referer = req.get_header_value("Referer");
  10097. res.set_content("ok", "text/plain");
  10098. });
  10099. thread t = thread([&] { svr.listen(HOST, PORT); });
  10100. auto se = detail::scope_exit([&] {
  10101. svr.stop();
  10102. t.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. });
  10105. svr.wait_until_ready();
  10106. const std::string req = "GET /check HTTP/1.1\r\n"
  10107. "Host: localhost\r\n"
  10108. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10109. "Connection: close\r\n"
  10110. "\r\n";
  10111. std::string res;
  10112. ASSERT_TRUE(send_request(5, req, &res));
  10113. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10114. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10115. }
  10116. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10117. Server svr;
  10118. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10119. res.set_header("Cache-Control", "no-cache");
  10120. res.set_chunked_content_provider(
  10121. "text/event-stream", [](size_t offset, DataSink &sink) {
  10122. std::string s = "data:";
  10123. s += std::to_string(offset);
  10124. s += "\n\n";
  10125. auto ret = sink.write(s.data(), s.size());
  10126. EXPECT_TRUE(ret);
  10127. std::this_thread::sleep_for(std::chrono::seconds(1));
  10128. return true;
  10129. });
  10130. });
  10131. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10132. svr.wait_until_ready();
  10133. Client client(HOST, PORT);
  10134. const Headers headers = {{"Accept", "text/event-stream"}};
  10135. auto get_thread = std::thread([&client, &headers]() {
  10136. auto res = client.Get(
  10137. "/events", headers,
  10138. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10139. });
  10140. auto se = detail::scope_exit([&] {
  10141. svr.stop();
  10142. get_thread.join();
  10143. listen_thread.join();
  10144. ASSERT_FALSE(svr.is_running());
  10145. });
  10146. // Give GET time to get a few messages.
  10147. std::this_thread::sleep_for(std::chrono::seconds(2));
  10148. }
  10149. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10150. httplib::Server svr;
  10151. svr.Post("/hi",
  10152. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10153. res.status = StatusCode::OK_200;
  10154. });
  10155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10156. svr.wait_until_ready();
  10157. Client cli(HOST, PORT);
  10158. auto res = cli.Post("/hi", "data", "text/plain");
  10159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10160. EXPECT_EQ(StatusCode::OK_200, res->status);
  10161. svr.stop();
  10162. thread.join();
  10163. ASSERT_FALSE(svr.is_running());
  10164. res = cli.Post("/hi", "data", "text/plain");
  10165. ASSERT_FALSE(res);
  10166. }
  10167. TEST(ServerStopTest, ListenFailure) {
  10168. Server svr;
  10169. auto t = thread([&]() {
  10170. auto ret = svr.listen("????", PORT);
  10171. EXPECT_FALSE(ret);
  10172. });
  10173. svr.wait_until_ready();
  10174. svr.stop();
  10175. t.join();
  10176. }
  10177. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10178. TEST(ServerStopTest, Decommision) {
  10179. Server svr;
  10180. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10181. for (int i = 0; i < 4; i++) {
  10182. auto is_even = !(i % 2);
  10183. std::thread t{[&] {
  10184. try {
  10185. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10186. if (is_even) {
  10187. throw std::runtime_error("Some thing that happens to go wrong.");
  10188. }
  10189. svr.listen(HOST, PORT);
  10190. } catch (...) { svr.decommission(); }
  10191. }};
  10192. svr.wait_until_ready();
  10193. // Server is up
  10194. {
  10195. Client cli(HOST, PORT);
  10196. auto res = cli.Get("/hi");
  10197. if (is_even) {
  10198. EXPECT_FALSE(res);
  10199. } else {
  10200. EXPECT_TRUE(res);
  10201. EXPECT_EQ("hi...", res->body);
  10202. }
  10203. }
  10204. svr.stop();
  10205. t.join();
  10206. // Server is down...
  10207. {
  10208. Client cli(HOST, PORT);
  10209. auto res = cli.Get("/hi");
  10210. EXPECT_FALSE(res);
  10211. }
  10212. }
  10213. }
  10214. #endif
  10215. // Helper function for string body upload progress tests
  10216. template <typename SetupHandler, typename ClientCall>
  10217. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10218. ClientCall &&client_call,
  10219. const string &body) {
  10220. Server svr;
  10221. setup_handler(svr);
  10222. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10223. auto se = detail::scope_exit([&] {
  10224. svr.stop();
  10225. t.join();
  10226. });
  10227. svr.wait_until_ready();
  10228. Client cli(HOST, PORT);
  10229. vector<uint64_t> progress_values;
  10230. bool progress_called = false;
  10231. auto res =
  10232. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10233. progress_values.push_back(current);
  10234. progress_called = true;
  10235. return true;
  10236. });
  10237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10238. EXPECT_EQ(200, res->status);
  10239. EXPECT_TRUE(progress_called);
  10240. }
  10241. TEST(UploadProgressTest, PostStringBodyBasic) {
  10242. TestStringBodyUploadProgress(
  10243. [](Server &svr) {
  10244. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10245. res.set_content("received", "text/plain");
  10246. });
  10247. },
  10248. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10249. return cli.Post("/test", body, "text/plain", progress_callback);
  10250. },
  10251. "test data for upload progress");
  10252. }
  10253. TEST(UploadProgressTest, PutStringBodyBasic) {
  10254. TestStringBodyUploadProgress(
  10255. [](Server &svr) {
  10256. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10257. res.set_content("put received", "text/plain");
  10258. });
  10259. },
  10260. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10261. return cli.Put("/test", body, "text/plain", progress_callback);
  10262. },
  10263. "put test data for upload progress");
  10264. }
  10265. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10266. TestStringBodyUploadProgress(
  10267. [](Server &svr) {
  10268. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10269. res.set_content("patch received", "text/plain");
  10270. });
  10271. },
  10272. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10273. return cli.Patch("/test", body, "text/plain", progress_callback);
  10274. },
  10275. "patch test data for upload progress");
  10276. }
  10277. // Helper function for content provider upload progress tests
  10278. template <typename SetupHandler, typename ClientCall>
  10279. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10280. ClientCall &&client_call) {
  10281. Server svr;
  10282. setup_handler(svr);
  10283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10284. auto se = detail::scope_exit([&] {
  10285. svr.stop();
  10286. t.join();
  10287. });
  10288. svr.wait_until_ready();
  10289. Client cli(HOST, PORT);
  10290. vector<uint64_t> progress_values;
  10291. auto res =
  10292. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10293. progress_values.push_back(current);
  10294. return true;
  10295. });
  10296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10297. EXPECT_EQ(200, res->status);
  10298. EXPECT_FALSE(progress_values.empty());
  10299. }
  10300. TEST(UploadProgressTest, PostContentProviderProgress) {
  10301. TestContentProviderUploadProgress(
  10302. [](Server &svr) {
  10303. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10304. res.set_content("provider received", "text/plain");
  10305. });
  10306. },
  10307. [](Client &cli, UploadProgress progress_callback) {
  10308. return cli.Post(
  10309. "/test", 9,
  10310. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10311. sink.os << "test data";
  10312. return true;
  10313. },
  10314. "text/plain", progress_callback);
  10315. });
  10316. }
  10317. // Helper function for multipart upload progress tests
  10318. template <typename SetupHandler, typename ClientCall>
  10319. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10320. ClientCall &&client_call,
  10321. const string &endpoint) {
  10322. Server svr;
  10323. setup_handler(svr);
  10324. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10325. auto se = detail::scope_exit([&] {
  10326. svr.stop();
  10327. t.join();
  10328. });
  10329. svr.wait_until_ready();
  10330. Client cli(HOST, PORT);
  10331. vector<uint64_t> progress_values;
  10332. UploadFormDataItems items = {
  10333. {"field1", "value1", "", ""},
  10334. {"field2", "longer value for progress tracking test", "", ""},
  10335. {"file1", "file content data for upload progress", "test.txt",
  10336. "text/plain"}};
  10337. auto res = client_call(cli, endpoint, items,
  10338. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10339. progress_values.push_back(current);
  10340. return true;
  10341. });
  10342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10343. EXPECT_EQ(200, res->status);
  10344. EXPECT_FALSE(progress_values.empty());
  10345. }
  10346. TEST(UploadProgressTest, PostMultipartProgress) {
  10347. TestMultipartUploadProgress(
  10348. [](Server &svr) {
  10349. svr.Post("/multipart", [](const Request &req, Response &res) {
  10350. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10351. res.set_content("multipart received", "text/plain");
  10352. });
  10353. },
  10354. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10355. UploadProgress progress_callback) {
  10356. return cli.Post(endpoint, items, progress_callback);
  10357. },
  10358. "/multipart");
  10359. }
  10360. // Helper function for basic download progress tests
  10361. template <typename SetupHandler, typename ClientCall>
  10362. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10363. ClientCall &&client_call, const string &endpoint,
  10364. size_t expected_content_size) {
  10365. Server svr;
  10366. setup_handler(svr);
  10367. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10368. auto se = detail::scope_exit([&] {
  10369. svr.stop();
  10370. t.join();
  10371. });
  10372. svr.wait_until_ready();
  10373. Client cli(HOST, PORT);
  10374. vector<uint64_t> progress_values;
  10375. auto res = client_call(cli, endpoint,
  10376. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10377. progress_values.push_back(current);
  10378. return true;
  10379. });
  10380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10381. EXPECT_EQ(200, res->status);
  10382. EXPECT_FALSE(progress_values.empty());
  10383. EXPECT_EQ(expected_content_size, res->body.size());
  10384. }
  10385. TEST(DownloadProgressTest, GetBasic) {
  10386. TestBasicDownloadProgress(
  10387. [](Server &svr) {
  10388. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10389. string content(1000, 'D');
  10390. res.set_content(content, "text/plain");
  10391. });
  10392. },
  10393. [](Client &cli, const string &endpoint,
  10394. DownloadProgress progress_callback) {
  10395. return cli.Get(endpoint, progress_callback);
  10396. },
  10397. "/download", 1000u);
  10398. }
  10399. // Helper function for content receiver download progress tests
  10400. template <typename SetupHandler, typename ClientCall>
  10401. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10402. ClientCall &&client_call,
  10403. const string &endpoint,
  10404. size_t expected_content_size) {
  10405. Server svr;
  10406. setup_handler(svr);
  10407. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10408. auto se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. t.join();
  10411. });
  10412. svr.wait_until_ready();
  10413. Client cli(HOST, PORT);
  10414. vector<uint64_t> progress_values;
  10415. string received_body;
  10416. auto res = client_call(
  10417. cli, endpoint,
  10418. [&](const char *data, size_t data_length) -> bool {
  10419. received_body.append(data, data_length);
  10420. return true;
  10421. },
  10422. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10423. progress_values.push_back(current);
  10424. return true;
  10425. });
  10426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10427. EXPECT_EQ(200, res->status);
  10428. EXPECT_FALSE(progress_values.empty());
  10429. EXPECT_EQ(expected_content_size, received_body.size());
  10430. EXPECT_TRUE(res->body.empty());
  10431. }
  10432. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10433. TestContentReceiverDownloadProgress(
  10434. [](Server &svr) {
  10435. svr.Get("/download-receiver",
  10436. [](const Request & /*req*/, Response &res) {
  10437. string content(2000, 'R');
  10438. res.set_content(content, "text/plain");
  10439. });
  10440. },
  10441. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10442. DownloadProgress progress_callback) {
  10443. return cli.Get(endpoint, content_receiver, progress_callback);
  10444. },
  10445. "/download-receiver", 2000u);
  10446. }
  10447. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10448. // A provider reaching a pass with nothing to hand over - an empty buffer
  10449. // popped off a queue, say - must not be taken to mean the body is finished.
  10450. // It used to end the loop with the terminating chunk unwritten while the
  10451. // server still considered the response complete, so the peer waited for an
  10452. // end that never arrived.
  10453. Server svr;
  10454. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10455. auto step = std::make_shared<int>(0);
  10456. res.set_chunked_content_provider("text/plain",
  10457. [step](size_t /*offset*/, DataSink &sink) {
  10458. switch ((*step)++) {
  10459. case 0: sink.write("", 0); break;
  10460. case 1: sink.write("hello", 5); break;
  10461. default: sink.done(); break;
  10462. }
  10463. return true;
  10464. });
  10465. });
  10466. auto port = svr.bind_to_any_port(HOST);
  10467. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10468. auto listen_se = detail::scope_exit([&] {
  10469. svr.stop();
  10470. listen_thread.join();
  10471. ASSERT_FALSE(svr.is_running());
  10472. });
  10473. svr.wait_until_ready();
  10474. Client cli(HOST, port);
  10475. // Without the fix the body is never terminated, so bound the wait rather
  10476. // than letting the test hang on the default read timeout.
  10477. cli.set_read_timeout(5, 0);
  10478. auto res = cli.Get("/stream");
  10479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10480. EXPECT_EQ(StatusCode::OK_200, res->status);
  10481. EXPECT_EQ("hello", res->body);
  10482. }
  10483. TEST(StreamingTest, NoContentLengthStreaming) {
  10484. Server svr;
  10485. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10486. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10487. if (offset < 6) {
  10488. sink.os << (offset < 3 ? "a" : "b");
  10489. } else {
  10490. sink.done();
  10491. }
  10492. return true;
  10493. });
  10494. });
  10495. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10496. auto listen_se = detail::scope_exit([&] {
  10497. svr.stop();
  10498. listen_thread.join();
  10499. ASSERT_FALSE(svr.is_running());
  10500. });
  10501. svr.wait_until_ready();
  10502. Client client(HOST, PORT);
  10503. auto get_thread = std::thread([&client]() {
  10504. std::string s;
  10505. auto res =
  10506. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10507. s += std::string(data, len);
  10508. return true;
  10509. });
  10510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10511. EXPECT_EQ(StatusCode::OK_200, res->status);
  10512. EXPECT_EQ("aaabbb", s);
  10513. });
  10514. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10515. // Give GET time to get a few messages.
  10516. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10517. }
  10518. TEST(MountTest, Unmount) {
  10519. Server svr;
  10520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10521. auto se = detail::scope_exit([&] {
  10522. svr.stop();
  10523. listen_thread.join();
  10524. ASSERT_FALSE(svr.is_running());
  10525. });
  10526. svr.wait_until_ready();
  10527. Client cli("localhost", PORT);
  10528. svr.set_mount_point("/mount2", "./www2");
  10529. auto res = cli.Get("/");
  10530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10532. res = cli.Get("/mount2/dir/test.html");
  10533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10534. EXPECT_EQ(StatusCode::OK_200, res->status);
  10535. svr.set_mount_point("/", "./www");
  10536. res = cli.Get("/dir/");
  10537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10538. EXPECT_EQ(StatusCode::OK_200, res->status);
  10539. svr.remove_mount_point("/");
  10540. res = cli.Get("/dir/");
  10541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10542. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10543. svr.remove_mount_point("/mount2");
  10544. res = cli.Get("/mount2/dir/test.html");
  10545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10547. }
  10548. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10549. Server svr;
  10550. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10551. svr.Get("/api/hello", [](const Request &, Response &res) {
  10552. res.set_content("api", "text/plain");
  10553. });
  10554. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10555. auto se = detail::scope_exit([&] {
  10556. svr.stop();
  10557. listen_thread.join();
  10558. ASSERT_FALSE(svr.is_running());
  10559. });
  10560. svr.wait_until_ready();
  10561. Client cli(HOST, PORT);
  10562. auto res = cli.Get("/dir/test.html");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. res = cli.Get("/api/hello");
  10566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10567. EXPECT_EQ(StatusCode::OK_200, res->status);
  10568. EXPECT_EQ("api", res->body);
  10569. }
  10570. TEST(MountTest, PathSegmentBoundary) {
  10571. Server svr;
  10572. svr.set_mount_point("/mount2", "./www2");
  10573. svr.set_mount_point("/", "./www");
  10574. auto port = svr.bind_to_any_port(HOST);
  10575. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10576. auto se = detail::scope_exit([&] {
  10577. svr.stop();
  10578. listen_thread.join();
  10579. ASSERT_FALSE(svr.is_running());
  10580. });
  10581. svr.wait_until_ready();
  10582. Client cli(HOST, port);
  10583. auto res = cli.Get("/mount2/dir/test.html");
  10584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10585. EXPECT_EQ(StatusCode::OK_200, res->status);
  10586. // "/mount2" must not match part-way through a path segment.
  10587. res = cli.Get("/mount2dir/test.html");
  10588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10590. // A mount point ending in '/' keeps matching every path below it.
  10591. res = cli.Get("/dir/test.html");
  10592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10593. EXPECT_EQ(StatusCode::OK_200, res->status);
  10594. }
  10595. TEST(MountTest, Redicect) {
  10596. Server svr;
  10597. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10598. auto se = detail::scope_exit([&] {
  10599. svr.stop();
  10600. listen_thread.join();
  10601. ASSERT_FALSE(svr.is_running());
  10602. });
  10603. svr.set_mount_point("/", "./www");
  10604. svr.wait_until_ready();
  10605. Client cli("localhost", PORT);
  10606. auto res = cli.Get("/dir/");
  10607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10608. EXPECT_EQ(StatusCode::OK_200, res->status);
  10609. res = cli.Get("/dir");
  10610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10611. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10612. res = cli.Get("/file");
  10613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10614. EXPECT_EQ(StatusCode::OK_200, res->status);
  10615. res = cli.Get("/file/");
  10616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10618. cli.set_follow_location(true);
  10619. res = cli.Get("/dir");
  10620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10621. EXPECT_EQ(StatusCode::OK_200, res->status);
  10622. }
  10623. TEST(MountTest, MultibytesPathName) {
  10624. Server svr;
  10625. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10626. auto se = detail::scope_exit([&] {
  10627. svr.stop();
  10628. listen_thread.join();
  10629. ASSERT_FALSE(svr.is_running());
  10630. });
  10631. svr.set_mount_point("/", "./www");
  10632. svr.wait_until_ready();
  10633. Client cli("localhost", PORT);
  10634. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10636. EXPECT_EQ(StatusCode::OK_200, res->status);
  10637. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10638. }
  10639. // A mount point serves no path with an empty, "." or ".." segment, so a guard
  10640. // in the pre-routing handler sees the path of every file that is served
  10641. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10642. Server svr;
  10643. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10644. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10645. if (req.path == "/dir/test.html") {
  10646. res.status = StatusCode::Unauthorized_401;
  10647. return Server::HandlerResponse::Handled;
  10648. }
  10649. return Server::HandlerResponse::Unhandled;
  10650. });
  10651. auto port = svr.bind_to_any_port(HOST);
  10652. ASSERT_LT(0, port);
  10653. thread t = thread([&] { svr.listen_after_bind(); });
  10654. auto se = detail::scope_exit([&] {
  10655. svr.stop();
  10656. t.join();
  10657. ASSERT_FALSE(svr.is_running());
  10658. });
  10659. svr.wait_until_ready();
  10660. Client cli(HOST, port);
  10661. for (auto path :
  10662. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10663. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html"}) {
  10664. SCOPED_TRACE(path);
  10665. auto res = cli.Get(path);
  10666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10668. }
  10669. }
  10670. #ifdef _WIN32
  10671. // Issue #2435: mmap::open() must succeed even when another handle holds
  10672. // the file open for writing (e.g. an active log file).
  10673. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10674. const char *path = "mmap_concurrent_writer_test.txt";
  10675. const char *content = "hello";
  10676. {
  10677. std::ofstream f(path, std::ios::binary);
  10678. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10679. }
  10680. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10681. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10682. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10683. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10684. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10685. detail::mmap m(path);
  10686. ASSERT_TRUE(m.is_open());
  10687. EXPECT_EQ(strlen(content), m.size());
  10688. char buf[8];
  10689. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10690. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10691. }
  10692. #endif
  10693. #ifndef _WIN32
  10694. // A directory or a device has no size to serve.
  10695. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10696. const char *path = "./mmap_not_regular_test_dir";
  10697. ASSERT_EQ(0, ::mkdir(path, 0755));
  10698. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10699. for (auto p : {path, "/dev/null"}) {
  10700. detail::mmap m(p);
  10701. EXPECT_FALSE(m.is_open()) << p;
  10702. EXPECT_EQ(0U, m.size()) << p;
  10703. }
  10704. Server svr;
  10705. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10706. res.set_file_content("/dev/null");
  10707. });
  10708. auto port = svr.bind_to_any_port(HOST);
  10709. thread t = thread([&] { svr.listen_after_bind(); });
  10710. auto se = detail::scope_exit([&] {
  10711. svr.stop();
  10712. t.join();
  10713. });
  10714. svr.wait_until_ready();
  10715. auto res = Client(HOST, port).Get("/null");
  10716. ASSERT_TRUE(res);
  10717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10718. }
  10719. #endif
  10720. #ifdef __linux__
  10721. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10722. TEST(MmapTest, FileIsNotMapped) {
  10723. const char *path = "mmap_not_mapped_test.txt";
  10724. {
  10725. std::ofstream f(path, std::ios::binary);
  10726. f << "hello";
  10727. }
  10728. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10729. detail::mmap m(path);
  10730. ASSERT_TRUE(m.is_open());
  10731. std::ifstream maps("/proc/self/maps");
  10732. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10733. std::istreambuf_iterator<char>());
  10734. EXPECT_EQ(std::string::npos, mappings.find(path));
  10735. }
  10736. #endif
  10737. TEST(KeepAliveTest, ReadTimeout) {
  10738. Server svr;
  10739. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10740. std::this_thread::sleep_for(std::chrono::seconds(2));
  10741. res.set_content("a", "text/plain");
  10742. });
  10743. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10744. res.set_content("b", "text/plain");
  10745. });
  10746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10747. auto se = detail::scope_exit([&] {
  10748. svr.stop();
  10749. listen_thread.join();
  10750. ASSERT_FALSE(svr.is_running());
  10751. });
  10752. svr.wait_until_ready();
  10753. Client cli("localhost", PORT);
  10754. cli.set_keep_alive(true);
  10755. cli.set_read_timeout(std::chrono::seconds(1));
  10756. auto resa = cli.Get("/a");
  10757. ASSERT_FALSE(resa);
  10758. EXPECT_EQ(Error::Read, resa.error());
  10759. auto resb = cli.Get("/b");
  10760. ASSERT_TRUE(resb);
  10761. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10762. EXPECT_EQ("b", resb->body);
  10763. }
  10764. TEST(KeepAliveTest, MaxCount) {
  10765. size_t keep_alive_max_count = 3;
  10766. Server svr;
  10767. svr.set_keep_alive_max_count(keep_alive_max_count);
  10768. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10769. res.set_content("Hello World!", "text/plain");
  10770. });
  10771. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10772. auto se = detail::scope_exit([&] {
  10773. svr.stop();
  10774. listen_thread.join();
  10775. ASSERT_FALSE(svr.is_running());
  10776. });
  10777. svr.wait_until_ready();
  10778. Client cli(HOST, PORT);
  10779. cli.set_keep_alive(true);
  10780. for (size_t i = 0; i < 5; i++) {
  10781. auto result = cli.Get("/hi");
  10782. ASSERT_TRUE(result);
  10783. EXPECT_EQ(StatusCode::OK_200, result->status);
  10784. if (i == keep_alive_max_count - 1) {
  10785. EXPECT_EQ("close", result->get_header_value("Connection"));
  10786. } else {
  10787. EXPECT_FALSE(result->has_header("Connection"));
  10788. }
  10789. }
  10790. }
  10791. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10792. // can pull the next one into the server's buffer. The server must serve it
  10793. // without waiting for the socket to become readable again. The keep-alive
  10794. // timeout outlasts the client's read timeout, so a request left waiting for it
  10795. // shows up as a missing response.
  10796. static void serve_pipelining_routes(Server &svr,
  10797. const std::function<void(int)> &client) {
  10798. svr.set_keep_alive_timeout(5);
  10799. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10800. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10801. });
  10802. svr.Post("/echo", [](const Request &req, Response &res) {
  10803. res.set_content("echo " + req.body, "text/plain");
  10804. });
  10805. auto port = svr.bind_to_any_port(HOST);
  10806. thread t = thread([&] { svr.listen_after_bind(); });
  10807. auto se = detail::scope_exit([&] {
  10808. svr.stop();
  10809. t.join();
  10810. });
  10811. svr.wait_until_ready();
  10812. client(port);
  10813. }
  10814. static std::string
  10815. send_pipelined_requests(const std::vector<std::string> &parts) {
  10816. Server svr;
  10817. std::string res;
  10818. serve_pipelining_routes(svr, [&](int port) {
  10819. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10820. });
  10821. return res;
  10822. }
  10823. static void expect_in_order(const std::string &res,
  10824. const std::vector<std::string> &bodies) {
  10825. size_t pos = 0;
  10826. for (const auto &body : bodies) {
  10827. pos = res.find(body, pos);
  10828. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10829. pos += body.size();
  10830. }
  10831. }
  10832. TEST(KeepAliveTest, PipelinedRequests) {
  10833. auto res = send_pipelined_requests(
  10834. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10835. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10836. "Content-Length: 4\r\n\r\nbody"
  10837. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10838. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10839. }
  10840. // The second request starts in the server's buffer and ends on the socket.
  10841. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10842. auto res =
  10843. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10844. "GET /hi/2 HTTP/1.1\r\nHo",
  10845. "st: localhost\r\nConnection: close\r\n\r\n"});
  10846. expect_in_order(res, {"hi 1", "hi 2"});
  10847. }
  10848. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10849. // CRLF after a body does not turn into a 400 for the next request.
  10850. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10851. auto res = send_pipelined_requests(
  10852. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10853. "Content-Length: 4\r\n\r\nbody\r\n"
  10854. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10855. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10856. expect_in_order(res, {"echo body", "hi 2"});
  10857. }
  10858. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10859. // must not be served as the next request.
  10860. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10861. auto res = send_pipelined_requests(
  10862. {"INVALID REQUEST LINE\r\n\r\n"
  10863. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10864. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10865. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10866. }
  10867. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10868. // Over TLS, the next request is held by the TLS library as already decrypted
  10869. // data rather than on the socket.
  10870. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10872. std::string res;
  10873. serve_pipelining_routes(svr, [&](int port) {
  10874. // One part, so all three requests arrive in one TLS record
  10875. EXPECT_TRUE(send_ssl_request_in_parts(
  10876. 2,
  10877. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10878. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10879. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10880. &res, port));
  10881. });
  10882. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10883. }
  10884. #endif
  10885. TEST(KeepAliveTest, Issue1041) {
  10886. Server svr;
  10887. svr.set_keep_alive_timeout(3);
  10888. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10889. res.set_content("Hello World!", "text/plain");
  10890. });
  10891. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10892. auto se = detail::scope_exit([&] {
  10893. svr.stop();
  10894. listen_thread.join();
  10895. ASSERT_FALSE(svr.is_running());
  10896. });
  10897. svr.wait_until_ready();
  10898. Client cli(HOST, PORT);
  10899. cli.set_keep_alive(true);
  10900. auto result = cli.Get("/hi");
  10901. ASSERT_TRUE(result);
  10902. EXPECT_EQ(StatusCode::OK_200, result->status);
  10903. std::this_thread::sleep_for(std::chrono::seconds(5));
  10904. result = cli.Get("/hi");
  10905. ASSERT_TRUE(result);
  10906. EXPECT_EQ(StatusCode::OK_200, result->status);
  10907. }
  10908. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10909. Server svr;
  10910. svr.set_keep_alive_max_count(0);
  10911. std::set<int> remote_ports;
  10912. svr.Get("/hi", [&](const Request &req, Response &res) {
  10913. remote_ports.insert(req.remote_port);
  10914. res.set_content("hi", "text/plain");
  10915. });
  10916. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10917. auto se = detail::scope_exit([&] {
  10918. svr.stop();
  10919. listen_thread.join();
  10920. ASSERT_FALSE(svr.is_running());
  10921. });
  10922. svr.wait_until_ready();
  10923. Client cli(HOST, PORT);
  10924. cli.set_keep_alive(true);
  10925. for (int i = 0; i < 3; i++) {
  10926. auto res = cli.Get("/hi");
  10927. ASSERT_TRUE(res);
  10928. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10929. }
  10930. // All three over one connection
  10931. EXPECT_EQ(1u, remote_ports.size());
  10932. }
  10933. TEST(KeepAliveTest, Issue1959) {
  10934. Server svr;
  10935. svr.set_keep_alive_timeout(5);
  10936. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10937. res.set_content("a", "text/plain");
  10938. });
  10939. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10940. auto se = detail::scope_exit([&] {
  10941. if (!svr.is_running()) return;
  10942. svr.stop();
  10943. listen_thread.join();
  10944. ASSERT_FALSE(svr.is_running());
  10945. });
  10946. svr.wait_until_ready();
  10947. Client cli("localhost", PORT);
  10948. cli.set_keep_alive(true);
  10949. using namespace std::chrono;
  10950. auto start = steady_clock::now();
  10951. cli.Get("/a");
  10952. svr.stop();
  10953. listen_thread.join();
  10954. auto end = steady_clock::now();
  10955. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10956. EXPECT_LT(elapsed, 5000);
  10957. }
  10958. #ifdef CPPHTTPLIB_SSL_ENABLED
  10959. TEST(KeepAliveTest, SSLClientReconnection) {
  10960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10961. ASSERT_TRUE(svr.is_valid());
  10962. svr.set_keep_alive_timeout(1);
  10963. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10964. res.set_content("Hello World!", "text/plain");
  10965. });
  10966. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10967. auto se = detail::scope_exit([&] {
  10968. svr.stop();
  10969. listen_thread.join();
  10970. ASSERT_FALSE(svr.is_running());
  10971. });
  10972. svr.wait_until_ready();
  10973. SSLClient cli(HOST, PORT);
  10974. cli.enable_server_certificate_verification(false);
  10975. cli.set_keep_alive(true);
  10976. auto result = cli.Get("/hi");
  10977. ASSERT_TRUE(result);
  10978. EXPECT_EQ(StatusCode::OK_200, result->status);
  10979. result = cli.Get("/hi");
  10980. ASSERT_TRUE(result);
  10981. EXPECT_EQ(StatusCode::OK_200, result->status);
  10982. std::this_thread::sleep_for(std::chrono::seconds(2));
  10983. // Recoonect
  10984. result = cli.Get("/hi");
  10985. ASSERT_TRUE(result);
  10986. EXPECT_EQ(StatusCode::OK_200, result->status);
  10987. result = cli.Get("/hi");
  10988. ASSERT_TRUE(result);
  10989. EXPECT_EQ(StatusCode::OK_200, result->status);
  10990. }
  10991. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10993. ASSERT_TRUE(svr.is_valid());
  10994. svr.set_keep_alive_timeout(1);
  10995. std::string content = "reconnect";
  10996. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10997. res.set_content("Hello World!", "text/plain");
  10998. });
  10999. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11000. auto se = detail::scope_exit([&] {
  11001. svr.stop();
  11002. listen_thread.join();
  11003. ASSERT_FALSE(svr.is_running());
  11004. });
  11005. svr.wait_until_ready();
  11006. SSLClient cli(HOST, PORT);
  11007. cli.enable_server_certificate_verification(false);
  11008. cli.set_keep_alive(true);
  11009. auto result = cli.Post(
  11010. "/hi", content.size(),
  11011. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11012. sink.write(content.c_str(), content.size());
  11013. return true;
  11014. },
  11015. "text/plain");
  11016. ASSERT_TRUE(result);
  11017. EXPECT_EQ(200, result->status);
  11018. std::this_thread::sleep_for(std::chrono::seconds(2));
  11019. // Recoonect
  11020. result = cli.Post(
  11021. "/hi", content.size(),
  11022. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11023. sink.write(content.c_str(), content.size());
  11024. return true;
  11025. },
  11026. "text/plain");
  11027. ASSERT_TRUE(result);
  11028. EXPECT_EQ(200, result->status);
  11029. result = cli.Post(
  11030. "/hi", content.size(),
  11031. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11032. sink.write(content.c_str(), content.size());
  11033. return true;
  11034. },
  11035. "text/plain");
  11036. ASSERT_TRUE(result);
  11037. EXPECT_EQ(200, result->status);
  11038. }
  11039. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11040. using namespace httplib::tls;
  11041. {
  11042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11043. ASSERT_TRUE(svr.is_valid());
  11044. svr.Get("/sni", [&](const Request &req, Response &res) {
  11045. std::string expected = req.sni();
  11046. EXPECT_EQ(expected, req.get_param_value("expected"));
  11047. res.set_content("ok", "text/plain");
  11048. });
  11049. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11050. auto se = detail::scope_exit([&] {
  11051. svr.stop();
  11052. listen_thread.join();
  11053. ASSERT_FALSE(svr.is_running());
  11054. });
  11055. svr.wait_until_ready();
  11056. {
  11057. SSLClient cli("localhost", PORT);
  11058. cli.enable_server_certificate_verification(false);
  11059. auto res = cli.Get("/sni?expected=localhost");
  11060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11061. }
  11062. {
  11063. SSLClient cli("::1", PORT);
  11064. cli.enable_server_certificate_verification(false);
  11065. auto res = cli.Get("/sni?expected=");
  11066. // NOTE: This may fail if the server is listening on IPv4 only
  11067. // (e.g., when localhost resolves to 127.0.0.1 only)
  11068. if (res) {
  11069. EXPECT_EQ(StatusCode::OK_200, res->status);
  11070. } else {
  11071. EXPECT_EQ(Error::Connection, res.error());
  11072. }
  11073. }
  11074. }
  11075. }
  11076. // The SNI of a failed handshake does not reach the next connection that the
  11077. // same worker thread serves
  11078. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11079. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11080. ASSERT_TRUE(svr.is_valid());
  11081. svr.new_task_queue = [] { return new ThreadPool(1); };
  11082. svr.Get("/sni", [](const Request &req, Response &res) {
  11083. res.set_content(req.sni(), "text/plain");
  11084. });
  11085. auto port = svr.bind_to_any_port("127.0.0.1");
  11086. ASSERT_LT(0, port);
  11087. thread t = thread([&] { svr.listen_after_bind(); });
  11088. auto se = detail::scope_exit([&] {
  11089. svr.stop();
  11090. t.join();
  11091. ASSERT_FALSE(svr.is_running());
  11092. });
  11093. svr.wait_until_ready();
  11094. {
  11095. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11096. SSLClient cli("localhost", port);
  11097. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11098. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11099. auto res = cli.Get("/sni");
  11100. ASSERT_FALSE(res);
  11101. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11102. }
  11103. // An IP host sends no SNI (RFC 6066)
  11104. SSLClient cli("127.0.0.1", port);
  11105. cli.enable_server_certificate_verification(false);
  11106. auto res = cli.Get("/sni");
  11107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11108. EXPECT_EQ("", res->body);
  11109. }
  11110. #endif
  11111. TEST(ClientProblemDetectionTest, ContentProvider) {
  11112. Server svr;
  11113. size_t content_length = 1024 * 1024;
  11114. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11115. res.set_content_provider(
  11116. content_length, "text/plain",
  11117. [&](size_t offset, size_t length, DataSink &sink) {
  11118. auto out_len = std::min(length, static_cast<size_t>(1024));
  11119. std::string out(out_len, '@');
  11120. sink.write(out.data(), out_len);
  11121. return offset < 4096;
  11122. },
  11123. [](bool success) { ASSERT_FALSE(success); });
  11124. });
  11125. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11126. res.set_content_provider(
  11127. 0, "text/plain",
  11128. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11129. EXPECT_TRUE(false);
  11130. return true;
  11131. },
  11132. [](bool success) { ASSERT_FALSE(success); });
  11133. });
  11134. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11135. auto se = detail::scope_exit([&] {
  11136. svr.stop();
  11137. listen_thread.join();
  11138. ASSERT_FALSE(svr.is_running());
  11139. });
  11140. svr.wait_until_ready();
  11141. Client cli("localhost", PORT);
  11142. {
  11143. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11144. size_t /*data_length*/) { return false; });
  11145. ASSERT_FALSE(res);
  11146. }
  11147. {
  11148. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11149. size_t /*data_length*/) { return false; });
  11150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11151. }
  11152. }
  11153. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11154. // A provider that reports success without writing anything and without
  11155. // calling done() used to be handed the same offset and length again on every
  11156. // pass, so it spun for as long as the peer stayed connected.
  11157. Server svr;
  11158. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11159. res.set_content("ok", "text/plain");
  11160. });
  11161. auto port = svr.bind_to_any_port(HOST);
  11162. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11163. auto se = detail::scope_exit([&] {
  11164. svr.stop();
  11165. listen_thread.join();
  11166. ASSERT_FALSE(svr.is_running());
  11167. });
  11168. svr.wait_until_ready();
  11169. std::atomic<int> call_count{0};
  11170. Client cli(HOST, port);
  11171. auto res = cli.Post(
  11172. "/", 1024,
  11173. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11174. // Give up after enough passes to show the spin, so that losing the
  11175. // check below fails this test instead of hanging it.
  11176. return ++call_count < 100;
  11177. },
  11178. "text/plain");
  11179. ASSERT_FALSE(res);
  11180. EXPECT_EQ(Error::Write, res.error());
  11181. EXPECT_EQ(1, call_count.load());
  11182. }
  11183. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11184. // A writer only has to assign `write`. The other three used to be left as
  11185. // empty std::functions, so a provider calling one threw
  11186. // std::bad_function_call out of the thread running it and took the whole
  11187. // process down.
  11188. DataSink sink;
  11189. std::string written;
  11190. sink.write = [&](const char *data, size_t data_len) {
  11191. written.append(data, data_len);
  11192. return true;
  11193. };
  11194. EXPECT_TRUE(sink.is_writable());
  11195. sink.done();
  11196. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11197. EXPECT_TRUE(written.empty());
  11198. }
  11199. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11200. // A sink that cannot carry trailers still has to finish.
  11201. DataSink sink;
  11202. auto done_count = 0;
  11203. sink.done = [&]() { done_count++; };
  11204. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11205. EXPECT_EQ(1, done_count);
  11206. }
  11207. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11208. Server svr;
  11209. const std::string body(4096, 'x');
  11210. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11211. res.set_content_provider(body.size(), "text/plain",
  11212. [&](size_t offset, size_t length, DataSink &sink) {
  11213. sink.write(body.data() + offset, length);
  11214. sink.done();
  11215. return true;
  11216. });
  11217. });
  11218. auto port = svr.bind_to_any_port(HOST);
  11219. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11220. auto se = detail::scope_exit([&] {
  11221. svr.stop();
  11222. listen_thread.join();
  11223. ASSERT_FALSE(svr.is_running());
  11224. });
  11225. svr.wait_until_ready();
  11226. Client cli(HOST, port);
  11227. auto res = cli.Get("/");
  11228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11229. EXPECT_EQ(StatusCode::OK_200, res->status);
  11230. EXPECT_EQ(body, res->body);
  11231. }
  11232. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11233. Server svr;
  11234. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11235. res.set_content_provider(
  11236. 1024, "text/plain",
  11237. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11238. sink.write("hello", 5);
  11239. sink.done(); // short of the 1024 bytes the response promised
  11240. return true;
  11241. });
  11242. });
  11243. auto port = svr.bind_to_any_port(HOST);
  11244. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11245. auto se = detail::scope_exit([&] {
  11246. svr.stop();
  11247. listen_thread.join();
  11248. ASSERT_FALSE(svr.is_running());
  11249. });
  11250. svr.wait_until_ready();
  11251. Client cli(HOST, port);
  11252. cli.set_read_timeout(5, 0);
  11253. // The response is short of its Content-Length, so the client cannot read a
  11254. // complete body. What matters is that this returns at all: a no-op done()
  11255. // would leave the writer looping over a provider that never makes progress.
  11256. auto res = cli.Get("/");
  11257. EXPECT_FALSE(res);
  11258. }
  11259. // Read as the next response by a peer that sees it after a framed body.
  11260. static const std::string smuggled_response =
  11261. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11262. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11263. Server svr;
  11264. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11265. res.set_content_provider(
  11266. 5, "text/plain",
  11267. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11268. auto data = "AAAAA" + smuggled_response;
  11269. sink.write(data.data(), data.size());
  11270. return true;
  11271. });
  11272. });
  11273. thread t = thread([&] { svr.listen(HOST, PORT); });
  11274. auto se = detail::scope_exit([&] {
  11275. svr.stop();
  11276. t.join();
  11277. ASSERT_FALSE(svr.is_running());
  11278. });
  11279. svr.wait_until_ready();
  11280. std::string resp;
  11281. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11282. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11283. resp.clear();
  11284. ASSERT_TRUE(send_request(
  11285. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11286. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11287. }
  11288. TEST(NoContentTest, BodyIsNotSent) {
  11289. Server svr;
  11290. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11291. res.status = StatusCode::NoContent_204;
  11292. res.set_content(smuggled_response, "text/plain");
  11293. });
  11294. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11295. res.status = StatusCode::NotModified_304;
  11296. res.set_chunked_content_provider(
  11297. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11298. sink.write(smuggled_response.data(), smuggled_response.size());
  11299. sink.done();
  11300. return true;
  11301. });
  11302. });
  11303. thread t = thread([&] { svr.listen(HOST, PORT); });
  11304. auto se = detail::scope_exit([&] {
  11305. svr.stop();
  11306. t.join();
  11307. ASSERT_FALSE(svr.is_running());
  11308. });
  11309. svr.wait_until_ready();
  11310. for (auto path : {"/204", "/304"}) {
  11311. std::string resp;
  11312. ASSERT_TRUE(send_request(
  11313. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11314. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11315. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11316. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11317. }
  11318. }
  11319. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11320. Server svr;
  11321. std::atomic<bool> smuggled(false);
  11322. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11323. res.set_content("ok", "text/plain");
  11324. });
  11325. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11326. smuggled = true;
  11327. });
  11328. auto port = svr.bind_to_any_port(HOST);
  11329. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11330. auto se = detail::scope_exit([&] {
  11331. svr.stop();
  11332. listen_thread.join();
  11333. ASSERT_FALSE(svr.is_running());
  11334. });
  11335. svr.wait_until_ready();
  11336. // What follows the body would be read as the next request.
  11337. Client cli(HOST, port);
  11338. auto res = cli.Post(
  11339. "/", 5,
  11340. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11341. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11342. sink.write(data.data(), data.size());
  11343. return true;
  11344. },
  11345. "text/plain");
  11346. ASSERT_FALSE(res);
  11347. EXPECT_EQ(Error::Write, res.error());
  11348. EXPECT_FALSE(smuggled);
  11349. }
  11350. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11351. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11352. // The compressed path builds the whole body before connecting, so this
  11353. // fails client-side and never reaches a server.
  11354. Client cli(HOST, PORT);
  11355. cli.set_compress(true);
  11356. auto res = cli.Post(
  11357. "/", 1024,
  11358. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11359. sink.write("hello", 5);
  11360. sink.done(); // short of the 1024 bytes the request announced
  11361. return true;
  11362. },
  11363. "text/plain");
  11364. ASSERT_FALSE(res);
  11365. EXPECT_EQ(Error::Write, res.error());
  11366. }
  11367. #endif
  11368. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11369. Server svr;
  11370. svr.set_error_handler([](Request const &, Response &res) -> void {
  11371. res.set_chunked_content_provider(
  11372. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11373. sink.os << "hello";
  11374. sink.os << "world";
  11375. sink.done();
  11376. return true;
  11377. });
  11378. });
  11379. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11380. auto se = detail::scope_exit([&] {
  11381. svr.stop();
  11382. listen_thread.join();
  11383. ASSERT_FALSE(svr.is_running());
  11384. });
  11385. svr.wait_until_ready();
  11386. Client cli("localhost", PORT);
  11387. auto res = cli.Get("/");
  11388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11389. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11390. EXPECT_EQ("helloworld", res->body);
  11391. }
  11392. // A body set after a content provider must replace it, not be sent through it.
  11393. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11394. Server svr;
  11395. svr.set_mount_point("/", "./www");
  11396. svr.set_file_request_handler([](const Request &req, Response &res) {
  11397. if (req.path == "/dir/test.html") {
  11398. res.status = StatusCode::Forbidden_403;
  11399. res.set_content(std::string(5000, 'D'), "text/plain");
  11400. } else if (req.path == "/file") {
  11401. res.status = StatusCode::Forbidden_403;
  11402. res.body = "Denied";
  11403. }
  11404. });
  11405. auto port = svr.bind_to_any_port(HOST);
  11406. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11407. auto se = detail::scope_exit([&] {
  11408. svr.stop();
  11409. t.join();
  11410. ASSERT_FALSE(svr.is_running());
  11411. });
  11412. svr.wait_until_ready();
  11413. Client cli(HOST, port);
  11414. {
  11415. auto res = cli.Get("/dir/test.html");
  11416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11417. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11418. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11419. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11420. }
  11421. {
  11422. auto res = cli.Get("/file");
  11423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11424. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11425. EXPECT_EQ("Denied", res->body);
  11426. }
  11427. {
  11428. auto res = cli.Get("/dir/index.html");
  11429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11430. EXPECT_EQ(StatusCode::OK_200, res->status);
  11431. EXPECT_EQ(0U, res->body.find("<html>"));
  11432. }
  11433. }
  11434. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11435. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11436. Server svr;
  11437. std::vector<bool> released;
  11438. std::mutex released_mutex;
  11439. auto releaser = [&](bool success) {
  11440. std::lock_guard<std::mutex> guard(released_mutex);
  11441. released.push_back(success);
  11442. };
  11443. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11444. return sink.write(&"hello"[offset], length);
  11445. };
  11446. svr.Get("/sized", [&](const Request &, Response &res) {
  11447. res.status = StatusCode::NotFound_404;
  11448. res.set_content_provider(5, "text/plain", provider, releaser);
  11449. });
  11450. svr.Get("/chunked", [&](const Request &, Response &res) {
  11451. res.status = StatusCode::ServiceUnavailable_503;
  11452. res.set_chunked_content_provider(
  11453. "text/plain",
  11454. [](size_t, DataSink &sink) {
  11455. sink.os << "chunk";
  11456. sink.done();
  11457. return true;
  11458. },
  11459. releaser);
  11460. });
  11461. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11462. res.set_content_provider(5, "text/plain", provider, releaser);
  11463. throw std::runtime_error("after the provider");
  11464. });
  11465. svr.set_error_handler([](const Request &req, Response &res) {
  11466. // Leave the exception handler's content to it.
  11467. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11468. res.set_content(std::string(1000, 'E'), "text/html");
  11469. return Server::HandlerResponse::Handled;
  11470. });
  11471. svr.set_exception_handler(
  11472. [](const Request &, Response &res, std::exception_ptr) {
  11473. res.status = StatusCode::InternalServerError_500;
  11474. res.set_content(std::string(1000, 'X'), "text/html");
  11475. });
  11476. auto port = svr.bind_to_any_port(HOST);
  11477. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11478. auto se = detail::scope_exit([&] {
  11479. svr.stop();
  11480. t.join();
  11481. ASSERT_FALSE(svr.is_running());
  11482. });
  11483. svr.wait_until_ready();
  11484. Client cli(HOST, port);
  11485. {
  11486. auto res = cli.Get("/sized");
  11487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11489. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11490. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11491. }
  11492. {
  11493. auto res = cli.Get("/chunked");
  11494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11495. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11496. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11497. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11498. }
  11499. {
  11500. auto res = cli.Get("/throw");
  11501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11502. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11503. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11504. }
  11505. std::lock_guard<std::mutex> guard(released_mutex);
  11506. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11507. }
  11508. #endif
  11509. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11510. Server svr;
  11511. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11512. return sink.write(&"abc"[offset], length);
  11513. };
  11514. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11515. res.set_file_content("./www/dir/test.html");
  11516. res.set_content("body", "text/plain");
  11517. });
  11518. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11519. res.set_content(std::string(100, 'B'), "text/plain");
  11520. res.set_file_content("./www/dir/test.html");
  11521. });
  11522. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11523. res.set_content(std::string(100, 'B'), "text/plain");
  11524. res.set_content_provider(3, "text/x-provider", abc);
  11525. });
  11526. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11527. res.set_content_provider(3, "text/x-provider", abc);
  11528. res.set_content(std::string(100, 'B'), "text/plain");
  11529. });
  11530. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11531. res.set_content_provider(3, "text/x-provider", abc);
  11532. res.set_file_content("./www/dir/test.html", "text/x-file");
  11533. });
  11534. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11535. res.set_file_content("./www/dir/test.html");
  11536. res.set_header("Content-Type", "text/x-handler");
  11537. });
  11538. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11539. res.set_content_provider(3, "text/plain", abc);
  11540. res.body = "direct";
  11541. });
  11542. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11543. res.set_file_content("./www/dir/test.html");
  11544. res.body = "direct";
  11545. });
  11546. auto port = svr.bind_to_any_port(HOST);
  11547. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11548. auto se = detail::scope_exit([&] {
  11549. svr.stop();
  11550. t.join();
  11551. ASSERT_FALSE(svr.is_running());
  11552. });
  11553. svr.wait_until_ready();
  11554. Client cli(HOST, port);
  11555. auto expect_body = [&](const char *path, const std::string &body,
  11556. const std::string &type) {
  11557. // Uncompressed, so Content-Length can be compared with the body.
  11558. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11559. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11560. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11561. EXPECT_EQ(body, res->body) << path;
  11562. EXPECT_EQ(std::to_string(body.size()),
  11563. res->get_header_value("Content-Length"))
  11564. << path;
  11565. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11566. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11567. };
  11568. expect_body("/file-then-body", "body", "text/plain");
  11569. expect_body("/body-then-file", "test.html", "text/html");
  11570. expect_body("/body-then-provider", "abc", "text/x-provider");
  11571. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11572. expect_body("/provider-then-file", "test.html", "text/x-file");
  11573. expect_body("/file-then-header", "test.html", "text/x-handler");
  11574. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11575. expect_body("/file-then-direct-body", "direct", "text/plain");
  11576. // Ranges are checked against the body, not the dropped provider.
  11577. {
  11578. auto res = cli.Get("/provider-then-direct-body",
  11579. Headers{{make_range_header({{1, 2}})}});
  11580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11581. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11582. EXPECT_EQ("ir", res->body);
  11583. }
  11584. {
  11585. auto res = cli.Get("/file-then-direct-body",
  11586. Headers{{make_range_header({{7, 8}})}});
  11587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11588. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11589. }
  11590. }
  11591. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11592. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11593. const char *path = "./truncated_while_served.txt";
  11594. const size_t size = 32 * 1024 * 1024;
  11595. {
  11596. std::ofstream f(path, std::ios::binary);
  11597. f << std::string(size, 'x');
  11598. }
  11599. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11600. // Over TLS, where the bytes are encrypted in this process rather than
  11601. // copied by send().
  11602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11603. svr.Get("/file", [&](const Request &, Response &res) {
  11604. res.set_file_content(path, "text/plain");
  11605. });
  11606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11607. auto se = detail::scope_exit([&] {
  11608. svr.stop();
  11609. thread.join();
  11610. ASSERT_FALSE(svr.is_running());
  11611. });
  11612. svr.wait_until_ready();
  11613. // The file shrinks once the first bytes are in, as a rewrite in place
  11614. // would, and reading the mapping past its new end used to raise SIGBUS.
  11615. SSLClient cli(HOST, PORT);
  11616. cli.enable_server_certificate_verification(false);
  11617. size_t received = 0;
  11618. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11619. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11620. received += len;
  11621. return true;
  11622. });
  11623. EXPECT_FALSE(res);
  11624. EXPECT_LT(received, size);
  11625. }
  11626. #endif
  11627. // Forward declaration (see the base64_encode note).
  11628. namespace httplib {
  11629. namespace detail {
  11630. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11631. const std::string &content_type,
  11632. EncodingType encoding);
  11633. } // namespace detail
  11634. } // namespace httplib
  11635. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11636. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11637. ASSERT_TRUE(mm->is_open());
  11638. Response res;
  11639. detail::set_file_content_provider(res, mm, "text/html",
  11640. detail::EncodingType::None);
  11641. std::string out;
  11642. DataSink sink;
  11643. sink.write = [&](const char *d, size_t l) {
  11644. out.append(d, l);
  11645. return true;
  11646. };
  11647. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11648. EXPECT_EQ("test.html", out);
  11649. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11650. EXPECT_EQ("test.html", out);
  11651. }
  11652. TEST(LongPollingTest, ClientCloseDetection) {
  11653. Server svr;
  11654. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11655. res.set_chunked_content_provider(
  11656. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11657. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11658. sink.os << "hello";
  11659. auto count = 10;
  11660. while (count > 0 && sink.is_writable()) {
  11661. this_thread::sleep_for(chrono::milliseconds(10));
  11662. count--;
  11663. }
  11664. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11665. return true;
  11666. });
  11667. });
  11668. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11669. auto se = detail::scope_exit([&] {
  11670. svr.stop();
  11671. listen_thread.join();
  11672. ASSERT_FALSE(svr.is_running());
  11673. });
  11674. svr.wait_until_ready();
  11675. Client cli("localhost", PORT);
  11676. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11677. EXPECT_EQ("hello", string(data, data_length));
  11678. return false; // close the socket immediately.
  11679. });
  11680. ASSERT_FALSE(res);
  11681. }
  11682. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11683. Server svr;
  11684. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11685. res.set_chunked_content_provider(
  11686. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11687. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11688. sink.os << "hello";
  11689. EXPECT_TRUE(sink.os.good());
  11690. // Wait for the client to close the connection
  11691. auto count = 10;
  11692. while (count > 0 && sink.is_writable()) {
  11693. this_thread::sleep_for(chrono::milliseconds(10));
  11694. count--;
  11695. }
  11696. // After client disconnect, write repeatedly until the socket
  11697. // write actually fails (small writes may be absorbed by the
  11698. // kernel buffer)
  11699. std::string chunk(1024, 'x');
  11700. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11701. sink.os << chunk;
  11702. }
  11703. EXPECT_TRUE(sink.os.fail());
  11704. return true;
  11705. });
  11706. });
  11707. auto port = svr.bind_to_any_port("localhost");
  11708. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. listen_thread.join();
  11712. ASSERT_FALSE(svr.is_running());
  11713. });
  11714. svr.wait_until_ready();
  11715. Client cli("localhost", port);
  11716. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11717. EXPECT_EQ("hello", string(data, data_length));
  11718. return false; // close the socket immediately.
  11719. });
  11720. ASSERT_FALSE(res);
  11721. }
  11722. TEST(GetWithParametersTest, GetWithParameters) {
  11723. Server svr;
  11724. svr.Get("/", [&](const Request &req, Response &) {
  11725. EXPECT_EQ("world", req.get_param_value("hello"));
  11726. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11727. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11728. });
  11729. svr.Get("/params", [&](const Request &req, Response &) {
  11730. EXPECT_EQ("world", req.get_param_value("hello"));
  11731. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11732. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11733. });
  11734. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11735. EXPECT_EQ("resource-id", req.matches[1]);
  11736. EXPECT_EQ("foo", req.get_param_value("param1"));
  11737. EXPECT_EQ("bar", req.get_param_value("param2"));
  11738. });
  11739. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11740. EXPECT_EQ("user-id", req.path_params.at("id"));
  11741. EXPECT_EQ("foo", req.get_param_value("param1"));
  11742. EXPECT_EQ("bar", req.get_param_value("param2"));
  11743. });
  11744. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11745. auto se = detail::scope_exit([&] {
  11746. svr.stop();
  11747. listen_thread.join();
  11748. ASSERT_FALSE(svr.is_running());
  11749. });
  11750. svr.wait_until_ready();
  11751. {
  11752. Client cli(HOST, PORT);
  11753. Params params;
  11754. params.emplace("hello", "world");
  11755. params.emplace("hello2", "world2");
  11756. params.emplace("hello3", "world3");
  11757. auto res = cli.Get("/", params, Headers{});
  11758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11759. EXPECT_EQ(StatusCode::OK_200, res->status);
  11760. }
  11761. {
  11762. Client cli(HOST, PORT);
  11763. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11765. EXPECT_EQ(StatusCode::OK_200, res->status);
  11766. }
  11767. {
  11768. Client cli(HOST, PORT);
  11769. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11771. EXPECT_EQ(StatusCode::OK_200, res->status);
  11772. }
  11773. {
  11774. Client cli(HOST, PORT);
  11775. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11777. EXPECT_EQ(StatusCode::OK_200, res->status);
  11778. }
  11779. }
  11780. TEST(GetWithParametersTest, GetWithParameters2) {
  11781. Server svr;
  11782. svr.Get("/", [&](const Request &req, Response &res) {
  11783. auto text = req.get_param_value("hello");
  11784. res.set_content(text, "text/plain");
  11785. });
  11786. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11787. auto se = detail::scope_exit([&] {
  11788. svr.stop();
  11789. listen_thread.join();
  11790. ASSERT_FALSE(svr.is_running());
  11791. });
  11792. svr.wait_until_ready();
  11793. Client cli("localhost", PORT);
  11794. Params params;
  11795. params.emplace("hello", "world");
  11796. std::string body;
  11797. auto res = cli.Get("/", params, Headers{},
  11798. [&](const char *data, size_t data_length) {
  11799. body.append(data, data_length);
  11800. return true;
  11801. });
  11802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11803. EXPECT_EQ(StatusCode::OK_200, res->status);
  11804. EXPECT_EQ("world", body);
  11805. }
  11806. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11807. Server svr;
  11808. svr.Get("/search", [&](const Request &req, Response &res) {
  11809. auto q = req.get_param_value("q");
  11810. res.set_content(q, "text/plain");
  11811. });
  11812. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11813. auto se = detail::scope_exit([&] {
  11814. svr.stop();
  11815. listen_thread.join();
  11816. ASSERT_FALSE(svr.is_running());
  11817. });
  11818. svr.wait_until_ready();
  11819. Client cli("localhost", PORT);
  11820. // Verify that Get(path, params) works without requiring Headers argument
  11821. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11823. EXPECT_EQ(StatusCode::OK_200, res->status);
  11824. EXPECT_EQ("cpp-httplib", res->body);
  11825. }
  11826. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11827. auto host = "httpbingo.org";
  11828. auto path = std::string{"/range/32"};
  11829. #ifdef CPPHTTPLIB_SSL_ENABLED
  11830. SSLClient cli(host);
  11831. #else
  11832. Client cli(host);
  11833. #endif
  11834. cli.set_default_headers({make_range_header({{1, 10}})});
  11835. cli.set_connection_timeout(5);
  11836. {
  11837. auto res = cli.Get(path);
  11838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11839. EXPECT_EQ("bcdefghijk", res->body);
  11840. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11841. }
  11842. {
  11843. auto res = cli.Get(path);
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. EXPECT_EQ("bcdefghijk", res->body);
  11846. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11847. }
  11848. }
  11849. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11850. Server svr;
  11851. svr.set_default_headers({{"Hello", "World"}});
  11852. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11853. res.set_content("ok", "text/plain");
  11854. });
  11855. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11856. auto se = detail::scope_exit([&] {
  11857. svr.stop();
  11858. listen_thread.join();
  11859. ASSERT_FALSE(svr.is_running());
  11860. });
  11861. svr.wait_until_ready();
  11862. Client cli("localhost", PORT);
  11863. auto res = cli.Get("/");
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. EXPECT_EQ(StatusCode::OK_200, res->status);
  11866. EXPECT_EQ("ok", res->body);
  11867. EXPECT_EQ("World", res->get_header_value("Hello"));
  11868. }
  11869. #ifdef CPPHTTPLIB_SSL_ENABLED
  11870. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11872. ASSERT_TRUE(svr.is_valid());
  11873. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11874. std::this_thread::sleep_for(std::chrono::seconds(2));
  11875. res.set_content("a", "text/plain");
  11876. });
  11877. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11878. res.set_content("b", "text/plain");
  11879. });
  11880. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11881. auto se = detail::scope_exit([&] {
  11882. svr.stop();
  11883. listen_thread.join();
  11884. ASSERT_FALSE(svr.is_running());
  11885. });
  11886. svr.wait_until_ready();
  11887. SSLClient cli("localhost", PORT);
  11888. cli.enable_server_certificate_verification(false);
  11889. cli.set_keep_alive(true);
  11890. cli.set_read_timeout(std::chrono::seconds(1));
  11891. auto resa = cli.Get("/a");
  11892. ASSERT_TRUE(!resa);
  11893. EXPECT_EQ(Error::Read, resa.error());
  11894. auto resb = cli.Get("/b");
  11895. ASSERT_TRUE(resb);
  11896. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11897. EXPECT_EQ("b", resb->body);
  11898. }
  11899. // Closing an idle keep-alive connection sends close_notify and returns. The
  11900. // server must not wait for the client's close_notify: an idle client never
  11901. // sends one, so the worker would be held until the read timeout expires, and
  11902. // stop() would wait for it.
  11903. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11905. ASSERT_TRUE(svr.is_valid());
  11906. svr.set_keep_alive_timeout(1);
  11907. svr.set_read_timeout(10, 0);
  11908. svr.Get("/", [](const Request &, Response &res) {
  11909. res.set_content("ok", "text/plain");
  11910. });
  11911. auto port = svr.bind_to_any_port(HOST);
  11912. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11913. auto se = detail::scope_exit([&] {
  11914. if (listen_thread.joinable()) {
  11915. svr.stop();
  11916. listen_thread.join();
  11917. }
  11918. });
  11919. svr.wait_until_ready();
  11920. SSLClient cli(HOST, port);
  11921. cli.enable_server_certificate_verification(false);
  11922. cli.set_keep_alive(true);
  11923. auto res = cli.Get("/");
  11924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11925. EXPECT_EQ(StatusCode::OK_200, res->status);
  11926. // Stay idle past the keep-alive timeout so the server closes the connection.
  11927. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11928. auto start = std::chrono::steady_clock::now();
  11929. svr.stop();
  11930. listen_thread.join();
  11931. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11932. std::chrono::steady_clock::now() - start)
  11933. .count();
  11934. EXPECT_LT(elapsed, 3000);
  11935. }
  11936. #endif
  11937. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11938. protected:
  11939. ServerTestWithAI_PASSIVE()
  11940. : cli_(HOST, PORT)
  11941. #ifdef CPPHTTPLIB_SSL_ENABLED
  11942. ,
  11943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11944. #endif
  11945. {
  11946. #ifdef CPPHTTPLIB_SSL_ENABLED
  11947. cli_.enable_server_certificate_verification(false);
  11948. #endif
  11949. }
  11950. virtual void SetUp() {
  11951. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11952. res.set_content("Hello World!", "text/plain");
  11953. });
  11954. t_ = thread(
  11955. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11956. svr_.wait_until_ready();
  11957. }
  11958. virtual void TearDown() {
  11959. svr_.stop();
  11960. t_.join();
  11961. }
  11962. #ifdef CPPHTTPLIB_SSL_ENABLED
  11963. SSLClient cli_;
  11964. SSLServer svr_;
  11965. #else
  11966. Client cli_;
  11967. Server svr_;
  11968. #endif
  11969. thread t_;
  11970. };
  11971. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11972. auto res = cli_.Get("/hi");
  11973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11974. EXPECT_EQ(StatusCode::OK_200, res->status);
  11975. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11976. EXPECT_EQ("Hello World!", res->body);
  11977. }
  11978. class ServerUpDownTest : public ::testing::Test {
  11979. protected:
  11980. ServerUpDownTest() : cli_(HOST, PORT) {}
  11981. virtual void SetUp() {
  11982. t_ = thread([&]() {
  11983. svr_.bind_to_any_port(HOST);
  11984. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11985. ASSERT_TRUE(svr_.listen_after_bind());
  11986. });
  11987. svr_.wait_until_ready();
  11988. }
  11989. virtual void TearDown() {
  11990. svr_.stop();
  11991. t_.join();
  11992. }
  11993. Client cli_;
  11994. Server svr_;
  11995. thread t_;
  11996. };
  11997. TEST_F(ServerUpDownTest, QuickStartStop) {
  11998. // Should not crash, especially when run with
  11999. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12000. }
  12001. class PayloadMaxLengthTest : public ::testing::Test {
  12002. protected:
  12003. PayloadMaxLengthTest()
  12004. : cli_(HOST, PORT)
  12005. #ifdef CPPHTTPLIB_SSL_ENABLED
  12006. ,
  12007. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12008. #endif
  12009. {
  12010. #ifdef CPPHTTPLIB_SSL_ENABLED
  12011. cli_.enable_server_certificate_verification(false);
  12012. #endif
  12013. }
  12014. virtual void SetUp() {
  12015. svr_.set_payload_max_length(8);
  12016. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12017. res.set_content("test", "text/plain");
  12018. });
  12019. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12020. svr_.wait_until_ready();
  12021. }
  12022. virtual void TearDown() {
  12023. svr_.stop();
  12024. t_.join();
  12025. }
  12026. #ifdef CPPHTTPLIB_SSL_ENABLED
  12027. SSLClient cli_;
  12028. SSLServer svr_;
  12029. #else
  12030. Client cli_;
  12031. Server svr_;
  12032. #endif
  12033. thread t_;
  12034. };
  12035. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12036. auto res = cli_.Post("/test", "123456789", "text/plain");
  12037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12038. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12039. res = cli_.Post("/test", "12345678", "text/plain");
  12040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12041. EXPECT_EQ(StatusCode::OK_200, res->status);
  12042. }
  12043. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12044. // Test chunked encoding with payload exceeding the 8-byte limit
  12045. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12046. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12048. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12049. }
  12050. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12051. // Test chunked encoding with payload within the 8-byte limit
  12052. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12053. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12055. EXPECT_EQ(StatusCode::OK_200, res->status);
  12056. }
  12057. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12058. // Test using send_request to send chunked data exceeding payload limit
  12059. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12060. "Host: " +
  12061. std::string(HOST) + ":" + std::to_string(PORT) +
  12062. "\r\n"
  12063. "Transfer-Encoding: chunked\r\n"
  12064. "Connection: close\r\n"
  12065. "\r\n"
  12066. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12067. "0123456789\r\n"
  12068. "0\r\n" // End chunk
  12069. "\r\n";
  12070. std::string response;
  12071. bool result = send_request(1, chunked_request, &response);
  12072. if (!result) {
  12073. // If send_request fails, it might be because the server closed the
  12074. // connection due to payload limit enforcement, which is acceptable
  12075. SUCCEED()
  12076. << "Server rejected oversized chunked request (connection closed)";
  12077. } else {
  12078. // If we got a response, check if it's an error response or connection was
  12079. // closed early Short response length indicates connection was closed due to
  12080. // payload limit
  12081. if (response.length() <= 10) {
  12082. SUCCEED() << "Server closed connection for oversized chunked request";
  12083. } else {
  12084. // Check for error status codes
  12085. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12086. response.find("Payload Too Large") != std::string::npos ||
  12087. response.find("400") != std::string::npos);
  12088. }
  12089. }
  12090. }
  12091. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  12092. // Test request without Content-Length header exceeding payload limit
  12093. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12094. "Host: " +
  12095. std::string(HOST) + ":" +
  12096. std::to_string(PORT) +
  12097. "\r\n"
  12098. "Connection: close\r\n"
  12099. "\r\n";
  12100. // Add payload exceeding the 8-byte limit
  12101. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12102. request_without_content_length += large_payload;
  12103. std::string response;
  12104. bool result = send_request(1, request_without_content_length, &response);
  12105. if (!result) {
  12106. // If send_request fails, server likely closed connection due to payload
  12107. // limit
  12108. SUCCEED() << "Server rejected oversized request without Content-Length "
  12109. "(connection closed)";
  12110. } else {
  12111. // Check if server responded with error or closed connection early
  12112. if (response.length() <= 10) {
  12113. SUCCEED() << "Server closed connection for oversized request without "
  12114. "Content-Length";
  12115. } else {
  12116. // Check for error status codes
  12117. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12118. response.find("Payload Too Large") != std::string::npos ||
  12119. response.find("400") != std::string::npos);
  12120. }
  12121. }
  12122. }
  12123. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12124. // Test request without Content-Length header within payload limit
  12125. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12126. "Host: " +
  12127. std::string(HOST) + ":" +
  12128. std::to_string(PORT) +
  12129. "\r\n"
  12130. "Connection: close\r\n"
  12131. "\r\n";
  12132. // Add payload within the 8-byte limit
  12133. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12134. request_without_content_length += small_payload;
  12135. std::string response;
  12136. bool result = send_request(1, request_without_content_length, &response);
  12137. // For requests without Content-Length, the server may have different behavior
  12138. // The key is that it should not reject due to payload limit for small
  12139. // payloads
  12140. if (result) {
  12141. // Check for any HTTP response (success or error, but not connection closed)
  12142. if (response.length() > 10) {
  12143. SUCCEED()
  12144. << "Server processed request without Content-Length within limit";
  12145. } else {
  12146. // Short response might indicate connection closed, which is acceptable
  12147. SUCCEED() << "Server closed connection for request without "
  12148. "Content-Length (acceptable behavior)";
  12149. }
  12150. } else {
  12151. // Connection failure might be due to protocol requirements
  12152. SUCCEED() << "Connection issue with request without Content-Length "
  12153. "(environment-specific)";
  12154. }
  12155. }
  12156. class LargePayloadMaxLengthTest : public ::testing::Test {
  12157. protected:
  12158. LargePayloadMaxLengthTest()
  12159. : cli_(HOST, PORT)
  12160. #ifdef CPPHTTPLIB_SSL_ENABLED
  12161. ,
  12162. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12163. #endif
  12164. {
  12165. #ifdef CPPHTTPLIB_SSL_ENABLED
  12166. cli_.enable_server_certificate_verification(false);
  12167. #endif
  12168. }
  12169. virtual void SetUp() {
  12170. // Set 10MB payload limit
  12171. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12172. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12173. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12174. res.set_content("Large payload test", "text/plain");
  12175. });
  12176. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12177. svr_.wait_until_ready();
  12178. }
  12179. virtual void TearDown() {
  12180. svr_.stop();
  12181. t_.join();
  12182. }
  12183. #ifdef CPPHTTPLIB_SSL_ENABLED
  12184. SSLClient cli_;
  12185. SSLServer svr_;
  12186. #else
  12187. Client cli_;
  12188. Server svr_;
  12189. #endif
  12190. thread t_;
  12191. };
  12192. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12193. // Test chunked encoding with payload within 10MB limit
  12194. std::string medium_payload(5 * 1024 * 1024,
  12195. 'A'); // 5MB payload, within 10MB limit
  12196. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12198. EXPECT_EQ(StatusCode::OK_200, res->status);
  12199. }
  12200. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12201. // Test chunked encoding with payload exceeding 10MB limit
  12202. std::string large_payload(12 * 1024 * 1024,
  12203. 'B'); // 12MB payload, exceeds 10MB limit
  12204. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12205. // Server may either return 413 or close the connection
  12206. if (res) {
  12207. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12208. } else {
  12209. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12210. }
  12211. }
  12212. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12213. // Test request without Content-Length header within 10MB limit
  12214. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12215. "Host: " +
  12216. std::string(HOST) + ":" +
  12217. std::to_string(PORT) +
  12218. "\r\n"
  12219. "Connection: close\r\n"
  12220. "\r\n";
  12221. // Add 1MB payload (within 10MB limit)
  12222. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12223. request_without_content_length += medium_payload;
  12224. std::string response;
  12225. bool result = send_request(5, request_without_content_length, &response);
  12226. if (result) {
  12227. // Should get a proper HTTP response for payloads within limit
  12228. if (response.length() > 10) {
  12229. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12230. "10MB limit";
  12231. } else {
  12232. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12233. "Content-Length)";
  12234. }
  12235. } else {
  12236. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12237. }
  12238. }
  12239. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12240. // Test request without Content-Length header exceeding 10MB limit
  12241. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12242. "Host: " +
  12243. std::string(HOST) + ":" +
  12244. std::to_string(PORT) +
  12245. "\r\n"
  12246. "Connection: close\r\n"
  12247. "\r\n";
  12248. // Add 12MB payload (exceeds 10MB limit)
  12249. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12250. request_without_content_length += large_payload;
  12251. std::string response;
  12252. bool result = send_request(10, request_without_content_length, &response);
  12253. if (!result) {
  12254. // Server should close connection due to payload limit
  12255. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12256. "(connection closed)";
  12257. } else {
  12258. // Check for error response
  12259. if (response.length() <= 10) {
  12260. SUCCEED()
  12261. << "Server closed connection for 12MB request exceeding 10MB limit";
  12262. } else {
  12263. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12264. response.find("Payload Too Large") != std::string::npos ||
  12265. response.find("400") != std::string::npos);
  12266. }
  12267. }
  12268. }
  12269. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12270. Server svr;
  12271. svr.Get("/", [](const Request &, Response &res) {
  12272. // Claims the most the client accepts, far more than it sends, then drops
  12273. // the connection.
  12274. res.set_content_provider(std::string().max_size(), "text/plain",
  12275. [](size_t, size_t, DataSink &sink) {
  12276. sink.write("abc", 3);
  12277. return false;
  12278. });
  12279. });
  12280. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12281. auto se = detail::scope_exit([&] {
  12282. svr.stop();
  12283. thread.join();
  12284. ASSERT_FALSE(svr.is_running());
  12285. });
  12286. svr.wait_until_ready();
  12287. Client cli(HOST, PORT);
  12288. cli.set_payload_max_length(0);
  12289. EXPECT_FALSE(cli.Get("/"));
  12290. }
  12291. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12292. // Stream API does, not as a plain read failure
  12293. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12294. Server svr;
  12295. svr.Get("/big", [](const Request &, Response &res) {
  12296. res.set_content(std::string(100000, 'b'), "text/plain");
  12297. });
  12298. auto port = svr.bind_to_any_port(HOST);
  12299. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12300. auto se = detail::scope_exit([&] {
  12301. svr.stop();
  12302. thread.join();
  12303. });
  12304. svr.wait_until_ready();
  12305. Client cli(HOST, port);
  12306. cli.set_payload_max_length(1000);
  12307. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12308. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12309. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12310. [](const char *, size_t) { return true; });
  12311. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12312. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12313. // Small on the wire, over the limit once decompressed
  12314. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12315. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12316. #endif
  12317. }
  12318. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12319. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12320. // path.
  12321. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12322. Server svr;
  12323. const size_t LIMIT = 64 * 1024; // 64KB
  12324. svr.set_payload_max_length(LIMIT);
  12325. size_t total = 0;
  12326. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12327. const ContentReader &content_reader) {
  12328. content_reader([&](const char * /*data*/, size_t len) {
  12329. total += len;
  12330. return true;
  12331. });
  12332. res.status = 200;
  12333. res.set_content("stream_ok", "text/plain");
  12334. });
  12335. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12336. auto se = detail::scope_exit([&] {
  12337. svr.stop();
  12338. thread.join();
  12339. ASSERT_FALSE(svr.is_running());
  12340. });
  12341. svr.wait_until_ready();
  12342. // Prepare 256KB raw data and gzip-compress it
  12343. std::string raw(256 * 1024, 'A');
  12344. std::string gz;
  12345. {
  12346. z_stream zs{};
  12347. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12348. Z_DEFAULT_STRATEGY);
  12349. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12350. zs.avail_in = static_cast<uInt>(raw.size());
  12351. char outbuf[4096];
  12352. int ret;
  12353. do {
  12354. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12355. zs.avail_out = sizeof(outbuf);
  12356. ret = deflate(&zs, Z_FINISH);
  12357. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12358. } while (ret != Z_STREAM_END);
  12359. deflateEnd(&zs);
  12360. }
  12361. Client cli(HOST, PORT);
  12362. cli.set_connection_timeout(std::chrono::seconds(5));
  12363. Headers headers = {{"Content-Encoding", "gzip"}};
  12364. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12365. "application/octet-stream");
  12366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12367. // Server must reject oversized decompressed payloads with 413.
  12368. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12369. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12370. EXPECT_LE(total, LIMIT);
  12371. }
  12372. #ifndef CPPHTTPLIB_SSL_ENABLED
  12373. // For a request with neither Content-Length nor Transfer-Encoding, the
  12374. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12375. // compressed wire bytes straight to the ContentReader without ever routing
  12376. // them through the decompressor, so payload_max_length_ only bounded the
  12377. // compressed size on the wire, not the decompressed size.
  12378. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12379. Server svr;
  12380. const size_t LIMIT = 64 * 1024; // 64KB
  12381. svr.set_payload_max_length(LIMIT);
  12382. size_t total = 0;
  12383. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12384. const ContentReader &content_reader) {
  12385. content_reader([&](const char * /*data*/, size_t len) {
  12386. total += len;
  12387. return true;
  12388. });
  12389. res.status = 200;
  12390. res.set_content("stream_ok", "text/plain");
  12391. });
  12392. auto port = svr.bind_to_any_port(HOST);
  12393. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12394. auto se = detail::scope_exit([&] {
  12395. svr.stop();
  12396. thread.join();
  12397. ASSERT_FALSE(svr.is_running());
  12398. });
  12399. svr.wait_until_ready();
  12400. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12401. // StreamingGzipDecompression test above.
  12402. std::string raw(256 * 1024, 'A');
  12403. std::string gz;
  12404. {
  12405. httplib::detail::gzip_compressor compressor;
  12406. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12407. [&](const char *chunk, size_t len) {
  12408. gz.append(chunk, len);
  12409. return true;
  12410. });
  12411. ASSERT_TRUE(result);
  12412. }
  12413. // Send the gzip body over raw TCP with neither Content-Length nor
  12414. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12415. // kicks in.
  12416. std::string req = "POST /stream HTTP/1.1\r\n"
  12417. "Host: " +
  12418. std::string(HOST) + ":" + std::to_string(port) +
  12419. "\r\n"
  12420. "Content-Encoding: gzip\r\n"
  12421. "Connection: close\r\n"
  12422. "\r\n" +
  12423. gz;
  12424. std::string response;
  12425. ASSERT_TRUE(send_request(5, req, &response, port));
  12426. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12427. EXPECT_LE(total, LIMIT);
  12428. }
  12429. #endif
  12430. #endif
  12431. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12432. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12433. // the payload must be passed through untouched instead of being rejected.
  12434. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12435. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12436. Server svr;
  12437. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12438. res.set_content(body, "image/jpeg");
  12439. res.set_header("Content-Encoding", "UTF-8");
  12440. });
  12441. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12442. res.set_content(body, "image/jpeg");
  12443. res.set_header("Content-Encoding", "identity");
  12444. });
  12445. svr.Post("/echo", [](const Request &req, Response &res) {
  12446. res.set_content(req.body, "image/jpeg");
  12447. });
  12448. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12449. auto se = detail::scope_exit([&] {
  12450. svr.stop();
  12451. t.join();
  12452. ASSERT_FALSE(svr.is_running());
  12453. });
  12454. svr.wait_until_ready();
  12455. Client cli(HOST, PORT);
  12456. {
  12457. auto res = cli.Get("/image");
  12458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12459. EXPECT_EQ(StatusCode::OK_200, res->status);
  12460. EXPECT_EQ(body, res->body);
  12461. }
  12462. {
  12463. auto res = cli.Get("/identity");
  12464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12465. EXPECT_EQ(StatusCode::OK_200, res->status);
  12466. EXPECT_EQ(body, res->body);
  12467. }
  12468. {
  12469. // The same applies to a request body reaching the server.
  12470. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12471. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12473. EXPECT_EQ(StatusCode::OK_200, res->status);
  12474. EXPECT_EQ(body, res->body);
  12475. }
  12476. }
  12477. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12478. // gzip-encoded response even when the build has no zlib support.
  12479. static const char GZIPPED_HELLO_WORLD[] = {
  12480. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12481. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12482. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12483. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12484. // A content coding is a whole token, not something the field value merely
  12485. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12486. // as "fibre" look like Brotli, and turned a multi-coding value like
  12487. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12488. // it was never meant to see.
  12489. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12490. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12491. Server svr;
  12492. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12493. res.set_content(body, "image/jpeg");
  12494. res.set_header("Content-Encoding", "fibre");
  12495. });
  12496. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12497. res.set_content(body, "image/jpeg");
  12498. res.set_header("Content-Encoding", "gzip, br");
  12499. });
  12500. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12501. res.set_content(body, "image/jpeg");
  12502. res.set_header("Content-Encoding", "x-zstd-ish");
  12503. });
  12504. auto port = svr.bind_to_any_port(HOST);
  12505. thread t = thread([&]() { svr.listen_after_bind(); });
  12506. auto se = detail::scope_exit([&] {
  12507. svr.stop();
  12508. t.join();
  12509. ASSERT_FALSE(svr.is_running());
  12510. });
  12511. svr.wait_until_ready();
  12512. Client cli(HOST, port);
  12513. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12514. auto res = cli.Get(path);
  12515. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12516. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12517. // Not a coding we recognize, so the payload comes back untouched
  12518. EXPECT_EQ(body, res->body) << path;
  12519. }
  12520. }
  12521. // A content coding cpp-httplib recognizes but was not built with must be
  12522. // reported as such. Handing the still-compressed payload back to the caller
  12523. // would silently corrupt it.
  12524. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12525. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12526. Server svr;
  12527. // "image/jpeg" keeps the server from applying a content coding of its own,
  12528. // so the hand-crafted Content-Encoding below survives.
  12529. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12530. res.set_content(gzipped, "image/jpeg");
  12531. res.set_header("Content-Encoding", "gzip");
  12532. });
  12533. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12534. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12535. res.set_content(gzipped, "image/jpeg");
  12536. res.set_header("Content-Encoding", "GZIP");
  12537. });
  12538. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12539. auto se = detail::scope_exit([&] {
  12540. svr.stop();
  12541. t.join();
  12542. ASSERT_FALSE(svr.is_running());
  12543. });
  12544. svr.wait_until_ready();
  12545. Client cli(HOST, PORT);
  12546. {
  12547. auto res = cli.Get("/gzipped");
  12548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12550. EXPECT_EQ("Hello World!", res->body);
  12551. #else
  12552. ASSERT_FALSE(res);
  12553. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12554. #endif
  12555. }
  12556. {
  12557. // open_stream() must behave the same way.
  12558. auto handle = cli.open_stream("GET", "/gzipped");
  12559. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12560. ASSERT_TRUE(handle.is_valid());
  12561. std::string received;
  12562. char buf[256];
  12563. ssize_t n;
  12564. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12565. received.append(buf, static_cast<size_t>(n));
  12566. }
  12567. EXPECT_EQ("Hello World!", received);
  12568. #else
  12569. EXPECT_FALSE(handle.is_valid());
  12570. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12571. #endif
  12572. }
  12573. {
  12574. // A differently-cased coding must not be mistaken for an unknown one, or
  12575. // the body would be handed back still compressed.
  12576. auto res = cli.Get("/gzipped-uppercase");
  12577. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12579. EXPECT_EQ("Hello World!", res->body);
  12580. #else
  12581. ASSERT_FALSE(res);
  12582. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12583. #endif
  12584. }
  12585. }
  12586. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12587. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12588. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12589. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12590. // body a second time and appending a second Content-Encoding field line, so
  12591. // clients that decode one coding per listed value handed back raw gzip bytes.
  12592. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12593. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12594. Server svr;
  12595. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12596. // keeps the server from applying a coding of its own.
  12597. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12598. res.set_content(gzipped, "text/plain");
  12599. res.set_header("Content-Encoding", "gzip");
  12600. });
  12601. auto port = svr.bind_to_any_port(HOST);
  12602. thread t = thread([&]() { svr.listen_after_bind(); });
  12603. auto se = detail::scope_exit([&] {
  12604. svr.stop();
  12605. t.join();
  12606. ASSERT_FALSE(svr.is_running());
  12607. });
  12608. svr.wait_until_ready();
  12609. Client cli(HOST, port);
  12610. Headers headers = {{"Accept-Encoding", "gzip"}};
  12611. auto res = cli.Get("/pre-gzipped", headers);
  12612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12613. EXPECT_EQ(StatusCode::OK_200, res->status);
  12614. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12615. EXPECT_EQ("Hello World!", res->body);
  12616. }
  12617. // set_compress(false) sends every handler response as it is, buffered or
  12618. // streamed
  12619. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12620. const std::string text(1000, 'a');
  12621. Server svr;
  12622. svr.set_compress(false);
  12623. svr.Get("/buffered", [&](const Request &, Response &res) {
  12624. res.set_content(text, "text/plain");
  12625. });
  12626. svr.Get("/streamed", [&](const Request &, Response &res) {
  12627. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12628. sink.write(text.data(), text.size());
  12629. sink.done();
  12630. return true;
  12631. });
  12632. });
  12633. auto port = svr.bind_to_any_port(HOST);
  12634. ASSERT_LT(0, port);
  12635. thread t = thread([&] { svr.listen_after_bind(); });
  12636. auto se = detail::scope_exit([&] {
  12637. svr.stop();
  12638. t.join();
  12639. ASSERT_FALSE(svr.is_running());
  12640. });
  12641. svr.wait_until_ready();
  12642. Client cli(HOST, port);
  12643. cli.set_decompress(false);
  12644. for (auto path : {"/buffered", "/streamed"}) {
  12645. SCOPED_TRACE(path);
  12646. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12648. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12649. EXPECT_EQ(text, res->body);
  12650. }
  12651. }
  12652. // A chunked provider settles its coding where the headers are written and
  12653. // reuses it at write time. Both ends of that have to hold: a handler's own
  12654. // Content-Encoding suppresses the coding, and a response without one is still
  12655. // compressed as it always was.
  12656. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12657. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12658. const std::string plain = "Hello World! Hello World! Hello World!";
  12659. Server svr;
  12660. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12661. res.set_header("Content-Encoding", "gzip");
  12662. res.set_chunked_content_provider(
  12663. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12664. sink.write(gzipped.data(), gzipped.size());
  12665. sink.done();
  12666. return true;
  12667. });
  12668. });
  12669. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12670. res.set_chunked_content_provider(
  12671. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12672. sink.write(plain.data(), plain.size());
  12673. sink.done();
  12674. return true;
  12675. });
  12676. });
  12677. auto port = svr.bind_to_any_port(HOST);
  12678. thread t = thread([&]() { svr.listen_after_bind(); });
  12679. auto se = detail::scope_exit([&] {
  12680. svr.stop();
  12681. t.join();
  12682. ASSERT_FALSE(svr.is_running());
  12683. });
  12684. svr.wait_until_ready();
  12685. Client cli(HOST, port);
  12686. Headers headers = {{"Accept-Encoding", "gzip"}};
  12687. {
  12688. auto res = cli.Get("/pre-gzipped", headers);
  12689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12690. EXPECT_EQ(StatusCode::OK_200, res->status);
  12691. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12692. EXPECT_EQ("Hello World!", res->body);
  12693. }
  12694. {
  12695. auto res = cli.Get("/negotiated", headers);
  12696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12697. EXPECT_EQ(StatusCode::OK_200, res->status);
  12698. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12699. EXPECT_EQ(plain, res->body);
  12700. }
  12701. }
  12702. #endif
  12703. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12704. // the same message as the comma-joined one, so both have to be read the same
  12705. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12706. // single gzip coding, and a body the sender says was encoded twice was handed
  12707. // back after one pass, still compressed but presented as decoded.
  12708. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12709. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12710. Server svr;
  12711. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12712. res.set_content(body, "image/jpeg");
  12713. res.headers.emplace("Content-Encoding", "gzip");
  12714. res.headers.emplace("Content-Encoding", "gzip");
  12715. });
  12716. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12717. res.set_content(body, "image/jpeg");
  12718. res.set_header("Content-Encoding", "gzip, gzip");
  12719. });
  12720. auto port = svr.bind_to_any_port(HOST);
  12721. thread t = thread([&]() { svr.listen_after_bind(); });
  12722. auto se = detail::scope_exit([&] {
  12723. svr.stop();
  12724. t.join();
  12725. ASSERT_FALSE(svr.is_running());
  12726. });
  12727. svr.wait_until_ready();
  12728. Client cli(HOST, port);
  12729. // Two codings is not something cpp-httplib decodes, so both representations
  12730. // take the pass-through path rather than one of them being gunzipped once.
  12731. for (const char *path : {"/split", "/joined"}) {
  12732. auto res = cli.Get(path);
  12733. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12734. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12735. EXPECT_EQ(body, res->body) << path;
  12736. }
  12737. }
  12738. // Regression test for DoS vulnerability: a malicious server sending a response
  12739. // without Content-Length header must not cause unbounded memory consumption on
  12740. // the client side. The client should stop reading after a reasonable limit,
  12741. // similar to the server-side set_payload_max_length protection.
  12742. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12743. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12744. #ifndef _WIN32
  12745. signal(SIGPIPE, SIG_IGN);
  12746. #endif
  12747. auto server_thread = std::thread([] {
  12748. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12749. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12750. default_socket_options(srv);
  12751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12752. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12753. sockaddr_in addr{};
  12754. addr.sin_family = AF_INET;
  12755. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12756. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12757. int opt = 1;
  12758. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12759. #ifdef _WIN32
  12760. reinterpret_cast<const char *>(&opt),
  12761. #else
  12762. &opt,
  12763. #endif
  12764. sizeof(opt));
  12765. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12766. ::listen(srv, 1);
  12767. sockaddr_in cli_addr{};
  12768. socklen_t cli_len = sizeof(cli_addr);
  12769. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12770. if (cli != INVALID_SOCKET) {
  12771. char buf[4096];
  12772. ::recv(cli, buf, sizeof(buf), 0);
  12773. // Malicious response: no Content-Length, no chunked encoding
  12774. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12775. "Connection: close\r\n"
  12776. "\r\n";
  12777. ::send(cli,
  12778. #ifdef _WIN32
  12779. static_cast<const char *>(response_header.c_str()),
  12780. static_cast<int>(response_header.size()),
  12781. #else
  12782. response_header.c_str(), response_header.size(),
  12783. #endif
  12784. 0);
  12785. // Send 10MB of data
  12786. std::string chunk(64 * 1024, 'A');
  12787. size_t total_sent = 0;
  12788. while (total_sent < MALICIOUS_DATA_SIZE) {
  12789. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12790. auto sent = ::send(cli,
  12791. #ifdef _WIN32
  12792. static_cast<const char *>(chunk.c_str()),
  12793. static_cast<int>(to_send),
  12794. #else
  12795. chunk.c_str(), to_send,
  12796. #endif
  12797. 0);
  12798. if (sent <= 0) break;
  12799. total_sent += static_cast<size_t>(sent);
  12800. }
  12801. detail::close_socket(cli);
  12802. }
  12803. detail::close_socket(srv);
  12804. });
  12805. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12806. size_t total_read = 0;
  12807. {
  12808. Client cli("127.0.0.1", PORT + 2);
  12809. cli.set_read_timeout(5, 0);
  12810. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12811. auto stream = cli.open_stream("GET", "/malicious");
  12812. ASSERT_TRUE(stream.is_valid());
  12813. char buffer[64 * 1024];
  12814. ssize_t n;
  12815. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12816. total_read += static_cast<size_t>(n);
  12817. }
  12818. } // StreamHandle and Client destroyed here, closing the socket
  12819. server_thread.join();
  12820. // With set_payload_max_length, the client must stop reading before consuming
  12821. // all 10MB. The read loop should be cut off at or near the configured limit.
  12822. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12823. << "Client read " << total_read << " bytes, exceeding the configured "
  12824. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12825. }
  12826. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12827. // the entire response body without truncation.
  12828. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12829. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12830. #ifndef _WIN32
  12831. signal(SIGPIPE, SIG_IGN);
  12832. #endif
  12833. auto server_thread = std::thread([] {
  12834. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12835. default_socket_options(srv);
  12836. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12837. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12838. sockaddr_in addr{};
  12839. addr.sin_family = AF_INET;
  12840. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12841. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12842. int opt = 1;
  12843. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12844. #ifdef _WIN32
  12845. reinterpret_cast<const char *>(&opt),
  12846. #else
  12847. &opt,
  12848. #endif
  12849. sizeof(opt));
  12850. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12851. ::listen(srv, 1);
  12852. sockaddr_in cli_addr{};
  12853. socklen_t cli_len = sizeof(cli_addr);
  12854. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12855. if (cli != INVALID_SOCKET) {
  12856. char buf[4096];
  12857. ::recv(cli, buf, sizeof(buf), 0);
  12858. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12859. "Connection: close\r\n"
  12860. "\r\n";
  12861. ::send(cli,
  12862. #ifdef _WIN32
  12863. static_cast<const char *>(response_header.c_str()),
  12864. static_cast<int>(response_header.size()),
  12865. #else
  12866. response_header.c_str(), response_header.size(),
  12867. #endif
  12868. 0);
  12869. std::string chunk(64 * 1024, 'A');
  12870. size_t total_sent = 0;
  12871. while (total_sent < DATA_SIZE) {
  12872. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12873. auto sent = ::send(cli,
  12874. #ifdef _WIN32
  12875. static_cast<const char *>(chunk.c_str()),
  12876. static_cast<int>(to_send),
  12877. #else
  12878. chunk.c_str(), to_send,
  12879. #endif
  12880. 0);
  12881. if (sent <= 0) break;
  12882. total_sent += static_cast<size_t>(sent);
  12883. }
  12884. #ifdef _WIN32
  12885. ::shutdown(cli, SD_SEND);
  12886. #else
  12887. ::shutdown(cli, SHUT_WR);
  12888. #endif
  12889. // Drain until the client closes its end, ensuring all data is delivered
  12890. char drain[1024];
  12891. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12892. detail::close_socket(cli);
  12893. }
  12894. detail::close_socket(srv);
  12895. });
  12896. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12897. size_t total_read = 0;
  12898. {
  12899. Client cli("127.0.0.1", PORT + 2);
  12900. cli.set_read_timeout(5, 0);
  12901. cli.set_payload_max_length(0); // 0 means no limit
  12902. auto stream = cli.open_stream("GET", "/data");
  12903. ASSERT_TRUE(stream.is_valid());
  12904. char buffer[64 * 1024];
  12905. ssize_t n;
  12906. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12907. total_read += static_cast<size_t>(n);
  12908. }
  12909. }
  12910. server_thread.join();
  12911. EXPECT_EQ(total_read, DATA_SIZE)
  12912. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12913. << " bytes without truncation, but only read " << total_read << " bytes.";
  12914. }
  12915. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12916. // enormous Content-Length must not cause the client to pre-allocate a huge
  12917. // response body buffer. The reservation is capped at payload_max_length_, and
  12918. // the read itself fails when the body exceeds the limit.
  12919. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12920. #ifndef _WIN32
  12921. signal(SIGPIPE, SIG_IGN);
  12922. #endif
  12923. auto server_thread = std::thread([] {
  12924. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12925. default_socket_options(srv);
  12926. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12927. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12928. sockaddr_in addr{};
  12929. addr.sin_family = AF_INET;
  12930. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12931. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12932. int opt = 1;
  12933. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12934. #ifdef _WIN32
  12935. reinterpret_cast<const char *>(&opt),
  12936. #else
  12937. &opt,
  12938. #endif
  12939. sizeof(opt));
  12940. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12941. ::listen(srv, 1);
  12942. sockaddr_in cli_addr{};
  12943. socklen_t cli_len = sizeof(cli_addr);
  12944. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12945. if (cli != INVALID_SOCKET) {
  12946. char buf[4096];
  12947. ::recv(cli, buf, sizeof(buf), 0);
  12948. // Malicious response: claim a 20GB body but send only a tiny payload.
  12949. std::string response = "HTTP/1.1 200 OK\r\n"
  12950. "Content-Length: 20000000000\r\n"
  12951. "\r\n"
  12952. "abc";
  12953. ::send(cli,
  12954. #ifdef _WIN32
  12955. static_cast<const char *>(response.c_str()),
  12956. static_cast<int>(response.size()),
  12957. #else
  12958. response.c_str(), response.size(),
  12959. #endif
  12960. 0);
  12961. detail::close_socket(cli);
  12962. }
  12963. detail::close_socket(srv);
  12964. });
  12965. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12966. {
  12967. Client cli("127.0.0.1", PORT + 2);
  12968. cli.set_read_timeout(5, 0);
  12969. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12970. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12971. // (server claims more bytes than payload_max_length permits), but it must
  12972. // not exhaust memory before getting there.
  12973. auto res = cli.Get("/malicious");
  12974. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12975. }
  12976. server_thread.join();
  12977. }
  12978. // Verify that content_receiver bypasses the default payload_max_length,
  12979. // allowing streaming downloads larger than 100MB without requiring an explicit
  12980. // set_payload_max_length call.
  12981. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12982. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12983. #ifndef _WIN32
  12984. signal(SIGPIPE, SIG_IGN);
  12985. #endif
  12986. auto server_thread = std::thread([] {
  12987. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12988. default_socket_options(srv);
  12989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12990. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12991. sockaddr_in addr{};
  12992. addr.sin_family = AF_INET;
  12993. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12994. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12995. int opt = 1;
  12996. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12997. #ifdef _WIN32
  12998. reinterpret_cast<const char *>(&opt),
  12999. #else
  13000. &opt,
  13001. #endif
  13002. sizeof(opt));
  13003. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13004. ::listen(srv, 1);
  13005. sockaddr_in cli_addr{};
  13006. socklen_t cli_len = sizeof(cli_addr);
  13007. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13008. if (cli != INVALID_SOCKET) {
  13009. char buf[4096];
  13010. ::recv(cli, buf, sizeof(buf), 0);
  13011. // Response with Content-Length larger than default 100MB limit
  13012. auto content_length = std::to_string(DATA_SIZE);
  13013. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13014. "Content-Length: " +
  13015. content_length +
  13016. "\r\n"
  13017. "Connection: close\r\n"
  13018. "\r\n";
  13019. ::send(cli,
  13020. #ifdef _WIN32
  13021. static_cast<const char *>(response_header.c_str()),
  13022. static_cast<int>(response_header.size()),
  13023. #else
  13024. response_header.c_str(), response_header.size(),
  13025. #endif
  13026. 0);
  13027. std::string chunk(64 * 1024, 'A');
  13028. size_t total_sent = 0;
  13029. while (total_sent < DATA_SIZE) {
  13030. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13031. auto sent = ::send(cli,
  13032. #ifdef _WIN32
  13033. static_cast<const char *>(chunk.c_str()),
  13034. static_cast<int>(to_send),
  13035. #else
  13036. chunk.c_str(), to_send,
  13037. #endif
  13038. 0);
  13039. if (sent <= 0) break;
  13040. total_sent += static_cast<size_t>(sent);
  13041. }
  13042. detail::close_socket(cli);
  13043. }
  13044. detail::close_socket(srv);
  13045. });
  13046. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13047. size_t total_received = 0;
  13048. {
  13049. Client cli("127.0.0.1", PORT + 2);
  13050. cli.set_read_timeout(10, 0);
  13051. // Do NOT call set_payload_max_length — use the default 100MB limit
  13052. auto res =
  13053. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13054. total_received += data_length;
  13055. return true;
  13056. });
  13057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13058. EXPECT_EQ(StatusCode::OK_200, res->status);
  13059. }
  13060. server_thread.join();
  13061. EXPECT_EQ(total_received, DATA_SIZE)
  13062. << "With content_receiver, the client should read all " << DATA_SIZE
  13063. << " bytes despite the default 100MB payload_max_length, but only read "
  13064. << total_received << " bytes.";
  13065. }
  13066. // Verify that an explicit set_payload_max_length smaller than the response is
  13067. // enforced even when a content_receiver is used.
  13068. TEST(ClientVulnerabilityTest,
  13069. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13070. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13071. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13072. #ifndef _WIN32
  13073. signal(SIGPIPE, SIG_IGN);
  13074. #endif
  13075. auto server_thread = std::thread([] {
  13076. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13077. default_socket_options(srv);
  13078. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13079. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13080. sockaddr_in addr{};
  13081. addr.sin_family = AF_INET;
  13082. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13083. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13084. int opt = 1;
  13085. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13086. #ifdef _WIN32
  13087. reinterpret_cast<const char *>(&opt),
  13088. #else
  13089. &opt,
  13090. #endif
  13091. sizeof(opt));
  13092. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13093. ::listen(srv, 1);
  13094. sockaddr_in cli_addr{};
  13095. socklen_t cli_len = sizeof(cli_addr);
  13096. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13097. if (cli != INVALID_SOCKET) {
  13098. char buf[4096];
  13099. ::recv(cli, buf, sizeof(buf), 0);
  13100. auto content_length = std::to_string(DATA_SIZE);
  13101. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13102. "Content-Length: " +
  13103. content_length +
  13104. "\r\n"
  13105. "Connection: close\r\n"
  13106. "\r\n";
  13107. ::send(cli,
  13108. #ifdef _WIN32
  13109. static_cast<const char *>(response_header.c_str()),
  13110. static_cast<int>(response_header.size()),
  13111. #else
  13112. response_header.c_str(), response_header.size(),
  13113. #endif
  13114. 0);
  13115. std::string chunk(64 * 1024, 'A');
  13116. size_t total_sent = 0;
  13117. while (total_sent < DATA_SIZE) {
  13118. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13119. auto sent = ::send(cli,
  13120. #ifdef _WIN32
  13121. static_cast<const char *>(chunk.c_str()),
  13122. static_cast<int>(to_send),
  13123. #else
  13124. chunk.c_str(), to_send,
  13125. #endif
  13126. 0);
  13127. if (sent <= 0) break;
  13128. total_sent += static_cast<size_t>(sent);
  13129. }
  13130. detail::close_socket(cli);
  13131. }
  13132. detail::close_socket(srv);
  13133. });
  13134. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13135. size_t total_received = 0;
  13136. {
  13137. Client cli("127.0.0.1", PORT + 2);
  13138. cli.set_read_timeout(10, 0);
  13139. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13140. auto res =
  13141. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13142. total_received += data_length;
  13143. return true;
  13144. });
  13145. // Should fail because 200MB exceeds the explicit 150MB limit
  13146. EXPECT_FALSE(res);
  13147. }
  13148. server_thread.join();
  13149. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13150. << "Client with content_receiver should respect the explicit "
  13151. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13152. << total_received << " bytes.";
  13153. }
  13154. // Verify that an explicit set_payload_max_length larger than the response
  13155. // allows the content_receiver to read all data successfully.
  13156. TEST(ClientVulnerabilityTest,
  13157. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13158. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13159. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13160. #ifndef _WIN32
  13161. signal(SIGPIPE, SIG_IGN);
  13162. #endif
  13163. auto server_thread = std::thread([] {
  13164. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13165. default_socket_options(srv);
  13166. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13167. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13168. sockaddr_in addr{};
  13169. addr.sin_family = AF_INET;
  13170. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13171. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13172. int opt = 1;
  13173. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13174. #ifdef _WIN32
  13175. reinterpret_cast<const char *>(&opt),
  13176. #else
  13177. &opt,
  13178. #endif
  13179. sizeof(opt));
  13180. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13181. ::listen(srv, 1);
  13182. sockaddr_in cli_addr{};
  13183. socklen_t cli_len = sizeof(cli_addr);
  13184. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13185. if (cli != INVALID_SOCKET) {
  13186. char buf[4096];
  13187. ::recv(cli, buf, sizeof(buf), 0);
  13188. auto content_length = std::to_string(DATA_SIZE);
  13189. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13190. "Content-Length: " +
  13191. content_length +
  13192. "\r\n"
  13193. "Connection: close\r\n"
  13194. "\r\n";
  13195. ::send(cli,
  13196. #ifdef _WIN32
  13197. static_cast<const char *>(response_header.c_str()),
  13198. static_cast<int>(response_header.size()),
  13199. #else
  13200. response_header.c_str(), response_header.size(),
  13201. #endif
  13202. 0);
  13203. std::string chunk(64 * 1024, 'A');
  13204. size_t total_sent = 0;
  13205. while (total_sent < DATA_SIZE) {
  13206. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13207. auto sent = ::send(cli,
  13208. #ifdef _WIN32
  13209. static_cast<const char *>(chunk.c_str()),
  13210. static_cast<int>(to_send),
  13211. #else
  13212. chunk.c_str(), to_send,
  13213. #endif
  13214. 0);
  13215. if (sent <= 0) break;
  13216. total_sent += static_cast<size_t>(sent);
  13217. }
  13218. #ifdef _WIN32
  13219. ::shutdown(cli, SD_SEND);
  13220. #else
  13221. ::shutdown(cli, SHUT_WR);
  13222. #endif
  13223. char drain[1024];
  13224. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13225. detail::close_socket(cli);
  13226. }
  13227. detail::close_socket(srv);
  13228. });
  13229. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13230. size_t total_received = 0;
  13231. {
  13232. Client cli("127.0.0.1", PORT + 2);
  13233. cli.set_read_timeout(10, 0);
  13234. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13235. auto res =
  13236. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13237. total_received += data_length;
  13238. return true;
  13239. });
  13240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13241. EXPECT_EQ(StatusCode::OK_200, res->status);
  13242. }
  13243. server_thread.join();
  13244. EXPECT_EQ(total_received, DATA_SIZE)
  13245. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13246. << " bytes (larger than " << DATA_SIZE
  13247. << " bytes response), content_receiver should read all data, but only "
  13248. "read "
  13249. << total_received << " bytes.";
  13250. }
  13251. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13252. // Regression test for "zip bomb" attack on the client side: a malicious server
  13253. // sends a small gzip-compressed response that decompresses to a huge payload.
  13254. // The client must enforce payload_max_length on the decompressed size.
  13255. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13256. constexpr size_t DECOMPRESSED_SIZE =
  13257. 10 * 1024 * 1024; // 10MB after decompression
  13258. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13259. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13260. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13261. std::string compressed;
  13262. {
  13263. httplib::detail::gzip_compressor compressor;
  13264. bool ok =
  13265. compressor.compress(uncompressed.data(), uncompressed.size(),
  13266. /*last=*/true, [&](const char *buf, size_t len) {
  13267. compressed.append(buf, len);
  13268. return true;
  13269. });
  13270. ASSERT_TRUE(ok);
  13271. }
  13272. // Sanity: compressed data should be much smaller than the decompressed size
  13273. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13274. #ifndef _WIN32
  13275. signal(SIGPIPE, SIG_IGN);
  13276. #endif
  13277. // Set up the listening socket in the main thread so the server is guaranteed
  13278. // to be ready before the client connects (eliminates race condition).
  13279. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13280. default_socket_options(srv);
  13281. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13282. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13283. sockaddr_in addr{};
  13284. addr.sin_family = AF_INET;
  13285. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13286. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13287. int opt = 1;
  13288. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13289. #ifdef _WIN32
  13290. reinterpret_cast<const char *>(&opt),
  13291. #else
  13292. &opt,
  13293. #endif
  13294. sizeof(opt));
  13295. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13296. ASSERT_EQ(0, ::listen(srv, 1));
  13297. auto server_thread = std::thread([&compressed, srv] {
  13298. sockaddr_in cli_addr{};
  13299. socklen_t cli_len = sizeof(cli_addr);
  13300. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13301. if (cli != INVALID_SOCKET) {
  13302. // Read the full HTTP request (until \r\n\r\n)
  13303. char buf[4096];
  13304. size_t total = 0;
  13305. while (total < sizeof(buf)) {
  13306. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13307. if (n <= 0) break;
  13308. total += static_cast<size_t>(n);
  13309. // Check for end of headers
  13310. if (total >= 4) {
  13311. std::string req(buf, total);
  13312. if (req.find("\r\n\r\n") != std::string::npos) break;
  13313. }
  13314. }
  13315. // Malicious response: gzip-compressed body, no Content-Length
  13316. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13317. "Content-Encoding: gzip\r\n"
  13318. "Connection: close\r\n"
  13319. "\r\n";
  13320. ::send(cli,
  13321. #ifdef _WIN32
  13322. static_cast<const char *>(response_header.c_str()),
  13323. static_cast<int>(response_header.size()),
  13324. #else
  13325. response_header.c_str(), response_header.size(),
  13326. #endif
  13327. 0);
  13328. // Send the compressed payload (small on the wire, huge when decompressed)
  13329. size_t total_sent = 0;
  13330. while (total_sent < compressed.size()) {
  13331. auto to_send = std::min(compressed.size() - total_sent,
  13332. static_cast<size_t>(64 * 1024));
  13333. auto sent =
  13334. ::send(cli,
  13335. #ifdef _WIN32
  13336. static_cast<const char *>(compressed.c_str() + total_sent),
  13337. static_cast<int>(to_send),
  13338. #else
  13339. compressed.c_str() + total_sent, to_send,
  13340. #endif
  13341. 0);
  13342. if (sent <= 0) break;
  13343. total_sent += static_cast<size_t>(sent);
  13344. }
  13345. detail::close_socket(cli);
  13346. }
  13347. });
  13348. auto se = detail::scope_exit([&] {
  13349. detail::close_socket(srv);
  13350. server_thread.join();
  13351. });
  13352. size_t total_decompressed = 0;
  13353. {
  13354. Client cli("127.0.0.1", PORT + 3);
  13355. cli.set_read_timeout(5, 0);
  13356. cli.set_decompress(true);
  13357. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13358. auto stream = cli.open_stream("GET", "/zipbomb");
  13359. ASSERT_TRUE(stream.is_valid());
  13360. char buffer[64 * 1024];
  13361. ssize_t n;
  13362. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13363. total_decompressed += static_cast<size_t>(n);
  13364. }
  13365. }
  13366. // The decompressed size must be capped by payload_max_length. Without
  13367. // protection, the client would decompress the full 10MB from a tiny
  13368. // compressed payload, enabling a zip bomb DoS attack.
  13369. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13370. << "Client decompressed " << total_decompressed
  13371. << " bytes from a gzip response. The decompressed size should be "
  13372. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13373. }
  13374. #endif
  13375. TEST(HostAndPortPropertiesTest, NoSSL) {
  13376. httplib::Client cli("www.google.com", 1234);
  13377. ASSERT_EQ("www.google.com", cli.host());
  13378. ASSERT_EQ(1234, cli.port());
  13379. }
  13380. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13381. httplib::Client cli("www.google.com:1234");
  13382. ASSERT_EQ("www.google.com", cli.host());
  13383. ASSERT_EQ(1234, cli.port());
  13384. }
  13385. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13386. // Port number that overflows int — should not crash, client becomes invalid
  13387. httplib::Client cli("http://www.google.com:99999999999999999999");
  13388. ASSERT_FALSE(cli.is_valid());
  13389. }
  13390. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13391. // Port 99999 exceeds valid range (1-65535) — should not crash
  13392. httplib::Client cli("http://www.google.com:99999");
  13393. ASSERT_FALSE(cli.is_valid());
  13394. auto res = cli.Get("/");
  13395. EXPECT_FALSE(res);
  13396. EXPECT_EQ(Error::Connection, res.error());
  13397. }
  13398. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13399. httplib::Client cli("http://user:pass@localhost:1234");
  13400. ASSERT_FALSE(cli.is_valid());
  13401. EXPECT_FALSE(cli.Get("/"));
  13402. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13403. }
  13404. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13405. httplib::Client cli("http://www.google.com:80abc");
  13406. ASSERT_FALSE(cli.is_valid());
  13407. }
  13408. #ifdef CPPHTTPLIB_SSL_ENABLED
  13409. TEST(HostAndPortPropertiesTest, SSL) {
  13410. httplib::SSLClient cli("www.google.com");
  13411. ASSERT_EQ("www.google.com", cli.host());
  13412. ASSERT_EQ(443, cli.port());
  13413. }
  13414. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13415. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13416. std::string cert;
  13417. read_file(CA_CERT_FILE, cert);
  13418. httplib::SSLClient httplib_client("www.google.com");
  13419. // Load CA store first time
  13420. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13421. // Load CA store second time (update)
  13422. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13423. // Verify client is still valid and can make connections
  13424. httplib_client.enable_server_certificate_verification(true);
  13425. auto res = httplib_client.Get("/");
  13426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13427. // Google may return 200 or 301 depending on various factors
  13428. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13429. res->status == StatusCode::MovedPermanently_301);
  13430. }
  13431. TEST(SSLClientTest, ServerNameIndication_Online) {
  13432. auto host = "httpbingo.org";
  13433. auto path = std::string{"/get"};
  13434. SSLClient cli(host, 443);
  13435. auto res = cli.Get(path);
  13436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13437. ASSERT_EQ(StatusCode::OK_200, res->status);
  13438. }
  13439. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13440. // Use a site that will cause SSL verification failure due to self-signed cert
  13441. SSLClient cli("self-signed.badssl.com", 443);
  13442. cli.enable_server_certificate_verification(true);
  13443. auto res = cli.Get("/");
  13444. ASSERT_TRUE(!res);
  13445. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13446. // Verify backend error is captured for SSLServerVerification
  13447. // This occurs when certificate verification fails
  13448. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13449. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13450. EXPECT_NE(0UL, res.ssl_backend_error());
  13451. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13452. res.ssl_error());
  13453. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13454. #if !defined(_WIN32) || \
  13455. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13456. // On non-Windows or when Windows Schannel is disabled, the error comes
  13457. // from OpenSSL's verification
  13458. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13459. res.ssl_backend_error());
  13460. #endif
  13461. #endif
  13462. }
  13463. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13464. // Use a site where hostname doesn't match the certificate
  13465. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13466. SSLClient cli("wrong.host.badssl.com", 443);
  13467. cli.enable_server_certificate_verification(true);
  13468. cli.enable_server_hostname_verification(true);
  13469. auto res = cli.Get("/");
  13470. ASSERT_TRUE(!res);
  13471. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13472. // Verify backend error is captured for hostname verification failure
  13473. EXPECT_NE(0UL, res.ssl_backend_error());
  13474. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13475. res.ssl_error());
  13476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13477. #if !defined(_WIN32) || \
  13478. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13479. // On non-Windows or when Windows Schannel is disabled, the error comes
  13480. // from OpenSSL's hostname verification
  13481. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13482. res.ssl_backend_error());
  13483. #endif
  13484. #endif
  13485. }
  13486. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13487. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13488. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13489. SSLClient cli("www.google.com", 443);
  13490. cli.enable_server_certificate_verification(true);
  13491. auto res = cli.Get("/");
  13492. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13493. }
  13494. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13495. SSLClient cli("www.google.com", 443);
  13496. cli.enable_server_certificate_verification(true);
  13497. cli.enable_windows_certificate_verification(false);
  13498. auto res = cli.Get("/");
  13499. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13500. }
  13501. // The server sends an intermediate cross-signed by a root Windows trusts,
  13502. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13503. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13504. SSLClient cli("accounts.spotify.com", 443);
  13505. auto res = cli.Get("/");
  13506. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13507. << " ssl_backend_error=" << res.ssl_backend_error();
  13508. }
  13509. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13510. // policy status, which no backend reports for a self-signed certificate.
  13511. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13512. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13513. ASSERT_TRUE(svr.is_valid());
  13514. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13515. auto se = detail::scope_exit([&] {
  13516. svr.stop();
  13517. t.join();
  13518. ASSERT_FALSE(svr.is_running());
  13519. });
  13520. svr.wait_until_ready();
  13521. SSLClient cli("127.0.0.1", PORT);
  13522. cli.set_connection_timeout(30);
  13523. auto res = cli.Get("/");
  13524. ASSERT_FALSE(res);
  13525. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13526. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13527. }
  13528. #endif
  13529. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13530. Client cli("https://google.com");
  13531. auto res = cli.Get("/");
  13532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13533. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13534. }
  13535. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13536. SSLClient cli("google.com");
  13537. cli.set_ca_cert_path(CA_CERT_FILE);
  13538. auto res = cli.Get("/");
  13539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13540. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13541. }
  13542. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13543. SSLClient cli("google.com");
  13544. cli.enable_server_certificate_verification(true);
  13545. cli.set_ca_cert_path("hello");
  13546. auto res = cli.Get("/");
  13547. ASSERT_TRUE(!res);
  13548. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13549. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13550. // should be set
  13551. EXPECT_EQ(0, res.ssl_error());
  13552. // Verify backend error is captured for SSLLoadingCerts
  13553. // This error occurs when loading CA certificates fails
  13554. EXPECT_NE(0UL, res.ssl_backend_error());
  13555. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13556. // OpenSSL specific error codes:
  13557. // > openssl errstr 0x80000002
  13558. // error:80000002:system library::No such file or directory
  13559. // > openssl errstr 0xA000126
  13560. // error:0A000126:SSL routines::unexpected eof while reading
  13561. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13562. res.ssl_backend_error() == 0xA000126);
  13563. #endif
  13564. }
  13565. TEST(SSLClientTest, ServerCertificateVerification4) {
  13566. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13567. ASSERT_TRUE(svr.is_valid());
  13568. svr.Get("/test", [&](const Request &, Response &res) {
  13569. res.set_content("test", "text/plain");
  13570. svr.stop();
  13571. ASSERT_TRUE(true);
  13572. });
  13573. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13574. auto se = detail::scope_exit([&] {
  13575. t.join();
  13576. ASSERT_FALSE(svr.is_running());
  13577. });
  13578. svr.wait_until_ready();
  13579. SSLClient cli("127.0.0.1", PORT);
  13580. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13581. cli.enable_server_certificate_verification(true);
  13582. cli.set_connection_timeout(30);
  13583. auto res = cli.Get("/test");
  13584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13585. ASSERT_EQ(StatusCode::OK_200, res->status);
  13586. }
  13587. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13588. std::string cert;
  13589. read_file(CA_CERT_FILE, cert);
  13590. SSLClient cli("google.com");
  13591. cli.load_ca_cert_store(cert.data(), cert.size());
  13592. const auto res = cli.Get("/");
  13593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13594. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13595. }
  13596. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13597. // clang-format off
  13598. static constexpr char cert[] =
  13599. "GlobalSign Root CA\n"
  13600. "==================\n"
  13601. "-----BEGIN CERTIFICATE-----\n"
  13602. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13603. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13604. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13605. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13606. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13607. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13608. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13609. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13610. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13611. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13612. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13613. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13614. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13615. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13616. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13617. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13618. "-----END CERTIFICATE-----\n";
  13619. // clang-format on
  13620. SSLClient cli("google.com");
  13621. cli.load_ca_cert_store(cert, sizeof(cert));
  13622. const auto res = cli.Get("/");
  13623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13624. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13625. }
  13626. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13627. SSLClient cli("www.youtube.com");
  13628. cli.set_ca_cert_path(CA_CERT_FILE);
  13629. cli.enable_server_certificate_verification(true);
  13630. cli.set_follow_location(true);
  13631. auto res = cli.Get("/");
  13632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13633. ASSERT_EQ(StatusCode::OK_200, res->status);
  13634. }
  13635. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13636. SSLClient cli("wWw.YouTube.Com");
  13637. cli.set_ca_cert_path(CA_CERT_FILE);
  13638. cli.enable_server_certificate_verification(true);
  13639. cli.enable_server_hostname_verification(true);
  13640. cli.set_follow_location(true);
  13641. auto res = cli.Get("/");
  13642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13643. ASSERT_EQ(StatusCode::OK_200, res->status);
  13644. }
  13645. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13646. SSLClient cli("gOoGlE.COm");
  13647. cli.enable_server_certificate_verification(true);
  13648. cli.enable_server_hostname_verification(true);
  13649. cli.set_follow_location(true);
  13650. auto res = cli.Get("/");
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. ASSERT_EQ(StatusCode::OK_200, res->status);
  13653. }
  13654. TEST(SSLClientTest, Issue2004_Online) {
  13655. Client client("https://google.com");
  13656. client.set_follow_location(true);
  13657. auto res = client.Get("/");
  13658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13659. ASSERT_EQ(StatusCode::OK_200, res->status);
  13660. auto body = res->body;
  13661. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13662. }
  13663. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13664. // Create SSLClient with invalid cert/key to make is_valid() return false
  13665. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13666. "nonexistent_key.pem");
  13667. // is_valid() should be false due to cert loading failure
  13668. ASSERT_FALSE(cli.is_valid());
  13669. auto res = cli.Get("/");
  13670. ASSERT_FALSE(res);
  13671. EXPECT_EQ(Error::SSLConnection, res.error());
  13672. }
  13673. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13674. // Test for Issue #2251: SSL error not properly reported when client cert
  13675. // and key paths are swapped or mismatched
  13676. // This simulates the scenario where user accidentally swaps the cert and key
  13677. // files
  13678. // Using client cert file as private key and vice versa (completely wrong)
  13679. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13680. // Should fail validation due to cert/key mismatch
  13681. ASSERT_FALSE(cli.is_valid());
  13682. // Attempt to make a request should fail with proper error
  13683. auto res = cli.Get("/");
  13684. ASSERT_FALSE(res);
  13685. EXPECT_EQ(Error::SSLConnection, res.error());
  13686. // SSL error should be recorded in the Result object (this is the key fix for
  13687. // Issue #2251)
  13688. auto backend_error = res.ssl_backend_error();
  13689. EXPECT_NE(0u, backend_error);
  13690. }
  13691. // Tests cert/key mismatch detection at the TLS context level
  13692. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13693. // Test that using mismatched cert/key causes connection failure.
  13694. // We verify this at the SSLClient level rather than through internal
  13695. // TLS API functions.
  13696. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13697. cli.enable_server_certificate_verification(false);
  13698. cli.set_connection_timeout(2);
  13699. // The mismatch should cause a connection or handshake error
  13700. auto res = cli.Get("/test");
  13701. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13702. // Either way, the request should fail
  13703. EXPECT_FALSE(res);
  13704. }
  13705. #endif
  13706. #if 0
  13707. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13708. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13709. ASSERT_TRUE(cli != nullptr);
  13710. cli->set_address_family(AF_INET6);
  13711. cli->set_interface("en0");
  13712. auto res = cli->Get("/get");
  13713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13714. ASSERT_EQ(StatusCode::OK_200, res->status);
  13715. }
  13716. #endif
  13717. // Client certificate tests - work with all TLS backends
  13718. #ifdef CPPHTTPLIB_SSL_ENABLED
  13719. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13720. void ClientCertPresent(
  13721. const std::string &client_cert_file,
  13722. const std::string &client_private_key_file,
  13723. const std::string &client_encrypted_private_key_pass = std::string(),
  13724. const ClientCertServerSetup &setup = nullptr) {
  13725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13726. ASSERT_TRUE(svr.is_valid());
  13727. if (setup) { setup(svr); }
  13728. svr.Get("/test", [&](const Request &req, Response &res) {
  13729. res.set_content("test", "text/plain");
  13730. auto cert = req.peer_cert();
  13731. ASSERT_TRUE(static_cast<bool>(cert));
  13732. std::string common_name = cert.subject_cn();
  13733. EXPECT_EQ("Common Name", common_name);
  13734. });
  13735. auto port = svr.bind_to_any_port(HOST);
  13736. ASSERT_LT(0, port);
  13737. thread t = thread([&]() { svr.listen_after_bind(); });
  13738. auto se = detail::scope_exit([&] {
  13739. svr.stop();
  13740. t.join();
  13741. ASSERT_FALSE(svr.is_running());
  13742. });
  13743. svr.wait_until_ready();
  13744. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13745. client_encrypted_private_key_pass);
  13746. cli.enable_server_certificate_verification(false);
  13747. cli.set_connection_timeout(30);
  13748. auto res = cli.Get("/test");
  13749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13750. ASSERT_EQ(StatusCode::OK_200, res->status);
  13751. }
  13752. TEST(SSLClientServerTest, ClientCertPresent) {
  13753. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13754. }
  13755. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13756. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13757. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13758. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13759. }
  13760. // Expects svr, which must require client certificates, to reject a client
  13761. // that has none
  13762. void RejectsClientWithoutCert(SSLServer &svr) {
  13763. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13764. auto port = svr.bind_to_any_port(HOST);
  13765. ASSERT_LT(0, port);
  13766. thread t = thread([&]() { svr.listen_after_bind(); });
  13767. auto se = detail::scope_exit([&] {
  13768. svr.stop();
  13769. t.join();
  13770. ASSERT_FALSE(svr.is_running());
  13771. });
  13772. svr.wait_until_ready();
  13773. SSLClient cli(HOST, port);
  13774. cli.set_connection_timeout(30);
  13775. // Skip the server certificate check, so that the request fails because the
  13776. // client certificate is missing rather than because cert.pem is not trusted
  13777. cli.enable_server_certificate_verification(false);
  13778. auto res = cli.Get("/test");
  13779. ASSERT_FALSE(res);
  13780. // The server rejects the client during the handshake, or on TLS 1.3 right
  13781. // after it, which the client notices on its first write or read
  13782. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13783. res.error() == Error::Write || res.error() == Error::Read)
  13784. << to_string(res.error());
  13785. if (res.error() == Error::SSLConnection) {
  13786. EXPECT_NE(0UL, res.ssl_backend_error());
  13787. }
  13788. // A rejection noticed on the write keeps the TLS error the write hit
  13789. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13790. }
  13791. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13793. ASSERT_TRUE(svr.is_valid());
  13794. if (setup) { setup(svr); }
  13795. RejectsClientWithoutCert(svr);
  13796. }
  13797. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13798. // A server that requires client certificates must keep requiring them after
  13799. // setup changes it, and keep accepting a client that has one
  13800. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13801. ClientCertMissing(setup);
  13802. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13803. setup);
  13804. }
  13805. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13806. ClientCertStillRequired([](SSLServer &svr) {
  13807. ASSERT_TRUE(tls::set_verify_callback(
  13808. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13809. });
  13810. }
  13811. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13812. ClientCertStillRequired([](SSLServer &svr) {
  13813. ASSERT_TRUE(tls::set_verify_callback(
  13814. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13815. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13816. });
  13817. }
  13818. // The client verifies the server certificate during the handshake, so a
  13819. // server that fails the check never gets the client certificate, even when a
  13820. // verifier of the client's own accepts it
  13821. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13822. struct Case {
  13823. const char *trusted_ca;
  13824. const char *host;
  13825. Error error;
  13826. };
  13827. // cert2.pem names localhost: the first client does not trust it, and the
  13828. // second trusts it but asks for another name
  13829. for (const auto &c :
  13830. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13831. Case{SERVER_CERT2_FILE, "example.com",
  13832. Error::SSLServerHostnameVerification}}) {
  13833. for (auto with_verifier : {false, true}) {
  13834. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13835. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13836. CLIENT_CA_CERT_FILE);
  13837. ASSERT_TRUE(svr.is_valid());
  13838. std::atomic<bool> got_client_cert{false};
  13839. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13840. [&](const tls::VerifyContext &) {
  13841. got_client_cert = true;
  13842. return true;
  13843. }));
  13844. auto port = svr.bind_to_any_port("127.0.0.1");
  13845. ASSERT_LT(0, port);
  13846. thread t = thread([&] { svr.listen_after_bind(); });
  13847. svr.wait_until_ready();
  13848. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13849. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13850. cli.set_ca_cert_path(c.trusted_ca);
  13851. if (with_verifier) {
  13852. cli.set_server_certificate_verifier(
  13853. [](const tls::VerifyContext &) { return true; });
  13854. }
  13855. auto res = cli.Get("/");
  13856. EXPECT_FALSE(res);
  13857. EXPECT_EQ(c.error, res.error());
  13858. svr.stop();
  13859. t.join();
  13860. EXPECT_FALSE(got_client_cert);
  13861. }
  13862. }
  13863. }
  13864. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13865. std::string cert_pem, key_pem, ca_pem;
  13866. read_file(SERVER_CERT_FILE, cert_pem);
  13867. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13868. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13869. ASSERT_TRUE(
  13870. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13871. }
  13872. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13874. ASSERT_TRUE(svr.is_valid());
  13875. UpdateCertsPemWithClientCA(svr);
  13876. RejectsClientWithoutCert(svr);
  13877. }
  13878. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13879. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13880. }
  13881. // A TLS error from one request must not show up in a later request's Result
  13882. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13883. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13884. ASSERT_TRUE(svr.is_valid());
  13885. svr.Get("/test", [](const Request &, Response &res) {
  13886. res.set_content("test", "text/plain");
  13887. });
  13888. auto port = svr.bind_to_any_port(HOST);
  13889. ASSERT_LT(0, port);
  13890. thread t = thread([&]() { svr.listen_after_bind(); });
  13891. auto se = detail::scope_exit([&] {
  13892. svr.stop();
  13893. t.join();
  13894. ASSERT_FALSE(svr.is_running());
  13895. });
  13896. svr.wait_until_ready();
  13897. SSLClient cli(HOST, port);
  13898. cli.set_connection_timeout(30);
  13899. cli.enable_server_hostname_verification(false);
  13900. // cert.pem is not trusted, so the handshake fails
  13901. ASSERT_FALSE(cli.Get("/test"));
  13902. cli.enable_server_certificate_verification(false);
  13903. auto res = cli.Get("/test");
  13904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13905. EXPECT_EQ(0, res.ssl_error());
  13906. EXPECT_EQ(0UL, res.ssl_backend_error());
  13907. }
  13908. // PEM memory-based constructor tests (works with all TLS backends).
  13909. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13910. // terminator after it.
  13911. void PemMemoryClientCertPresent(
  13912. const std::string &client_cert_file,
  13913. const std::string &client_private_key_file,
  13914. const std::string &client_encrypted_private_key_pass = std::string(),
  13915. bool exact_size = false) {
  13916. // Read PEM files into memory
  13917. std::string server_cert_pem, server_key_pem;
  13918. std::string client_ca_pem;
  13919. std::string client_cert_pem, client_key_pem;
  13920. read_file(SERVER_CERT_FILE, server_cert_pem);
  13921. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13922. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13923. read_file(client_cert_file, client_cert_pem);
  13924. read_file(client_private_key_file, client_key_pem);
  13925. std::list<std::vector<char>> exact_copies;
  13926. auto data = [&](const std::string &pem) -> const char * {
  13927. if (!exact_size) { return pem.c_str(); }
  13928. exact_copies.emplace_back(pem.begin(), pem.end());
  13929. return exact_copies.back().data();
  13930. };
  13931. // Create server with PEM memory
  13932. SSLServer::PemMemory server_pem = {
  13933. data(server_cert_pem),
  13934. server_cert_pem.size(),
  13935. data(server_key_pem),
  13936. server_key_pem.size(),
  13937. data(client_ca_pem),
  13938. client_ca_pem.size(),
  13939. nullptr // no password for server key
  13940. };
  13941. SSLServer svr(server_pem);
  13942. ASSERT_TRUE(svr.is_valid());
  13943. svr.Get("/test", [&](const Request &req, Response &res) {
  13944. res.set_content("test", "text/plain");
  13945. auto cert = req.peer_cert();
  13946. ASSERT_TRUE(static_cast<bool>(cert));
  13947. EXPECT_EQ("Common Name", cert.subject_cn());
  13948. });
  13949. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13950. auto se = detail::scope_exit([&] {
  13951. svr.stop();
  13952. t.join();
  13953. ASSERT_FALSE(svr.is_running());
  13954. });
  13955. svr.wait_until_ready();
  13956. // Create client with PEM memory
  13957. const char *password = client_encrypted_private_key_pass.empty()
  13958. ? nullptr
  13959. : client_encrypted_private_key_pass.c_str();
  13960. SSLClient::PemMemory client_pem = {
  13961. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13962. client_key_pem.size(), password};
  13963. SSLClient cli(HOST, PORT, client_pem);
  13964. cli.enable_server_certificate_verification(false);
  13965. cli.set_connection_timeout(30);
  13966. auto res = cli.Get("/test");
  13967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13968. ASSERT_EQ(StatusCode::OK_200, res->status);
  13969. }
  13970. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13971. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13972. }
  13973. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13974. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13975. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13976. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13977. }
  13978. // A server built from PEM memory with a client CA requires client certificates,
  13979. // also when the CA is a NUL-terminated string passed with a length of 0
  13980. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13981. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13982. read_file(SERVER_CERT_FILE, server_cert_pem);
  13983. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13984. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13985. SSLServer::PemMemory server_pem = {
  13986. server_cert_pem.c_str(),
  13987. server_cert_pem.size(),
  13988. server_key_pem.c_str(),
  13989. server_key_pem.size(),
  13990. client_ca_pem.c_str(),
  13991. client_ca_pem.size(),
  13992. nullptr // no password for server key
  13993. };
  13994. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13995. SCOPED_TRACE(client_ca_pem_len);
  13996. server_pem.client_ca_pem_len = client_ca_pem_len;
  13997. SSLServer svr(server_pem);
  13998. ASSERT_TRUE(svr.is_valid());
  13999. RejectsClientWithoutCert(svr);
  14000. }
  14001. // An empty CA fails to load instead of turning the check off
  14002. server_pem.client_ca_pem = "";
  14003. server_pem.client_ca_pem_len = 0;
  14004. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14005. }
  14006. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14007. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14008. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14009. true);
  14010. }
  14011. // A length shorter than the PEM cuts it short, so it no longer loads
  14012. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14013. std::string cert, key;
  14014. read_file(SERVER_CERT_FILE, cert);
  14015. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14016. for (auto cut_cert : {true, false}) {
  14017. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14018. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14019. SSLServer::PemMemory server_pem = {
  14020. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14021. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14022. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14023. key_len, nullptr};
  14024. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14025. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14026. key.c_str(), key_len, nullptr};
  14027. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14028. }
  14029. }
  14030. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14031. class NoListenSSLServer : public SSLServer {
  14032. public:
  14033. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14034. const char *client_ca_cert_file_path,
  14035. const char *client_ca_cert_dir_path = nullptr)
  14036. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14037. client_ca_cert_dir_path),
  14038. stop_(false) {}
  14039. std::atomic_bool stop_;
  14040. private:
  14041. bool process_and_close_socket(socket_t /*sock*/) override {
  14042. // Don't create SSL context
  14043. while (!stop_.load()) {
  14044. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14045. }
  14046. return true;
  14047. }
  14048. };
  14049. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14050. CLIENT_CA_CERT_FILE);
  14051. ASSERT_TRUE(svr.is_valid());
  14052. svr.Get("/test", [&](const Request &, Response &res) {
  14053. res.set_content("test", "text/plain");
  14054. });
  14055. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14056. auto se = detail::scope_exit([&] {
  14057. svr.stop_ = true;
  14058. svr.stop();
  14059. t.join();
  14060. ASSERT_FALSE(svr.is_running());
  14061. });
  14062. svr.wait_until_ready();
  14063. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14064. cli.enable_server_certificate_verification(false);
  14065. cli.set_connection_timeout(1);
  14066. auto res = cli.Get("/test");
  14067. ASSERT_TRUE(!res);
  14068. EXPECT_EQ(Error::SSLConnection, res.error());
  14069. // Timeout results in WantRead error code (maps to backend-specific value)
  14070. EXPECT_NE(0, res.ssl_error());
  14071. }
  14072. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14073. // Test SSLServer with client certificate verification using the standard
  14074. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14076. CLIENT_CA_CERT_DIR);
  14077. ASSERT_TRUE(svr.is_valid());
  14078. svr.Get("/test", [&](const Request &req, Response &res) {
  14079. res.set_content("test", "text/plain");
  14080. auto cert = req.peer_cert();
  14081. ASSERT_TRUE(static_cast<bool>(cert));
  14082. auto common_name = cert.subject_cn();
  14083. EXPECT_EQ("Common Name", common_name);
  14084. });
  14085. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14086. auto se = detail::scope_exit([&] {
  14087. svr.stop();
  14088. t.join();
  14089. ASSERT_FALSE(svr.is_running());
  14090. });
  14091. svr.wait_until_ready();
  14092. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14093. cli.enable_server_certificate_verification(false);
  14094. cli.set_connection_timeout(30);
  14095. auto res = cli.Get("/test");
  14096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14097. ASSERT_EQ(StatusCode::OK_200, res->status);
  14098. }
  14099. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14100. // Verifies that wildcard matching and exact matching work consistently
  14101. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14102. using namespace httplib::tls;
  14103. // We need a running server to test against
  14104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14105. ASSERT_TRUE(svr.is_valid());
  14106. svr.Get("/test", [](const Request &, Response &res) {
  14107. res.set_content("ok", "text/plain");
  14108. });
  14109. thread t([&]() { svr.listen(HOST, PORT); });
  14110. auto se = detail::scope_exit([&] {
  14111. svr.stop();
  14112. t.join();
  14113. });
  14114. svr.wait_until_ready();
  14115. bool verify_callback_called = false;
  14116. bool verify_result_wrong = false;
  14117. SSLClient cli(HOST, PORT);
  14118. cli.enable_server_certificate_verification(true);
  14119. cli.set_ca_cert_path(CA_CERT_FILE);
  14120. cli.set_connection_timeout(5);
  14121. // Note: Test certificate has CN="Common Name", not "localhost"
  14122. bool verify_result_cn = false;
  14123. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14124. verify_callback_called = true;
  14125. if (!ctx.cert) return false;
  14126. // Test 1: "Common Name" should match (our test server cert CN)
  14127. verify_result_cn = ctx.check_hostname("Common Name");
  14128. // Test 2: wrong hostname should not match
  14129. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14130. return true; // Accept for the purpose of this test
  14131. });
  14132. auto res = cli.Get("/test");
  14133. // The request may succeed or fail depending on cert configuration
  14134. // but the callback should have been called
  14135. ASSERT_TRUE(verify_callback_called)
  14136. << "Verify callback should have been called";
  14137. // CN="Common Name" should match our test certificate
  14138. //
  14139. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14140. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14141. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14142. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14143. // <openssl/base.h>, which is included transitively when
  14144. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14145. #if defined(OPENSSL_IS_BORINGSSL)
  14146. EXPECT_FALSE(verify_result_cn)
  14147. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14148. #else
  14149. EXPECT_TRUE(verify_result_cn)
  14150. << "verify_hostname should match 'Common Name' (certificate CN)";
  14151. #endif
  14152. // Wrong hostname should not match
  14153. EXPECT_FALSE(verify_result_wrong)
  14154. << "verify_hostname should not match 'wronghost.example.com'";
  14155. }
  14156. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14157. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14158. // X509_check_ip behavior and must hold for every backend.
  14159. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14160. using namespace httplib::tls;
  14161. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14162. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14163. ASSERT_TRUE(svr.is_valid());
  14164. svr.Get("/test", [](const Request &, Response &res) {
  14165. res.set_content("ok", "text/plain");
  14166. });
  14167. thread t([&]() { svr.listen(HOST, PORT); });
  14168. auto se = detail::scope_exit([&] {
  14169. svr.stop();
  14170. t.join();
  14171. });
  14172. svr.wait_until_ready();
  14173. bool verify_callback_called = false;
  14174. bool ip_matched_via_cn = true;
  14175. SSLClient cli(HOST, PORT);
  14176. cli.enable_server_certificate_verification(true);
  14177. cli.set_ca_cert_path(CA_CERT_FILE);
  14178. cli.set_connection_timeout(5);
  14179. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14180. verify_callback_called = true;
  14181. if (!ctx.cert) return false;
  14182. // The IP appears only in the CN, so it must NOT be accepted.
  14183. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14184. return true; // Accept for the purpose of this test
  14185. });
  14186. cli.Get("/test");
  14187. ASSERT_TRUE(verify_callback_called)
  14188. << "Verify callback should have been called";
  14189. EXPECT_FALSE(ip_matched_via_cn)
  14190. << "An IP host must not be authenticated via the certificate CN";
  14191. }
  14192. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14193. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14194. using namespace httplib::tls;
  14195. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14196. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14197. ASSERT_TRUE(svr.is_valid());
  14198. svr.Get("/test", [](const Request &, Response &res) {
  14199. res.set_content("ok", "text/plain");
  14200. });
  14201. thread t([&]() { svr.listen(HOST, PORT); });
  14202. auto se = detail::scope_exit([&] {
  14203. svr.stop();
  14204. t.join();
  14205. });
  14206. svr.wait_until_ready();
  14207. bool verify_callback_called = false;
  14208. bool san_matched = false;
  14209. bool wrong_ipv6_matched = true;
  14210. bool cn_ipv6_matched = true;
  14211. SSLClient cli(HOST, PORT);
  14212. cli.enable_server_certificate_verification(true);
  14213. cli.set_ca_cert_path(CA_CERT_FILE);
  14214. cli.set_connection_timeout(5);
  14215. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14216. verify_callback_called = true;
  14217. if (!ctx.cert) return false;
  14218. // Matches the IPv6 iPAddress SAN.
  14219. san_matched = ctx.check_hostname("2001:db8::1");
  14220. // A different IPv6 address must not match.
  14221. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14222. // "::1" lives only in the CN, so it must not be accepted.
  14223. cn_ipv6_matched = ctx.check_hostname("::1");
  14224. return true; // Accept for the purpose of this test
  14225. });
  14226. cli.Get("/test");
  14227. ASSERT_TRUE(verify_callback_called)
  14228. << "Verify callback should have been called";
  14229. EXPECT_TRUE(san_matched)
  14230. << "verify_hostname should match an IPv6 iPAddress SAN";
  14231. EXPECT_FALSE(wrong_ipv6_matched)
  14232. << "verify_hostname should not match a non-matching IPv6 address";
  14233. EXPECT_FALSE(cn_ipv6_matched)
  14234. << "An IPv6 host must not be authenticated via the certificate CN";
  14235. }
  14236. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14237. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14238. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14239. using namespace httplib::tls;
  14240. // SANs: DNS:a.zz, IP:42.46.122.122
  14241. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14242. ASSERT_TRUE(svr.is_valid());
  14243. svr.Get("/test", [](const Request &, Response &res) {
  14244. res.set_content("ok", "text/plain");
  14245. });
  14246. auto port = svr.bind_to_any_port(HOST);
  14247. thread t([&]() { svr.listen_after_bind(); });
  14248. auto se = detail::scope_exit([&] {
  14249. svr.stop();
  14250. t.join();
  14251. });
  14252. svr.wait_until_ready();
  14253. bool verify_callback_called = false;
  14254. bool dns_san_matched = false;
  14255. bool ip_san_matched = false;
  14256. bool ip_matched_via_dns_san = true;
  14257. bool dns_matched_via_ip_san = true;
  14258. bool cn_matched_next_to_dns_san = true;
  14259. SSLClient cli(HOST, port);
  14260. cli.enable_server_certificate_verification(true);
  14261. cli.set_ca_cert_path(CA_CERT_FILE);
  14262. cli.set_connection_timeout(5);
  14263. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14264. verify_callback_called = true;
  14265. if (!ctx.cert) return false;
  14266. dns_san_matched = ctx.check_hostname("a.zz");
  14267. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14268. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14269. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14270. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14271. return true; // Accept for the purpose of this test
  14272. });
  14273. cli.Get("/test");
  14274. ASSERT_TRUE(verify_callback_called)
  14275. << "Verify callback should have been called";
  14276. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14277. EXPECT_TRUE(ip_san_matched)
  14278. << "verify_hostname should match an iPAddress SAN";
  14279. EXPECT_FALSE(ip_matched_via_dns_san)
  14280. << "An IP host must not be authenticated via a dNSName SAN";
  14281. EXPECT_FALSE(dns_matched_via_ip_san)
  14282. << "A DNS host must not be authenticated via an iPAddress SAN";
  14283. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14284. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14285. }
  14286. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14287. // "www.*.example.test" names one host and not every host under example.test.
  14288. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14289. using namespace httplib::tls;
  14290. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14291. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14292. ASSERT_TRUE(svr.is_valid());
  14293. svr.Get("/test", [](const Request &, Response &res) {
  14294. res.set_content("ok", "text/plain");
  14295. });
  14296. auto port = svr.bind_to_any_port(HOST);
  14297. thread t([&]() { svr.listen_after_bind(); });
  14298. auto se = detail::scope_exit([&] {
  14299. svr.stop();
  14300. t.join();
  14301. });
  14302. svr.wait_until_ready();
  14303. bool verify_callback_called = false;
  14304. bool leftmost_wildcard_matched = false;
  14305. bool wildcard_spanned_labels = true;
  14306. bool inner_wildcard_matched = true;
  14307. SSLClient cli(HOST, port);
  14308. cli.enable_server_certificate_verification(true);
  14309. cli.set_ca_cert_path(CA_CERT_FILE);
  14310. cli.set_connection_timeout(5);
  14311. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14312. verify_callback_called = true;
  14313. if (!ctx.cert) return false;
  14314. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14315. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14316. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14317. return true; // Accept for the purpose of this test
  14318. });
  14319. cli.Get("/test");
  14320. ASSERT_TRUE(verify_callback_called)
  14321. << "Verify callback should have been called";
  14322. EXPECT_TRUE(leftmost_wildcard_matched)
  14323. << "A leftmost wildcard should match a single label";
  14324. EXPECT_FALSE(wildcard_spanned_labels)
  14325. << "A wildcard label must not match more than one label";
  14326. EXPECT_FALSE(inner_wildcard_matched)
  14327. << "A wildcard outside the leftmost label must not be honoured";
  14328. }
  14329. // sans() must report each SAN entry under its own type.
  14330. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14331. using namespace httplib::tls;
  14332. // SANs: DNS:a.zz, IP:42.46.122.122
  14333. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14334. ASSERT_TRUE(svr.is_valid());
  14335. svr.Get("/test", [](const Request &, Response &res) {
  14336. res.set_content("ok", "text/plain");
  14337. });
  14338. auto port = svr.bind_to_any_port(HOST);
  14339. thread t([&]() { svr.listen_after_bind(); });
  14340. auto se = detail::scope_exit([&] {
  14341. svr.stop();
  14342. t.join();
  14343. });
  14344. svr.wait_until_ready();
  14345. bool verify_callback_called = false;
  14346. std::vector<SanEntry> sans;
  14347. SSLClient cli(HOST, port);
  14348. cli.enable_server_certificate_verification(true);
  14349. cli.set_ca_cert_path(CA_CERT_FILE);
  14350. cli.set_connection_timeout(5);
  14351. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14352. verify_callback_called = true;
  14353. if (!ctx.cert) return false;
  14354. sans = ctx.sans();
  14355. return true; // Accept for the purpose of this test
  14356. });
  14357. cli.Get("/test");
  14358. ASSERT_TRUE(verify_callback_called)
  14359. << "Verify callback should have been called";
  14360. auto has_san = [&](SanType type, const std::string &value) {
  14361. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14362. return san.type == type && san.value == value;
  14363. });
  14364. };
  14365. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14366. << "sans() should report the dNSName SAN";
  14367. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14368. << "sans() should report the iPAddress SAN";
  14369. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14370. << "sans() must not report the dNSName SAN as an address";
  14371. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14372. << "sans() must not report the iPAddress SAN as a DNS name";
  14373. }
  14374. #endif
  14375. // mbedTLS-specific callback constructor test
  14376. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14377. #ifdef CPPHTTPLIB_SSL_ENABLED
  14378. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14380. ASSERT_TRUE(svr.is_valid());
  14381. // Set up a handler to verify client certificate is present
  14382. bool client_cert_verified = false;
  14383. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14384. // Verify that client certificate was provided
  14385. client_cert_verified = true;
  14386. res.set_content("success", "text/plain");
  14387. });
  14388. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14389. auto se = detail::scope_exit([&] {
  14390. svr.stop();
  14391. t.join();
  14392. ASSERT_FALSE(svr.is_running());
  14393. });
  14394. svr.wait_until_ready();
  14395. // Client with certificate
  14396. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14397. cli.enable_server_certificate_verification(false);
  14398. cli.set_connection_timeout(30);
  14399. auto res = cli.Get("/test");
  14400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14401. ASSERT_EQ(StatusCode::OK_200, res->status);
  14402. ASSERT_TRUE(client_cert_verified);
  14403. EXPECT_EQ("success", res->body);
  14404. }
  14405. #endif
  14406. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14407. // backends
  14408. #ifdef CPPHTTPLIB_SSL_ENABLED
  14409. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14410. using namespace httplib::tls;
  14411. // Test that when client CA cert file is provided,
  14412. // the server properly requests and validates client certificates
  14413. // Create a server with client authentication
  14414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14415. ASSERT_TRUE(svr.is_valid());
  14416. bool handler_called = false;
  14417. svr.Get("/test", [&](const Request &req, Response &res) {
  14418. handler_called = true;
  14419. // Verify that a client certificate was provided
  14420. auto cert = req.peer_cert();
  14421. ASSERT_TRUE(static_cast<bool>(cert));
  14422. // Get the issuer name
  14423. std::string issuer_str = cert.issuer_name();
  14424. ASSERT_FALSE(issuer_str.empty());
  14425. // The client certificate should be issued by our test CA
  14426. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14427. res.set_content("authenticated", "text/plain");
  14428. });
  14429. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14430. auto se = detail::scope_exit([&] {
  14431. svr.stop();
  14432. t.join();
  14433. ASSERT_FALSE(svr.is_running());
  14434. });
  14435. svr.wait_until_ready();
  14436. // Connect with a client certificate issued by the CA
  14437. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14438. cli.enable_server_certificate_verification(false);
  14439. cli.set_connection_timeout(30);
  14440. auto res = cli.Get("/test");
  14441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14442. ASSERT_EQ(StatusCode::OK_200, res->status);
  14443. ASSERT_TRUE(handler_called);
  14444. EXPECT_EQ("authenticated", res->body);
  14445. }
  14446. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14447. using namespace httplib::tls;
  14448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14449. ASSERT_TRUE(svr.is_valid());
  14450. svr.Get("/test", [](const Request &, Response &res) {
  14451. res.set_content("ok", "text/plain");
  14452. });
  14453. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14454. auto se = detail::scope_exit([&] {
  14455. svr.stop();
  14456. t.join();
  14457. });
  14458. svr.wait_until_ready();
  14459. SSLClient cli(HOST, PORT);
  14460. cli.enable_server_certificate_verification(false);
  14461. cli.set_connection_timeout(30);
  14462. bool cert_checked = false;
  14463. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14464. if (ctx.cert) {
  14465. auto sans = ctx.sans();
  14466. // Test certificate may or may not have SANs - just verify the API
  14467. // works If SANs exist, verify the types are valid
  14468. for (const auto &san : sans) {
  14469. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14470. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14471. san.type == SanType::OTHER);
  14472. EXPECT_FALSE(san.value.empty());
  14473. }
  14474. cert_checked = true;
  14475. }
  14476. return true;
  14477. });
  14478. auto res = cli.Get("/test");
  14479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14480. EXPECT_TRUE(cert_checked);
  14481. }
  14482. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14483. using namespace httplib::tls;
  14484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14485. ASSERT_TRUE(svr.is_valid());
  14486. svr.Get("/test", [](const Request &, Response &res) {
  14487. res.set_content("ok", "text/plain");
  14488. });
  14489. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14490. auto se = detail::scope_exit([&] {
  14491. svr.stop();
  14492. t.join();
  14493. });
  14494. svr.wait_until_ready();
  14495. SSLClient cli(HOST, PORT);
  14496. cli.enable_server_certificate_verification(false);
  14497. cli.set_connection_timeout(30);
  14498. bool validity_checked = false;
  14499. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14500. if (ctx.cert) {
  14501. time_t not_before = 0, not_after = 0;
  14502. bool result = ctx.validity(not_before, not_after);
  14503. EXPECT_TRUE(result);
  14504. // Verify that not_before < now < not_after for a valid cert
  14505. time_t now = time(nullptr);
  14506. EXPECT_LT(not_before, now);
  14507. EXPECT_GT(not_after, now);
  14508. validity_checked = true;
  14509. }
  14510. return true;
  14511. });
  14512. auto res = cli.Get("/test");
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14514. EXPECT_TRUE(validity_checked);
  14515. }
  14516. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14517. using namespace httplib::tls;
  14518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14519. ASSERT_TRUE(svr.is_valid());
  14520. svr.Get("/test", [](const Request &, Response &res) {
  14521. res.set_content("ok", "text/plain");
  14522. });
  14523. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14524. auto se = detail::scope_exit([&] {
  14525. svr.stop();
  14526. t.join();
  14527. });
  14528. svr.wait_until_ready();
  14529. SSLClient cli(HOST, PORT);
  14530. cli.enable_server_certificate_verification(false);
  14531. cli.set_connection_timeout(30);
  14532. bool serial_checked = false;
  14533. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14534. if (ctx.cert) {
  14535. std::string serial = ctx.serial();
  14536. EXPECT_FALSE(serial.empty());
  14537. // Serial should be a hex string
  14538. for (char c : serial) {
  14539. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14540. (c >= 'a' && c <= 'f'));
  14541. }
  14542. serial_checked = true;
  14543. }
  14544. return true;
  14545. });
  14546. auto res = cli.Get("/test");
  14547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14548. EXPECT_TRUE(serial_checked);
  14549. }
  14550. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14551. // Test 1: Valid CA file - no error should be recorded
  14552. {
  14553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14554. CLIENT_CA_CERT_FILE);
  14555. ASSERT_TRUE(svr.is_valid());
  14556. // With valid setup, last_ssl_error should be 0
  14557. EXPECT_EQ(0, svr.ssl_last_error());
  14558. }
  14559. // Test 2: Invalid CA file content
  14560. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14561. {
  14562. // Create a temporary file with completely invalid content
  14563. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14564. {
  14565. std::ofstream ofs(temp_invalid_ca);
  14566. ofs << "This is not a certificate file at all\n";
  14567. ofs << "Just plain text content\n";
  14568. }
  14569. // Create server with invalid CA file
  14570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14571. // Clean up temporary file
  14572. std::remove(temp_invalid_ca);
  14573. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14574. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14575. // Note: SSL_CTX_load_verify_locations typically fails first,
  14576. // but our error handling code path is still exercised
  14577. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14578. }
  14579. }
  14580. TEST(VerifyCallbackTest, VerifyContextFields) {
  14581. using namespace httplib::tls;
  14582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14583. ASSERT_TRUE(svr.is_valid());
  14584. svr.Get("/test", [](const Request &, Response &res) {
  14585. res.set_content("ok", "text/plain");
  14586. });
  14587. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14588. auto se = detail::scope_exit([&] {
  14589. svr.stop();
  14590. t.join();
  14591. });
  14592. svr.wait_until_ready();
  14593. SSLClient cli(HOST, PORT);
  14594. cli.enable_server_certificate_verification(false);
  14595. cli.set_connection_timeout(30);
  14596. int callback_count = 0;
  14597. bool saw_leaf_cert = false;
  14598. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14599. if (ctx.cert) {
  14600. callback_count++;
  14601. // We should see at least one certificate (the leaf)
  14602. std::string cn = ctx.subject_cn();
  14603. if (!cn.empty()) { saw_leaf_cert = true; }
  14604. // Verify context fields are populated
  14605. EXPECT_NE(ctx.session, nullptr);
  14606. EXPECT_GE(ctx.depth, 0);
  14607. }
  14608. return true;
  14609. });
  14610. auto res = cli.Get("/test");
  14611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14612. EXPECT_GT(callback_count, 0);
  14613. EXPECT_TRUE(saw_leaf_cert);
  14614. }
  14615. // A verifier that accepts runs alongside the built-in verification, and is the
  14616. // only check once that is turned off.
  14617. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14618. using namespace httplib::tls;
  14619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14620. ASSERT_TRUE(svr.is_valid());
  14621. svr.Get("/test", [](const Request &, Response &res) {
  14622. res.set_content("ok", "text/plain");
  14623. });
  14624. auto port = svr.bind_to_any_port(HOST);
  14625. thread t([&]() { svr.listen_after_bind(); });
  14626. auto se = detail::scope_exit([&] {
  14627. svr.stop();
  14628. t.join();
  14629. });
  14630. svr.wait_until_ready();
  14631. SSLClient cli(HOST, port);
  14632. cli.enable_server_hostname_verification(false);
  14633. auto calls = 0;
  14634. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14635. calls++;
  14636. return true;
  14637. });
  14638. // cert.pem is not trusted
  14639. auto res = cli.Get("/test");
  14640. ASSERT_FALSE(res);
  14641. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14642. EXPECT_GT(calls, 0);
  14643. cli.enable_server_certificate_verification(false);
  14644. res = cli.Get("/test");
  14645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14646. EXPECT_EQ("ok", res->body);
  14647. }
  14648. // A verifier belongs to the client that set it, not to the thread that set it.
  14649. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14650. using namespace httplib::tls;
  14651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14652. ASSERT_TRUE(svr.is_valid());
  14653. svr.Get("/test", [](const Request &, Response &res) {
  14654. res.set_content("ok", "text/plain");
  14655. });
  14656. auto port = svr.bind_to_any_port(HOST);
  14657. thread t([&]() { svr.listen_after_bind(); });
  14658. auto se = detail::scope_exit([&] {
  14659. svr.stop();
  14660. t.join();
  14661. });
  14662. svr.wait_until_ready();
  14663. auto rejecting_calls = 0;
  14664. SSLClient rejecting(HOST, port);
  14665. rejecting.enable_server_certificate_verification(false);
  14666. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14667. rejecting_calls++;
  14668. return false;
  14669. });
  14670. auto accepting_calls = 0;
  14671. SSLClient accepting(HOST, port);
  14672. accepting.enable_server_certificate_verification(false);
  14673. // Set on another thread than the requests below.
  14674. thread([&]() {
  14675. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14676. accepting_calls++;
  14677. return true;
  14678. });
  14679. }).join();
  14680. // Requested on another thread than the verifier was set on.
  14681. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14682. EXPECT_GT(rejecting_calls, 0);
  14683. auto res = accepting.Get("/test");
  14684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14685. EXPECT_GT(accepting_calls, 0);
  14686. }
  14687. // A verifier replaced while a handshake runs it lives until it returns.
  14688. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14689. using namespace httplib::tls;
  14690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14691. ASSERT_TRUE(svr.is_valid());
  14692. svr.Get("/test", [](const Request &, Response &res) {
  14693. res.set_content("ok", "text/plain");
  14694. });
  14695. auto port = svr.bind_to_any_port(HOST);
  14696. thread t([&]() { svr.listen_after_bind(); });
  14697. auto se = detail::scope_exit([&] {
  14698. svr.stop();
  14699. t.join();
  14700. });
  14701. svr.wait_until_ready();
  14702. SSLClient cli(HOST, port);
  14703. cli.enable_server_certificate_verification(false);
  14704. std::promise<void> entered;
  14705. std::promise<void> replaced;
  14706. auto replaced_future = replaced.get_future();
  14707. auto first_call = true;
  14708. // Long enough to live on the heap
  14709. std::string expected(64, 'v');
  14710. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14711. if (first_call) {
  14712. first_call = false;
  14713. entered.set_value();
  14714. replaced_future.wait();
  14715. }
  14716. return expected == std::string(64, 'v');
  14717. });
  14718. thread request([&]() {
  14719. auto res = cli.Get("/test");
  14720. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14721. });
  14722. entered.get_future().wait();
  14723. cli.set_server_certificate_verifier(
  14724. [](const VerifyContext &) { return true; });
  14725. replaced.set_value();
  14726. request.join();
  14727. }
  14728. // VerifyContext::session is the same handle the other tls:: functions take.
  14729. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14730. using namespace httplib::tls;
  14731. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14732. ASSERT_TRUE(svr.is_valid());
  14733. svr.Get("/test", [](const Request &, Response &res) {
  14734. res.set_content("ok", "text/plain");
  14735. });
  14736. auto port = svr.bind_to_any_port(HOST);
  14737. thread t([&]() { svr.listen_after_bind(); });
  14738. auto se = detail::scope_exit([&] {
  14739. svr.stop();
  14740. t.join();
  14741. });
  14742. svr.wait_until_ready();
  14743. SSLClient cli(HOST, port);
  14744. cli.enable_server_certificate_verification(false);
  14745. session_t verifier_session = nullptr;
  14746. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14747. verifier_session = ctx.session;
  14748. return true;
  14749. });
  14750. session_t session_verifier_session = nullptr;
  14751. cli.set_session_verifier([&](session_t session) {
  14752. session_verifier_session = session;
  14753. return SSLVerifierResponse::NoDecisionMade;
  14754. });
  14755. auto res = cli.Get("/test");
  14756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14757. EXPECT_NE(nullptr, verifier_session);
  14758. EXPECT_EQ(session_verifier_session, verifier_session);
  14759. }
  14760. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14761. using httplib::tls::TlsError;
  14762. // Test that verify_error_to_string returns empty for success
  14763. std::string success_str = TlsError::verify_error_to_string(0);
  14764. EXPECT_TRUE(success_str.empty());
  14765. // Test that verify_error_to_string returns non-empty for error codes
  14766. // Using a common error code (certificate expired)
  14767. std::string error_str =
  14768. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14769. EXPECT_FALSE(error_str.empty());
  14770. }
  14771. TEST(SessionVerifierTest, CertificateAccepted) {
  14772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14773. ASSERT_TRUE(svr.is_valid());
  14774. svr.Get("/test", [](const Request &, Response &res) {
  14775. res.set_content("ok", "text/plain");
  14776. });
  14777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14778. auto se = detail::scope_exit([&] {
  14779. svr.stop();
  14780. t.join();
  14781. });
  14782. svr.wait_until_ready();
  14783. SSLClient cli(HOST, PORT);
  14784. cli.enable_server_certificate_verification(false);
  14785. cli.set_connection_timeout(30);
  14786. bool callback_called = false;
  14787. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14788. EXPECT_NE(session, nullptr);
  14789. callback_called = true;
  14790. return SSLVerifierResponse::CertificateAccepted;
  14791. });
  14792. auto res = cli.Get("/test");
  14793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14794. EXPECT_EQ(200, res->status);
  14795. EXPECT_TRUE(callback_called);
  14796. }
  14797. TEST(SessionVerifierTest, CertificateRejected) {
  14798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14799. ASSERT_TRUE(svr.is_valid());
  14800. svr.Get("/test", [](const Request &, Response &res) {
  14801. res.set_content("ok", "text/plain");
  14802. });
  14803. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14804. auto se = detail::scope_exit([&] {
  14805. svr.stop();
  14806. t.join();
  14807. });
  14808. svr.wait_until_ready();
  14809. SSLClient cli(HOST, PORT);
  14810. cli.enable_server_certificate_verification(false);
  14811. cli.set_connection_timeout(30);
  14812. bool callback_called = false;
  14813. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14814. EXPECT_NE(session, nullptr);
  14815. callback_called = true;
  14816. return SSLVerifierResponse::CertificateRejected;
  14817. });
  14818. auto res = cli.Get("/test");
  14819. EXPECT_FALSE(res);
  14820. EXPECT_TRUE(callback_called);
  14821. }
  14822. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14824. ASSERT_TRUE(svr.is_valid());
  14825. svr.Get("/test", [](const Request &, Response &res) {
  14826. res.set_content("ok", "text/plain");
  14827. });
  14828. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14829. auto se = detail::scope_exit([&] {
  14830. svr.stop();
  14831. t.join();
  14832. });
  14833. svr.wait_until_ready();
  14834. // NoDecisionMade with verification disabled should succeed (no default check)
  14835. SSLClient cli(HOST, PORT);
  14836. cli.enable_server_certificate_verification(false);
  14837. cli.set_connection_timeout(30);
  14838. bool callback_called = false;
  14839. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14840. EXPECT_NE(session, nullptr);
  14841. callback_called = true;
  14842. return SSLVerifierResponse::NoDecisionMade;
  14843. });
  14844. auto res = cli.Get("/test");
  14845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14846. EXPECT_EQ(200, res->status);
  14847. EXPECT_TRUE(callback_called);
  14848. }
  14849. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14851. ASSERT_TRUE(svr.is_valid());
  14852. svr.Get("/test", [](const Request &, Response &res) {
  14853. res.set_content("ok", "text/plain");
  14854. });
  14855. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14856. auto se = detail::scope_exit([&] {
  14857. svr.stop();
  14858. t.join();
  14859. });
  14860. svr.wait_until_ready();
  14861. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14862. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14863. // so we only check that the request fails, not whether the callback was
  14864. // called.
  14865. SSLClient cli(HOST, PORT);
  14866. cli.enable_server_certificate_verification(true);
  14867. cli.set_connection_timeout(30);
  14868. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14869. EXPECT_NE(session, nullptr);
  14870. return SSLVerifierResponse::NoDecisionMade;
  14871. });
  14872. auto res = cli.Get("/test");
  14873. EXPECT_FALSE(res);
  14874. }
  14875. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14876. // Test SSL server using PemMemory constructor with client CA certificates
  14877. // Read PEM files
  14878. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14879. read_file(SERVER_CERT_FILE, server_cert_pem);
  14880. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14881. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14882. // Create SSLServer with PemMemory constructor including client CA
  14883. SSLServer::PemMemory server_pem = {
  14884. server_cert_pem.c_str(),
  14885. server_cert_pem.size(),
  14886. server_key_pem.c_str(),
  14887. server_key_pem.size(),
  14888. client_ca_pem.c_str(),
  14889. client_ca_pem.size(),
  14890. nullptr // no password for server key
  14891. };
  14892. SSLServer svr(server_pem);
  14893. ASSERT_TRUE(svr.is_valid());
  14894. // No SSL error should be recorded for valid setup
  14895. EXPECT_EQ(0, svr.ssl_last_error());
  14896. // Set up server endpoints
  14897. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14898. res.set_content("ok", "text/plain");
  14899. });
  14900. // Start server in a thread
  14901. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14902. svr.wait_until_ready();
  14903. // Connect with client certificate (using constructor with paths)
  14904. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14905. cli.enable_server_certificate_verification(false);
  14906. auto res = cli.Get("/test-pem-ca");
  14907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14908. EXPECT_EQ(200, res->status);
  14909. EXPECT_EQ("ok", res->body);
  14910. svr.stop();
  14911. server_thread.join();
  14912. }
  14913. #endif
  14914. #ifdef _WIN32
  14915. TEST(CleanupTest, WSACleanup) {
  14916. int ret = WSACleanup();
  14917. ASSERT_EQ(0, ret);
  14918. }
  14919. #endif
  14920. #ifndef CPPHTTPLIB_SSL_ENABLED
  14921. TEST(NoSSLSupport, SimpleInterface) {
  14922. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14923. }
  14924. #endif
  14925. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14926. TEST(InvalidScheme, SimpleInterface) {
  14927. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14928. }
  14929. #endif
  14930. TEST(NoScheme, SimpleInterface) {
  14931. Client cli("yahoo.com:80");
  14932. ASSERT_TRUE(cli.is_valid());
  14933. }
  14934. TEST(SendAPI, SimpleInterface_Online) {
  14935. Client cli("http://yahoo.com");
  14936. Request req;
  14937. req.method = "GET";
  14938. req.path = "/";
  14939. auto res = cli.send(req);
  14940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14941. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14942. }
  14943. TEST(SendAPI, WithParamsInRequest) {
  14944. Server svr;
  14945. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14946. EXPECT_TRUE(req.has_param("test"));
  14947. EXPECT_EQ("test_value", req.get_param_value("test"));
  14948. });
  14949. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14950. auto se = detail::scope_exit([&] {
  14951. svr.stop();
  14952. t.join();
  14953. ASSERT_FALSE(svr.is_running());
  14954. });
  14955. svr.wait_until_ready();
  14956. Client cli(HOST, PORT);
  14957. {
  14958. Request req;
  14959. req.method = "GET";
  14960. req.path = "/";
  14961. req.params.emplace("test", "test_value");
  14962. auto res = cli.send(req);
  14963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14964. }
  14965. {
  14966. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14968. }
  14969. }
  14970. TEST(ClientImplMethods, GetSocketTest) {
  14971. httplib::Server svr;
  14972. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14973. res.status = StatusCode::OK_200;
  14974. });
  14975. auto port = svr.bind_to_any_port("127.0.0.1");
  14976. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14977. auto se = detail::scope_exit([&] {
  14978. svr.stop();
  14979. thread.join();
  14980. ASSERT_FALSE(svr.is_running());
  14981. });
  14982. svr.wait_until_ready();
  14983. {
  14984. httplib::Client cli("127.0.0.1", port);
  14985. cli.set_keep_alive(true);
  14986. // Use the behavior of cpp-httplib of opening the connection
  14987. // only when the first request happens. If that changes,
  14988. // this test would be obsolete.
  14989. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14990. // This also implicitly tests the server. But other tests would fail much
  14991. // earlier than this one to be considered.
  14992. auto res = cli.Get("/");
  14993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14994. EXPECT_EQ(StatusCode::OK_200, res->status);
  14995. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14996. }
  14997. }
  14998. #ifdef CPPHTTPLIB_SSL_ENABLED
  14999. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15000. Client cli("http://yahoo.com");
  15001. auto res = cli.Get("/");
  15002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15003. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15004. cli.set_follow_location(true);
  15005. res = cli.Get("/");
  15006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15007. EXPECT_EQ(StatusCode::OK_200, res->status);
  15008. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15009. }
  15010. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15011. Client cli("https://yahoo.com");
  15012. auto res = cli.Get("/");
  15013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15014. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15015. cli.set_follow_location(true);
  15016. res = cli.Get("/");
  15017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15018. EXPECT_EQ(StatusCode::OK_200, res->status);
  15019. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15020. }
  15021. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15022. Client cli("https://yahoo.com");
  15023. auto res = cli.Get("/");
  15024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15025. ASSERT_FALSE(!res);
  15026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15027. ASSERT_FALSE(res == nullptr);
  15028. ASSERT_TRUE(res != nullptr);
  15029. EXPECT_EQ(Error::Success, res.error());
  15030. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15031. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15032. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15033. cli.set_follow_location(true);
  15034. res = cli.Get("/");
  15035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15036. EXPECT_EQ(Error::Success, res.error());
  15037. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15038. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15039. EXPECT_EQ(StatusCode::OK_200, res->status);
  15040. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15041. }
  15042. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15043. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15044. Client cli("https://cdnjs.cloudflare.com");
  15045. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15046. Headers{{"Accept-Encoding", "br"}});
  15047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15048. EXPECT_EQ(StatusCode::OK_200, res->status);
  15049. EXPECT_EQ(287630U, res->body.size());
  15050. EXPECT_EQ("application/javascript; charset=utf-8",
  15051. res->get_header_value("Content-Type"));
  15052. }
  15053. #endif
  15054. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15055. #undef REDIR_HOST // Silence compiler warning
  15056. #define REDIR_HOST "https://httpbingo.org"
  15057. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15058. Client cli(REDIR_HOST);
  15059. cli.set_follow_location(true);
  15060. auto res =
  15061. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15063. EXPECT_EQ(StatusCode::OK_200, res->status);
  15064. }
  15065. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15066. Client cli(REDIR_HOST);
  15067. cli.set_follow_location(true);
  15068. Params params;
  15069. params.emplace("url", "http://example.com");
  15070. params.emplace("status_code", "302");
  15071. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15073. EXPECT_EQ(StatusCode::OK_200, res->status);
  15074. }
  15075. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15076. Client cli(REDIR_HOST);
  15077. cli.set_follow_location(true);
  15078. Params params;
  15079. params.emplace("url", "http://example.com");
  15080. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15082. EXPECT_EQ(StatusCode::OK_200, res->status);
  15083. }
  15084. TEST(HttpToHttpsRedirectTest, CertFile) {
  15085. auto ssl_port = PORT + 1;
  15086. Server svr;
  15087. ASSERT_TRUE(svr.is_valid());
  15088. svr.Get("/index", [&](const Request &, Response &res) {
  15089. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15090. "/index");
  15091. svr.stop();
  15092. });
  15093. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15094. ASSERT_TRUE(ssl_svr.is_valid());
  15095. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15096. res.set_content("test", "text/plain");
  15097. ssl_svr.stop();
  15098. });
  15099. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15100. thread t2 =
  15101. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15102. auto se = detail::scope_exit([&] {
  15103. t2.join();
  15104. t.join();
  15105. ASSERT_FALSE(svr.is_running());
  15106. });
  15107. svr.wait_until_ready();
  15108. ssl_svr.wait_until_ready();
  15109. Client cli("127.0.0.1", PORT);
  15110. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15111. cli.enable_server_certificate_verification(true);
  15112. cli.set_follow_location(true);
  15113. cli.set_connection_timeout(30);
  15114. auto res = cli.Get("/index");
  15115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15116. ASSERT_EQ(StatusCode::OK_200, res->status);
  15117. }
  15118. TEST(SSLClientRedirectTest, CertFile) {
  15119. auto ssl_port = PORT + 1;
  15120. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15121. ASSERT_TRUE(ssl_svr1.is_valid());
  15122. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15123. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15124. "/index");
  15125. ssl_svr1.stop();
  15126. });
  15127. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15128. ASSERT_TRUE(ssl_svr2.is_valid());
  15129. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15130. res.set_content("test", "text/plain");
  15131. ssl_svr2.stop();
  15132. });
  15133. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15134. thread t2 =
  15135. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15136. auto se = detail::scope_exit([&] {
  15137. t2.join();
  15138. t.join();
  15139. ASSERT_FALSE(ssl_svr1.is_running());
  15140. });
  15141. ssl_svr1.wait_until_ready();
  15142. ssl_svr2.wait_until_ready();
  15143. SSLClient cli("127.0.0.1", PORT);
  15144. std::string cert;
  15145. read_file(SERVER_CERT2_FILE, cert);
  15146. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15147. cli.enable_server_certificate_verification(true);
  15148. cli.set_follow_location(true);
  15149. cli.set_connection_timeout(30);
  15150. auto res = cli.Get("/index");
  15151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15152. ASSERT_EQ(StatusCode::OK_200, res->status);
  15153. }
  15154. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15155. // another port, so the client follows it with a new client.
  15156. static Result GetThroughTlsRedirectToDifferentPort(
  15157. const std::function<void(SSLClient &)> &setup,
  15158. const char *target_cert = SERVER_CERT2_FILE,
  15159. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15160. auto ssl_port = PORT + 1;
  15161. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15162. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15163. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15164. "/index");
  15165. });
  15166. SSLServer ssl_svr2(target_cert, target_key);
  15167. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15168. res.set_content("test", "text/plain");
  15169. });
  15170. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15171. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15172. auto se = detail::scope_exit([&] {
  15173. ssl_svr2.stop();
  15174. ssl_svr1.stop();
  15175. t2.join();
  15176. t.join();
  15177. });
  15178. ssl_svr1.wait_until_ready();
  15179. ssl_svr2.wait_until_ready();
  15180. SSLClient cli("127.0.0.1", PORT);
  15181. cli.set_follow_location(true);
  15182. cli.set_connection_timeout(30);
  15183. setup(cli);
  15184. return cli.Get("/index");
  15185. }
  15186. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15187. auto calls = 0;
  15188. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15189. cli.enable_server_certificate_verification(false);
  15190. // Accept the first server only.
  15191. cli.set_session_verifier([&](tls::session_t) {
  15192. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15193. : SSLVerifierResponse::CertificateRejected;
  15194. });
  15195. });
  15196. ASSERT_FALSE(res);
  15197. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15198. EXPECT_EQ(2, calls);
  15199. }
  15200. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15201. std::string pinned;
  15202. auto res = GetThroughTlsRedirectToDifferentPort(
  15203. [&](SSLClient &cli) {
  15204. cli.enable_server_certificate_verification(false);
  15205. // Pin the first certificate seen.
  15206. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15207. if (pinned.empty()) { pinned = ctx.serial(); }
  15208. return ctx.serial() == pinned;
  15209. });
  15210. },
  15211. // A certificate other than the first server's.
  15212. SERVER_CERT_FILE);
  15213. EXPECT_FALSE(res);
  15214. EXPECT_FALSE(pinned.empty());
  15215. }
  15216. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15217. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15218. std::string cert;
  15219. read_file(SERVER_CERT2_FILE, cert);
  15220. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15221. });
  15222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15223. EXPECT_EQ(StatusCode::OK_200, res->status);
  15224. }
  15225. // The target's certificate is signed by the root CA, which the first server's
  15226. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15227. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15228. auto res = GetThroughTlsRedirectToDifferentPort(
  15229. [](SSLClient &cli) {
  15230. std::string root_ca, cert;
  15231. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15232. read_file(SERVER_CERT2_FILE, cert);
  15233. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15234. cli.load_ca_cert_store(cert.data(), cert.size());
  15235. cli.enable_server_hostname_verification(false);
  15236. },
  15237. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15239. EXPECT_EQ(StatusCode::OK_200, res->status);
  15240. }
  15241. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15242. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15243. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15244. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15245. auto res = GetThroughTlsRedirectToDifferentPort(
  15246. [](SSLClient &cli) {
  15247. std::string root_ca, cert;
  15248. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15249. read_file(SERVER_CERT2_FILE, cert);
  15250. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15251. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15252. cli.enable_server_hostname_verification(false);
  15253. },
  15254. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15255. ASSERT_FALSE(res);
  15256. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15257. }
  15258. #endif
  15259. #endif
  15260. #ifdef CPPHTTPLIB_SSL_ENABLED
  15261. // Test that set_ca_cert_store() skips system certs (consistent with
  15262. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15263. // should be trusted - system certs should NOT be loaded.
  15264. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15265. // Load a specific cert that is NOT a system CA cert
  15266. std::string cert;
  15267. read_file(SERVER_CERT2_FILE, cert);
  15268. SSLClient cli("google.com");
  15269. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15270. cli.enable_server_certificate_verification(true);
  15271. // This should FAIL because:
  15272. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15273. // 2. System certs should NOT be loaded when custom store is set
  15274. // If system certs WERE loaded, this would succeed
  15275. auto res = cli.Get("/");
  15276. ASSERT_FALSE(res);
  15277. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15278. }
  15279. // Same as above, but through the native store handle path. Regression test:
  15280. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15281. // merged system certs into the user-provided store.
  15282. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15283. std::string cert;
  15284. read_file(SERVER_CERT2_FILE, cert);
  15285. SSLClient cli("google.com");
  15286. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15287. cli.enable_server_certificate_verification(true);
  15288. auto res = cli.Get("/");
  15289. ASSERT_FALSE(res);
  15290. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15291. }
  15292. // A custom store set via the native handle must still verify a server whose
  15293. // cert it does contain.
  15294. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15295. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15296. ASSERT_TRUE(svr.is_valid());
  15297. svr.Get("/test", [&](const Request &, Response &res) {
  15298. res.set_content("test", "text/plain");
  15299. });
  15300. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15301. auto se = detail::scope_exit([&] {
  15302. svr.stop();
  15303. t.join();
  15304. ASSERT_FALSE(svr.is_running());
  15305. });
  15306. svr.wait_until_ready();
  15307. SSLClient cli("127.0.0.1", PORT);
  15308. std::string cert;
  15309. read_file(SERVER_CERT2_FILE, cert);
  15310. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15311. cli.enable_server_certificate_verification(true);
  15312. cli.set_connection_timeout(30);
  15313. auto res = cli.Get("/test");
  15314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15315. ASSERT_EQ(StatusCode::OK_200, res->status);
  15316. }
  15317. // CA certs loaded through the universal Client must be transferred to the
  15318. // client created internally for following an HTTPS redirect. Regression test:
  15319. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15320. // the CA data for redirect transfer.
  15321. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15322. auto ssl_port = PORT + 1;
  15323. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15324. ASSERT_TRUE(ssl_svr1.is_valid());
  15325. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15326. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15327. "/index");
  15328. });
  15329. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15330. ASSERT_TRUE(ssl_svr2.is_valid());
  15331. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15332. res.set_content("test", "text/plain");
  15333. });
  15334. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15335. thread t2 =
  15336. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15337. auto se = detail::scope_exit([&] {
  15338. ssl_svr2.stop();
  15339. ssl_svr1.stop();
  15340. t2.join();
  15341. t.join();
  15342. ASSERT_FALSE(ssl_svr1.is_running());
  15343. });
  15344. ssl_svr1.wait_until_ready();
  15345. ssl_svr2.wait_until_ready();
  15346. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15347. std::string cert;
  15348. read_file(SERVER_CERT2_FILE, cert);
  15349. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15350. cli.enable_server_certificate_verification(true);
  15351. cli.set_follow_location(true);
  15352. cli.set_connection_timeout(30);
  15353. auto res = cli.Get("/index");
  15354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15355. ASSERT_EQ(StatusCode::OK_200, res->status);
  15356. }
  15357. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15358. // so a host signed by a system CA verifies even though a custom CA is set
  15359. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15360. std::string cert;
  15361. read_file(SERVER_CERT2_FILE, cert);
  15362. SSLClient cli("google.com");
  15363. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15364. cli.enable_system_ca(true);
  15365. cli.enable_server_certificate_verification(true);
  15366. auto res = cli.Get("/");
  15367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15368. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15369. }
  15370. // The custom CA remains effective when combined with the system CA
  15371. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15372. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15373. ASSERT_TRUE(svr.is_valid());
  15374. svr.Get("/test", [&](const Request &, Response &res) {
  15375. res.set_content("test", "text/plain");
  15376. });
  15377. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15378. auto se = detail::scope_exit([&] {
  15379. svr.stop();
  15380. t.join();
  15381. ASSERT_FALSE(svr.is_running());
  15382. });
  15383. svr.wait_until_ready();
  15384. SSLClient cli("127.0.0.1", PORT);
  15385. std::string cert;
  15386. read_file(SERVER_CERT2_FILE, cert);
  15387. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15388. cli.enable_system_ca(true);
  15389. cli.enable_server_certificate_verification(true);
  15390. cli.set_connection_timeout(30);
  15391. auto res = cli.Get("/test");
  15392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15393. ASSERT_EQ(StatusCode::OK_200, res->status);
  15394. }
  15395. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15396. // skip chain verification entirely (only the certificate identity was
  15397. // checked), so a server presenting an untrusted certificate with a matching
  15398. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15399. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15400. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15401. ASSERT_TRUE(svr.is_valid());
  15402. svr.Get("/test", [&](const Request &, Response &res) {
  15403. res.set_content("test", "text/plain");
  15404. });
  15405. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15406. auto se = detail::scope_exit([&] {
  15407. svr.stop();
  15408. t.join();
  15409. ASSERT_FALSE(svr.is_running());
  15410. });
  15411. svr.wait_until_ready();
  15412. SSLClient cli("127.0.0.1", PORT);
  15413. std::string cert;
  15414. // A trusted CA that did not sign the server certificate. The server cert
  15415. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15416. // this connection.
  15417. read_file(CLIENT_CA_CERT_FILE, cert);
  15418. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15419. cli.enable_server_certificate_verification(true);
  15420. cli.set_connection_timeout(30);
  15421. auto res = cli.Get("/test");
  15422. ASSERT_FALSE(res);
  15423. }
  15424. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15425. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15426. // CA that failed to come through fails verification instead of trusting them.
  15427. // (wolfSSL does not list the system CAs it loaded.)
  15428. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15429. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15430. ASSERT_TRUE(svr.is_valid());
  15431. auto port = svr.bind_to_any_port("127.0.0.1");
  15432. ASSERT_LT(0, port);
  15433. thread t = thread([&] { svr.listen_after_bind(); });
  15434. auto se = detail::scope_exit([&] {
  15435. svr.stop();
  15436. t.join();
  15437. ASSERT_FALSE(svr.is_running());
  15438. });
  15439. svr.wait_until_ready();
  15440. // The CAs a client trusts once its first request has loaded them
  15441. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15442. Client cli("https://127.0.0.1:" + std::to_string(port));
  15443. setup(cli);
  15444. cli.Get("/");
  15445. return tls::get_ca_names(cli.tls_context()).size();
  15446. };
  15447. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15448. EXPECT_EQ(0u,
  15449. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15450. }
  15451. #endif
  15452. // A TLS setting changed between requests applies to the next one, not just to
  15453. // the next connection
  15454. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15455. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15456. ASSERT_TRUE(svr.is_valid());
  15457. svr.Get("/", [](const Request &req, Response &res) {
  15458. res.set_content(std::to_string(req.remote_port), "text/plain");
  15459. });
  15460. auto port = svr.bind_to_any_port("127.0.0.1");
  15461. ASSERT_LT(0, port);
  15462. thread t = thread([&] { svr.listen_after_bind(); });
  15463. auto se = detail::scope_exit([&] {
  15464. svr.stop();
  15465. t.join();
  15466. ASSERT_FALSE(svr.is_running());
  15467. });
  15468. svr.wait_until_ready();
  15469. SSLClient cli("127.0.0.1", port);
  15470. cli.set_keep_alive(true);
  15471. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15472. cli.enable_server_certificate_verification(false);
  15473. // The port the request went out from, so a new one means a new connection
  15474. auto client_port = [&] {
  15475. auto res = cli.Get("/");
  15476. return res ? res->body : std::string();
  15477. };
  15478. auto last = client_port();
  15479. ASSERT_FALSE(last.empty());
  15480. // Setting a value it already has keeps the connection
  15481. cli.enable_server_certificate_verification(false);
  15482. cli.enable_server_hostname_verification(true);
  15483. EXPECT_EQ(last, client_port());
  15484. cli.enable_server_certificate_verification(true);
  15485. auto res = cli.Get("/");
  15486. EXPECT_FALSE(res);
  15487. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15488. std::string ca;
  15489. read_file(SERVER_CERT2_FILE, ca);
  15490. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15491. last = client_port();
  15492. ASSERT_FALSE(last.empty());
  15493. std::vector<std::function<void()>> setters = {
  15494. [&] { cli.enable_server_hostname_verification(false); },
  15495. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15496. [&] {
  15497. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15498. },
  15499. [&] {
  15500. cli.set_server_certificate_verifier(
  15501. [](const tls::VerifyContext &) { return true; });
  15502. },
  15503. [&] {
  15504. cli.set_session_verifier(
  15505. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15506. },
  15507. };
  15508. for (const auto &setter : setters) {
  15509. setter();
  15510. auto next = client_port();
  15511. ASSERT_FALSE(next.empty());
  15512. EXPECT_NE(last, next);
  15513. last = next;
  15514. }
  15515. cli.set_session_verifier(
  15516. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15517. auto handle = cli.open_stream("GET", "/");
  15518. EXPECT_FALSE(handle.is_valid());
  15519. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15520. }
  15521. // A PEM given to create_ca_store() needs no NUL after it
  15522. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15523. std::string pem;
  15524. read_file(SERVER_CERT2_FILE, pem);
  15525. auto buf = pem + "X";
  15526. auto store = tls::create_ca_store(buf.data(), pem.size());
  15527. EXPECT_TRUE(store != nullptr);
  15528. SSLClient cli("localhost");
  15529. cli.set_ca_cert_store(store);
  15530. }
  15531. // enable_system_ca(false) prevents system CA loading entirely
  15532. TEST(SSLClientTest, DisableSystemCa_Online) {
  15533. SSLClient cli("google.com");
  15534. cli.enable_system_ca(false);
  15535. cli.enable_server_certificate_verification(true);
  15536. auto res = cli.Get("/");
  15537. ASSERT_FALSE(res);
  15538. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15539. // itself when the CA chain is empty
  15540. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15541. res.error() == Error::SSLConnection);
  15542. }
  15543. // The universal Client forwards enable_system_ca()
  15544. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15545. std::string cert;
  15546. read_file(SERVER_CERT2_FILE, cert);
  15547. Client cli("https://google.com");
  15548. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15549. cli.enable_system_ca(true);
  15550. cli.enable_server_certificate_verification(true);
  15551. auto res = cli.Get("/");
  15552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15553. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15554. }
  15555. // The system CA policy must carry over to the client created internally for
  15556. // following a cross-host HTTPS redirect
  15557. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15558. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15559. ASSERT_TRUE(svr.is_valid());
  15560. svr.Get("/index", [&](const Request &, Response &res) {
  15561. res.set_redirect("https://www.google.com/");
  15562. });
  15563. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15564. auto se = detail::scope_exit([&] {
  15565. svr.stop();
  15566. t.join();
  15567. ASSERT_FALSE(svr.is_running());
  15568. });
  15569. svr.wait_until_ready();
  15570. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15571. std::string cert;
  15572. read_file(SERVER_CERT2_FILE, cert);
  15573. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15574. cli.enable_system_ca(true);
  15575. cli.enable_server_certificate_verification(true);
  15576. cli.set_follow_location(true);
  15577. cli.set_connection_timeout(30);
  15578. // Receiving any response proves the redirect client completed the TLS
  15579. // handshake with a system-CA-signed host
  15580. auto res = cli.Get("/index");
  15581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15582. }
  15583. TEST(MultipartFormDataTest, LargeData) {
  15584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15585. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15586. const ContentReader &content_reader) {
  15587. if (req.is_multipart_form_data()) {
  15588. std::vector<FormData> items;
  15589. content_reader(
  15590. [&](const FormData &file) {
  15591. items.push_back(file);
  15592. return true;
  15593. },
  15594. [&](const char *data, size_t data_length) {
  15595. items.back().content.append(data, data_length);
  15596. return true;
  15597. });
  15598. EXPECT_TRUE(std::string(items[0].name) == "document");
  15599. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15600. EXPECT_TRUE(items[0].filename == "2MB_data");
  15601. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15602. EXPECT_TRUE(items[1].name == "hello");
  15603. EXPECT_TRUE(items[1].content == "world");
  15604. EXPECT_TRUE(items[1].filename == "");
  15605. EXPECT_TRUE(items[1].content_type == "");
  15606. } else {
  15607. std::string body;
  15608. content_reader([&](const char *data, size_t data_length) {
  15609. body.append(data, data_length);
  15610. return true;
  15611. });
  15612. }
  15613. });
  15614. auto port = svr.bind_to_any_port(HOST);
  15615. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15616. auto se = detail::scope_exit([&] {
  15617. svr.stop();
  15618. t.join();
  15619. ASSERT_FALSE(svr.is_running());
  15620. });
  15621. svr.wait_until_ready();
  15622. {
  15623. std::string data(1024 * 1024 * 2, '.');
  15624. std::stringstream buffer;
  15625. buffer << data;
  15626. SSLClient cli(HOST, port);
  15627. cli.enable_server_certificate_verification(false);
  15628. UploadFormDataItems items{
  15629. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15630. {"hello", "world", "", ""},
  15631. };
  15632. auto res = cli.Post("/post", items);
  15633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15634. ASSERT_EQ(StatusCode::OK_200, res->status);
  15635. }
  15636. }
  15637. TEST(MultipartFormDataTest, DataProviderItems) {
  15638. std::random_device seed_gen;
  15639. std::mt19937 random(seed_gen());
  15640. std::string rand1;
  15641. rand1.resize(1000);
  15642. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15643. std::string rand2;
  15644. rand2.resize(3000);
  15645. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15647. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15648. const ContentReader &content_reader) {
  15649. ASSERT_FALSE(req.is_multipart_form_data());
  15650. std::string body;
  15651. content_reader([&](const char *data, size_t data_length) {
  15652. body.append(data, data_length);
  15653. return true;
  15654. });
  15655. EXPECT_EQ(body, "");
  15656. });
  15657. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15658. const ContentReader &content_reader) {
  15659. ASSERT_TRUE(req.is_multipart_form_data());
  15660. std::vector<FormData> items;
  15661. content_reader(
  15662. [&](const FormData &file) {
  15663. items.push_back(file);
  15664. return true;
  15665. },
  15666. [&](const char *data, size_t data_length) {
  15667. items.back().content.append(data, data_length);
  15668. return true;
  15669. });
  15670. ASSERT_TRUE(items.size() == 2);
  15671. EXPECT_EQ(std::string(items[0].name), "name1");
  15672. EXPECT_EQ(items[0].content, "Testing123");
  15673. EXPECT_EQ(items[0].filename, "filename1");
  15674. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15675. EXPECT_EQ(items[1].name, "name2");
  15676. EXPECT_EQ(items[1].content, "Testing456");
  15677. EXPECT_EQ(items[1].filename, "");
  15678. EXPECT_EQ(items[1].content_type, "");
  15679. });
  15680. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15681. const ContentReader &content_reader) {
  15682. ASSERT_TRUE(req.is_multipart_form_data());
  15683. std::vector<FormData> items;
  15684. content_reader(
  15685. [&](const FormData &file) {
  15686. items.push_back(file);
  15687. return true;
  15688. },
  15689. [&](const char *data, size_t data_length) {
  15690. items.back().content.append(data, data_length);
  15691. return true;
  15692. });
  15693. ASSERT_TRUE(items.size() == 2);
  15694. EXPECT_EQ(items[0].name, "name3");
  15695. EXPECT_EQ(items[0].content, rand1);
  15696. EXPECT_EQ(items[0].filename, "filename3");
  15697. EXPECT_EQ(items[0].content_type, "");
  15698. EXPECT_EQ(items[1].name, "name4");
  15699. EXPECT_EQ(items[1].content, rand2);
  15700. EXPECT_EQ(items[1].filename, "filename4");
  15701. EXPECT_EQ(items[1].content_type, "");
  15702. });
  15703. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15704. const ContentReader &content_reader) {
  15705. ASSERT_TRUE(req.is_multipart_form_data());
  15706. std::vector<FormData> items;
  15707. content_reader(
  15708. [&](const FormData &file) {
  15709. items.push_back(file);
  15710. return true;
  15711. },
  15712. [&](const char *data, size_t data_length) {
  15713. items.back().content.append(data, data_length);
  15714. return true;
  15715. });
  15716. ASSERT_TRUE(items.size() == 4);
  15717. EXPECT_EQ(std::string(items[0].name), "name1");
  15718. EXPECT_EQ(items[0].content, "Testing123");
  15719. EXPECT_EQ(items[0].filename, "filename1");
  15720. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15721. EXPECT_EQ(items[1].name, "name2");
  15722. EXPECT_EQ(items[1].content, "Testing456");
  15723. EXPECT_EQ(items[1].filename, "");
  15724. EXPECT_EQ(items[1].content_type, "");
  15725. EXPECT_EQ(items[2].name, "name3");
  15726. EXPECT_EQ(items[2].content, rand1);
  15727. EXPECT_EQ(items[2].filename, "filename3");
  15728. EXPECT_EQ(items[2].content_type, "");
  15729. EXPECT_EQ(items[3].name, "name4");
  15730. EXPECT_EQ(items[3].content, rand2);
  15731. EXPECT_EQ(items[3].filename, "filename4");
  15732. EXPECT_EQ(items[3].content_type, "");
  15733. });
  15734. auto port = svr.bind_to_any_port("localhost");
  15735. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15736. auto se = detail::scope_exit([&] {
  15737. svr.stop();
  15738. t.join();
  15739. ASSERT_FALSE(svr.is_running());
  15740. });
  15741. svr.wait_until_ready();
  15742. {
  15743. SSLClient cli("localhost", port);
  15744. cli.enable_server_certificate_verification(false);
  15745. UploadFormDataItems items{
  15746. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15747. {"name2", "Testing456", "", ""}, // not a file
  15748. };
  15749. {
  15750. auto res = cli.Post("/post-none", {}, {}, {});
  15751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15752. ASSERT_EQ(StatusCode::OK_200, res->status);
  15753. }
  15754. FormDataProviderItems providers;
  15755. {
  15756. auto res =
  15757. cli.Post("/post-items", {}, items, providers); // empty providers
  15758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15759. ASSERT_EQ(StatusCode::OK_200, res->status);
  15760. }
  15761. providers.push_back({"name3",
  15762. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15763. // test the offset is given correctly at each step
  15764. if (!offset)
  15765. sink.os.write(rand1.data(), 30);
  15766. else if (offset == 30)
  15767. sink.os.write(rand1.data() + 30, 300);
  15768. else if (offset == 330)
  15769. sink.os.write(rand1.data() + 330, 670);
  15770. else if (offset == rand1.size())
  15771. sink.done();
  15772. return true;
  15773. },
  15774. "filename3",
  15775. {}});
  15776. providers.push_back({"name4",
  15777. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15778. // test the offset is given correctly at each step
  15779. if (!offset)
  15780. sink.os.write(rand2.data(), 2000);
  15781. else if (offset == 2000)
  15782. sink.os.write(rand2.data() + 2000, 1);
  15783. else if (offset == 2001)
  15784. sink.os.write(rand2.data() + 2001, 999);
  15785. else if (offset == rand2.size())
  15786. sink.done();
  15787. return true;
  15788. },
  15789. "filename4",
  15790. {}});
  15791. {
  15792. auto res = cli.Post("/post-providers", {}, {}, providers);
  15793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15794. ASSERT_EQ(StatusCode::OK_200, res->status);
  15795. }
  15796. {
  15797. auto res = cli.Post("/post-both", {}, items, providers);
  15798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15799. ASSERT_EQ(StatusCode::OK_200, res->status);
  15800. }
  15801. }
  15802. }
  15803. TEST(MultipartFormDataTest, BadHeader) {
  15804. Server svr;
  15805. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15806. res.set_content("ok", "text/plain");
  15807. });
  15808. thread t = thread([&] { svr.listen(HOST, PORT); });
  15809. auto se = detail::scope_exit([&] {
  15810. svr.stop();
  15811. t.join();
  15812. ASSERT_FALSE(svr.is_running());
  15813. });
  15814. svr.wait_until_ready();
  15815. const std::string body =
  15816. "This is the preamble. It is to be ignored, though it\r\n"
  15817. "is a handy place for composition agents to include an\r\n"
  15818. "explanatory note to non-MIME conformant readers.\r\n"
  15819. "\r\n"
  15820. "\r\n"
  15821. "--simple boundary\r\n"
  15822. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15823. ": BAD...\r\n"
  15824. "\r\n"
  15825. "value1\r\n"
  15826. "--simple boundary\r\n"
  15827. "Content-Disposition: form-data; name=\"field2\"; "
  15828. "filename=\"example.txt\"\r\n"
  15829. "\r\n"
  15830. "value2\r\n"
  15831. "--simple boundary--\r\n"
  15832. "This is the epilogue. It is also to be ignored.\r\n";
  15833. std::string content_type =
  15834. R"(multipart/form-data; boundary="simple boundary")";
  15835. Client cli(HOST, PORT);
  15836. auto res = cli.Post("/post", body, content_type.c_str());
  15837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15838. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15839. }
  15840. TEST(MultipartFormDataTest, WithPreamble) {
  15841. Server svr;
  15842. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15843. res.set_content("ok", "text/plain");
  15844. });
  15845. thread t = thread([&] { svr.listen(HOST, PORT); });
  15846. auto se = detail::scope_exit([&] {
  15847. svr.stop();
  15848. t.join();
  15849. ASSERT_FALSE(svr.is_running());
  15850. });
  15851. svr.wait_until_ready();
  15852. const std::string body =
  15853. "This is the preamble. It is to be ignored, though it\r\n"
  15854. "is a handy place for composition agents to include an\r\n"
  15855. "explanatory note to non-MIME conformant readers.\r\n"
  15856. "\r\n"
  15857. "\r\n"
  15858. "--simple boundary\r\n"
  15859. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15860. "\r\n"
  15861. "value1\r\n"
  15862. "--simple boundary\r\n"
  15863. "Content-Disposition: form-data; name=\"field2\"; "
  15864. "filename=\"example.txt\"\r\n"
  15865. "\r\n"
  15866. "value2\r\n"
  15867. "--simple boundary--\r\n"
  15868. "This is the epilogue. It is also to be ignored.\r\n";
  15869. std::string content_type =
  15870. R"(multipart/form-data; boundary="simple boundary")";
  15871. Client cli(HOST, PORT);
  15872. auto res = cli.Post("/post", body, content_type.c_str());
  15873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15874. EXPECT_EQ(StatusCode::OK_200, res->status);
  15875. }
  15876. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15878. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15879. const ContentReader &content_reader) {
  15880. if (req.is_multipart_form_data()) {
  15881. std::vector<FormData> items;
  15882. content_reader(
  15883. [&](const FormData &file) {
  15884. items.push_back(file);
  15885. return true;
  15886. },
  15887. [&](const char *data, size_t data_length) {
  15888. items.back().content.append(data, data_length);
  15889. return true;
  15890. });
  15891. EXPECT_TRUE(std::string(items[0].name) == "document");
  15892. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15893. EXPECT_TRUE(items[0].filename == "2MB_data");
  15894. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15895. EXPECT_TRUE(items[1].name == "hello");
  15896. EXPECT_TRUE(items[1].content == "world");
  15897. EXPECT_TRUE(items[1].filename == "");
  15898. EXPECT_TRUE(items[1].content_type == "");
  15899. } else {
  15900. std::string body;
  15901. content_reader([&](const char *data, size_t data_length) {
  15902. body.append(data, data_length);
  15903. return true;
  15904. });
  15905. }
  15906. });
  15907. auto port = svr.bind_to_any_port("localhost");
  15908. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15909. auto se = detail::scope_exit([&] {
  15910. svr.stop();
  15911. t.join();
  15912. ASSERT_FALSE(svr.is_running());
  15913. });
  15914. svr.wait_until_ready();
  15915. {
  15916. std::string data(1024 * 1024 * 2, '.');
  15917. std::stringstream buffer;
  15918. buffer << data;
  15919. SSLClient cli("localhost", port);
  15920. cli.enable_server_certificate_verification(false);
  15921. UploadFormDataItems items{
  15922. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15923. {"hello", "world", "", ""},
  15924. };
  15925. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15927. ASSERT_EQ(StatusCode::OK_200, res->status);
  15928. }
  15929. }
  15930. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15931. std::string data(1024 * 1024 * 2, '&');
  15932. std::stringstream buffer;
  15933. buffer << data;
  15934. Client cli("https://localhost:8080");
  15935. UploadFormDataItems items{
  15936. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15937. {"hello", "world", "", ""},
  15938. };
  15939. for (const char &c : " \t\r\n") {
  15940. auto res =
  15941. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15942. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15943. ASSERT_FALSE(res);
  15944. }
  15945. }
  15946. TEST(MultipartFormDataTest, PutFormData) {
  15947. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15948. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15949. const ContentReader &content_reader) {
  15950. if (req.is_multipart_form_data()) {
  15951. std::vector<FormData> items;
  15952. content_reader(
  15953. [&](const FormData &file) {
  15954. items.push_back(file);
  15955. return true;
  15956. },
  15957. [&](const char *data, size_t data_length) {
  15958. items.back().content.append(data, data_length);
  15959. return true;
  15960. });
  15961. EXPECT_TRUE(std::string(items[0].name) == "document");
  15962. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15963. EXPECT_TRUE(items[0].filename == "2MB_data");
  15964. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15965. EXPECT_TRUE(items[1].name == "hello");
  15966. EXPECT_TRUE(items[1].content == "world");
  15967. EXPECT_TRUE(items[1].filename == "");
  15968. EXPECT_TRUE(items[1].content_type == "");
  15969. } else {
  15970. std::string body;
  15971. content_reader([&](const char *data, size_t data_length) {
  15972. body.append(data, data_length);
  15973. return true;
  15974. });
  15975. }
  15976. });
  15977. auto port = svr.bind_to_any_port("localhost");
  15978. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15979. auto se = detail::scope_exit([&] {
  15980. svr.stop();
  15981. t.join();
  15982. ASSERT_FALSE(svr.is_running());
  15983. });
  15984. svr.wait_until_ready();
  15985. {
  15986. std::string data(1024 * 1024 * 2, '&');
  15987. std::stringstream buffer;
  15988. buffer << data;
  15989. SSLClient cli("localhost", port);
  15990. cli.enable_server_certificate_verification(false);
  15991. UploadFormDataItems items{
  15992. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15993. {"hello", "world", "", ""},
  15994. };
  15995. auto res = cli.Put("/put", items);
  15996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15997. ASSERT_EQ(StatusCode::OK_200, res->status);
  15998. }
  15999. }
  16000. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16002. svr.Put("/put_customboundary",
  16003. [&](const Request &req, const Response & /*res*/,
  16004. const ContentReader &content_reader) {
  16005. if (req.is_multipart_form_data()) {
  16006. std::vector<FormData> items;
  16007. content_reader(
  16008. [&](const FormData &file) {
  16009. items.push_back(file);
  16010. return true;
  16011. },
  16012. [&](const char *data, size_t data_length) {
  16013. items.back().content.append(data, data_length);
  16014. return true;
  16015. });
  16016. EXPECT_TRUE(std::string(items[0].name) == "document");
  16017. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16018. EXPECT_TRUE(items[0].filename == "2MB_data");
  16019. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16020. EXPECT_TRUE(items[1].name == "hello");
  16021. EXPECT_TRUE(items[1].content == "world");
  16022. EXPECT_TRUE(items[1].filename == "");
  16023. EXPECT_TRUE(items[1].content_type == "");
  16024. } else {
  16025. std::string body;
  16026. content_reader([&](const char *data, size_t data_length) {
  16027. body.append(data, data_length);
  16028. return true;
  16029. });
  16030. }
  16031. });
  16032. auto port = svr.bind_to_any_port("localhost");
  16033. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16034. auto se = detail::scope_exit([&] {
  16035. svr.stop();
  16036. t.join();
  16037. ASSERT_FALSE(svr.is_running());
  16038. });
  16039. svr.wait_until_ready();
  16040. {
  16041. std::string data(1024 * 1024 * 2, '&');
  16042. std::stringstream buffer;
  16043. buffer << data;
  16044. SSLClient cli("localhost", port);
  16045. cli.enable_server_certificate_verification(false);
  16046. UploadFormDataItems items{
  16047. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16048. {"hello", "world", "", ""},
  16049. };
  16050. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16052. ASSERT_EQ(StatusCode::OK_200, res->status);
  16053. }
  16054. }
  16055. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16056. std::string data(1024 * 1024 * 2, '&');
  16057. std::stringstream buffer;
  16058. buffer << data;
  16059. Client cli("https://localhost:8080");
  16060. cli.enable_server_certificate_verification(false);
  16061. UploadFormDataItems items{
  16062. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16063. {"hello", "world", "", ""},
  16064. };
  16065. for (const char &c : " \t\r\n") {
  16066. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16067. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16068. ASSERT_FALSE(res);
  16069. }
  16070. }
  16071. TEST(MultipartFormDataTest, AlternateFilename) {
  16072. auto handled = false;
  16073. Server svr;
  16074. svr.Post("/test", [&](const Request &req, Response &res) {
  16075. ASSERT_EQ(2u, req.form.files.size());
  16076. ASSERT_EQ(1u, req.form.fields.size());
  16077. // Test files
  16078. const auto &file1 = req.form.get_file("file1");
  16079. ASSERT_EQ("file1", file1.name);
  16080. ASSERT_EQ("A.txt", file1.filename);
  16081. ASSERT_EQ("text/plain", file1.content_type);
  16082. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16083. const auto &file2 = req.form.get_file("file2");
  16084. ASSERT_EQ("file2", file2.name);
  16085. ASSERT_EQ("a.html", file2.filename);
  16086. ASSERT_EQ("text/html", file2.content_type);
  16087. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16088. file2.content);
  16089. // Test text field
  16090. const auto &text = req.form.get_field("text");
  16091. ASSERT_EQ("text default", text);
  16092. res.set_content("ok", "text/plain");
  16093. handled = true;
  16094. });
  16095. thread t = thread([&] { svr.listen(HOST, PORT); });
  16096. auto se = detail::scope_exit([&] {
  16097. svr.stop();
  16098. t.join();
  16099. ASSERT_FALSE(svr.is_running());
  16100. ASSERT_TRUE(handled);
  16101. });
  16102. svr.wait_until_ready();
  16103. auto req = "POST /test HTTP/1.1\r\n"
  16104. "Host: localhost\r\n"
  16105. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16106. "Content-Length: 399\r\n"
  16107. "\r\n"
  16108. "----------\r\n"
  16109. "Content-Disposition: form-data; name=\"text\"\r\n"
  16110. "\r\n"
  16111. "text default\r\n"
  16112. "----------\r\n"
  16113. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16114. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16115. "Content-Type: text/plain\r\n"
  16116. "\r\n"
  16117. "Content of a.txt.\r\n"
  16118. "\r\n"
  16119. "----------\r\n"
  16120. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16121. "\"a.html\"\r\n"
  16122. "Content-Type: text/html\r\n"
  16123. "\r\n"
  16124. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16125. "\r\n"
  16126. "------------\r\n";
  16127. ASSERT_TRUE(send_request(1, req));
  16128. }
  16129. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16130. auto handled = false;
  16131. Server svr;
  16132. svr.Post("/test", [&](const Request &req, Response &res) {
  16133. // Case-insensitive "utf-8''" prefix with a long value
  16134. const auto &file = req.form.get_file("file1");
  16135. ASSERT_EQ("file1", file.name);
  16136. // 8000 chars exercises both the Content-Disposition parser and the
  16137. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16138. // Prior to the fix, std::regex_match on this header would cause O(N)
  16139. // stack recursion in libstdc++, leading to SIGSEGV.
  16140. std::string expected_filename(8000, 'A');
  16141. ASSERT_EQ(expected_filename, file.filename);
  16142. res.set_content("ok", "text/plain");
  16143. handled = true;
  16144. });
  16145. thread t = thread([&] { svr.listen(HOST, PORT); });
  16146. auto se = detail::scope_exit([&] {
  16147. svr.stop();
  16148. t.join();
  16149. ASSERT_FALSE(svr.is_running());
  16150. ASSERT_TRUE(handled);
  16151. });
  16152. svr.wait_until_ready();
  16153. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16154. // Regression test for GHSA-qq6v-r583-3h69
  16155. std::string long_filename(8000, 'A');
  16156. std::string body = "----------\r\n"
  16157. "Content-Disposition: form-data; name=\"file1\"; "
  16158. "filename*=\"Utf-8''" +
  16159. long_filename +
  16160. "\"\r\n"
  16161. "\r\n"
  16162. "hello\r\n"
  16163. "------------\r\n";
  16164. auto req = "POST /test HTTP/1.1\r\n"
  16165. "Host: localhost\r\n"
  16166. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16167. "Content-Length: " +
  16168. std::to_string(body.size()) + "\r\n\r\n" + body;
  16169. ASSERT_TRUE(send_request(1, req));
  16170. }
  16171. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16172. auto handled = false;
  16173. Server svr;
  16174. svr.Post("/test", [&](const Request &req, Response &) {
  16175. ASSERT_EQ(2u, req.form.fields.size());
  16176. const auto &text1 = req.form.get_field("text1");
  16177. ASSERT_EQ("text1", text1);
  16178. const auto &text2 = req.form.get_field("text2");
  16179. ASSERT_EQ("text2", text2);
  16180. handled = true;
  16181. });
  16182. thread t = thread([&] { svr.listen(HOST, PORT); });
  16183. auto se = detail::scope_exit([&] {
  16184. svr.stop();
  16185. t.join();
  16186. ASSERT_FALSE(svr.is_running());
  16187. ASSERT_TRUE(handled);
  16188. });
  16189. svr.wait_until_ready();
  16190. auto req = "POST /test HTTP/1.1\r\n"
  16191. "Host: localhost\r\n"
  16192. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16193. "Content-Length: 146\r\n"
  16194. "\r\n----------\r\n"
  16195. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16196. "\r\n"
  16197. "text1"
  16198. "\r\n----------\r\n"
  16199. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16200. "\r\n"
  16201. "text2"
  16202. "\r\n------------";
  16203. std::string response;
  16204. ASSERT_TRUE(send_request(1, req, &response));
  16205. ASSERT_EQ("200", response.substr(9, 3));
  16206. }
  16207. TEST(MultipartFormDataTest, ContentLength) {
  16208. auto handled = false;
  16209. Server svr;
  16210. svr.Post("/test", [&](const Request &req, Response &) {
  16211. ASSERT_EQ(2u, req.form.fields.size());
  16212. const auto &text1 = req.form.get_field("text1");
  16213. ASSERT_EQ("text1", text1);
  16214. const auto &text2 = req.form.get_field("text2");
  16215. ASSERT_EQ("text2", text2);
  16216. handled = true;
  16217. });
  16218. thread t = thread([&] { svr.listen(HOST, PORT); });
  16219. auto se = detail::scope_exit([&] {
  16220. svr.stop();
  16221. t.join();
  16222. ASSERT_FALSE(svr.is_running());
  16223. ASSERT_TRUE(handled);
  16224. });
  16225. svr.wait_until_ready();
  16226. auto req = "POST /test HTTP/1.1\r\n"
  16227. "Host: localhost\r\n"
  16228. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16229. "Content-Length: 167\r\n"
  16230. "\r\n----------\r\n"
  16231. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16232. "Content-Length: 5\r\n"
  16233. "\r\n"
  16234. "text1"
  16235. "\r\n----------\r\n"
  16236. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16237. "\r\n"
  16238. "text2"
  16239. "\r\n------------\r\n";
  16240. std::string response;
  16241. ASSERT_TRUE(send_request(1, req, &response));
  16242. ASSERT_EQ("200", response.substr(9, 3));
  16243. }
  16244. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16245. auto handled = false;
  16246. Server svr;
  16247. svr.Post("/test", [&](const Request &req, Response &) {
  16248. ASSERT_EQ(2u, req.form.fields.size());
  16249. const auto &text1 = req.form.get_field("text1");
  16250. ASSERT_EQ("text1", text1);
  16251. // TODO: Add header access for text fields if needed
  16252. const auto &text2 = req.form.get_field("text2");
  16253. ASSERT_EQ("text2", text2);
  16254. // TODO: Header access for text fields needs to be implemented
  16255. // auto &headers = it->second.headers;
  16256. // ASSERT_EQ(3U, headers.size());
  16257. // auto custom_header = headers.find("x-whatever");
  16258. // ASSERT_TRUE(custom_header != headers.end());
  16259. // ASSERT_NE("customvalue", custom_header->second);
  16260. // ASSERT_EQ("CustomValue", custom_header->second);
  16261. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16262. handled = true;
  16263. });
  16264. thread t = thread([&] { svr.listen(HOST, PORT); });
  16265. auto se = detail::scope_exit([&] {
  16266. svr.stop();
  16267. t.join();
  16268. ASSERT_FALSE(svr.is_running());
  16269. ASSERT_TRUE(handled);
  16270. });
  16271. svr.wait_until_ready();
  16272. auto req = "POST /test HTTP/1.1\r\n"
  16273. "Host: localhost\r\n"
  16274. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16275. "Content-Length: 232\r\n"
  16276. "\r\n----------\r\n"
  16277. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16278. "Content-Length: 5\r\n"
  16279. "X-Test: 1\r\n"
  16280. "\r\n"
  16281. "text1"
  16282. "\r\n----------\r\n"
  16283. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16284. "Content-Type: text/plain\r\n"
  16285. "X-Whatever: CustomValue\r\n"
  16286. "\r\n"
  16287. "text2"
  16288. "\r\n------------\r\n"
  16289. "That should be disregarded. Not even read";
  16290. std::string response;
  16291. ASSERT_TRUE(send_request(1, req, &response));
  16292. ASSERT_EQ("200", response.substr(9, 3));
  16293. }
  16294. TEST(MultipartFormDataTest, LargeHeader) {
  16295. auto handled = false;
  16296. Server svr;
  16297. svr.Post("/test", [&](const Request &req, Response &) {
  16298. ASSERT_EQ(1u, req.form.fields.size());
  16299. const auto &text = req.form.get_field("name1");
  16300. ASSERT_EQ("text1", text);
  16301. handled = true;
  16302. });
  16303. thread t = thread([&] { svr.listen(HOST, PORT); });
  16304. auto se = detail::scope_exit([&] {
  16305. svr.stop();
  16306. t.join();
  16307. ASSERT_FALSE(svr.is_running());
  16308. ASSERT_TRUE(handled);
  16309. });
  16310. svr.wait_until_ready();
  16311. auto boundary = std::string("cpp-httplib-multipart-data");
  16312. std::string content = "--" + boundary +
  16313. "\r\n"
  16314. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16315. "\r\n"
  16316. "text1\r\n"
  16317. "--" +
  16318. boundary + "--\r\n";
  16319. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16320. "Host: localhost\r\n"
  16321. "Content-Type: multipart/form-data;boundary=" +
  16322. boundary +
  16323. "\r\n"
  16324. "Content-Length: " +
  16325. std::to_string(content.size()) +
  16326. "\r\n"
  16327. "Dummy-Header: ";
  16328. std::string header_suffix = "\r\n"
  16329. "\r\n";
  16330. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16331. size_t header_dummy_size =
  16332. read_buff_size -
  16333. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16334. auto header_dummy = std::string(header_dummy_size, '@');
  16335. auto req = header_prefix + header_dummy + header_suffix + content;
  16336. std::string response;
  16337. ASSERT_TRUE(send_request(1, req, &response));
  16338. ASSERT_EQ("200", response.substr(9, 3));
  16339. }
  16340. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16341. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16342. // (not chunked Transfer-Encoding) after the streaming refactor.
  16343. auto handled = false;
  16344. Server svr;
  16345. svr.Post("/upload", [&](const Request &req, Response &res) {
  16346. auto cl_it = req.headers.find("Content-Length");
  16347. EXPECT_TRUE(cl_it != req.headers.end());
  16348. auto te_it = req.headers.find("Transfer-Encoding");
  16349. EXPECT_TRUE(te_it == req.headers.end());
  16350. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16351. res.set_content("ok", "text/plain");
  16352. handled = true;
  16353. });
  16354. auto port = svr.bind_to_any_port(HOST);
  16355. auto t = thread([&] { svr.listen_after_bind(); });
  16356. auto se = detail::scope_exit([&] {
  16357. svr.stop();
  16358. t.join();
  16359. ASSERT_FALSE(svr.is_running());
  16360. ASSERT_TRUE(handled);
  16361. });
  16362. svr.wait_until_ready();
  16363. UploadFormDataItems items = {
  16364. {"field1", "hello", "", "text/plain"},
  16365. {"file1", "world", "test.txt", "application/octet-stream"},
  16366. };
  16367. Client cli(HOST, port);
  16368. auto res = cli.Post("/upload", {}, items);
  16369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16370. EXPECT_EQ(StatusCode::OK_200, res->status);
  16371. }
  16372. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16373. // Verify that make_multipart_content_provider coalesces many small segments
  16374. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16375. constexpr size_t kItemCount = 1000;
  16376. UploadFormDataItems items;
  16377. items.reserve(kItemCount);
  16378. for (size_t i = 0; i < kItemCount; i++) {
  16379. items.push_back(
  16380. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16381. }
  16382. const std::string boundary = "----test-boundary";
  16383. auto content_length = detail::get_multipart_content_length(items, boundary);
  16384. auto provider = detail::make_multipart_content_provider(items, boundary);
  16385. // Drive the provider the same way write_content_with_progress does
  16386. size_t write_count = 0;
  16387. size_t total_bytes = 0;
  16388. DataSink sink;
  16389. size_t offset = 0;
  16390. sink.write = [&](const char *d, size_t l) -> bool {
  16391. (void)d;
  16392. write_count++;
  16393. total_bytes += l;
  16394. offset += l;
  16395. return true;
  16396. };
  16397. sink.is_writable = []() -> bool { return true; };
  16398. while (offset < content_length) {
  16399. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16400. }
  16401. EXPECT_EQ(content_length, total_bytes);
  16402. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16403. // With buffering into 64KB blocks, write_count should be much smaller.
  16404. auto segment_count = 3 * kItemCount + 1;
  16405. EXPECT_LT(write_count, segment_count / 10);
  16406. }
  16407. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16408. // Integration test: send many UploadFormDataItems and verify the server
  16409. // receives all of them correctly (#2410).
  16410. constexpr size_t kItemCount = 500;
  16411. auto handled = false;
  16412. Server svr;
  16413. svr.Post("/upload", [&](const Request &req, Response &res) {
  16414. EXPECT_EQ(kItemCount, req.form.fields.size());
  16415. for (size_t i = 0; i < kItemCount; i++) {
  16416. auto key = "field" + std::to_string(i);
  16417. auto val = "value" + std::to_string(i);
  16418. auto it = req.form.fields.find(key);
  16419. if (it != req.form.fields.end()) {
  16420. EXPECT_EQ(val, it->second.content);
  16421. } else {
  16422. ADD_FAILURE() << "Missing field: " << key;
  16423. }
  16424. }
  16425. res.set_content("ok", "text/plain");
  16426. handled = true;
  16427. });
  16428. auto port = svr.bind_to_any_port(HOST);
  16429. auto t = thread([&] { svr.listen_after_bind(); });
  16430. auto se = detail::scope_exit([&] {
  16431. svr.stop();
  16432. t.join();
  16433. ASSERT_FALSE(svr.is_running());
  16434. ASSERT_TRUE(handled);
  16435. });
  16436. svr.wait_until_ready();
  16437. UploadFormDataItems items;
  16438. items.reserve(kItemCount);
  16439. for (size_t i = 0; i < kItemCount; i++) {
  16440. items.push_back(
  16441. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16442. }
  16443. Client cli(HOST, port);
  16444. auto res = cli.Post("/upload", items);
  16445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16446. EXPECT_EQ(StatusCode::OK_200, res->status);
  16447. }
  16448. TEST(MultipartFormDataTest, MakeFileProvider) {
  16449. // Verify make_file_provider sends a file's contents correctly.
  16450. const std::string file_content(4096, 'Z');
  16451. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16452. {
  16453. std::ofstream ofs(tmp_path, std::ios::binary);
  16454. ofs.write(file_content.data(),
  16455. static_cast<std::streamsize>(file_content.size()));
  16456. }
  16457. auto handled = false;
  16458. Server svr;
  16459. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16460. const ContentReader &content_reader) {
  16461. ASSERT_TRUE(req.is_multipart_form_data());
  16462. std::vector<FormData> items;
  16463. content_reader(
  16464. [&](const FormData &file) {
  16465. items.push_back(file);
  16466. return true;
  16467. },
  16468. [&](const char *data, size_t data_length) {
  16469. items.back().content.append(data, data_length);
  16470. return true;
  16471. });
  16472. ASSERT_EQ(1u, items.size());
  16473. EXPECT_EQ("myfile", items[0].name);
  16474. EXPECT_EQ("data.bin", items[0].filename);
  16475. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16476. EXPECT_EQ(file_content, items[0].content);
  16477. handled = true;
  16478. });
  16479. auto port = svr.bind_to_any_port(HOST);
  16480. auto t = thread([&] { svr.listen_after_bind(); });
  16481. auto se = detail::scope_exit([&] {
  16482. svr.stop();
  16483. t.join();
  16484. ASSERT_FALSE(svr.is_running());
  16485. ASSERT_TRUE(handled);
  16486. std::remove(tmp_path.c_str());
  16487. });
  16488. svr.wait_until_ready();
  16489. FormDataProviderItems providers;
  16490. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16491. "application/octet-stream"));
  16492. Client cli(HOST, port);
  16493. auto res = cli.Post("/upload", {}, {}, providers);
  16494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16495. EXPECT_EQ(StatusCode::OK_200, res->status);
  16496. }
  16497. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16498. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16499. // (100) headers is rejected with a 400 Bad Request response.
  16500. Server svr;
  16501. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16502. res.set_content("ok", "text/plain");
  16503. });
  16504. thread t = thread([&] { svr.listen(HOST, PORT); });
  16505. auto se = detail::scope_exit([&] {
  16506. svr.stop();
  16507. t.join();
  16508. ASSERT_FALSE(svr.is_running());
  16509. });
  16510. svr.wait_until_ready();
  16511. // Build a multipart part with 101 custom headers (exceeding
  16512. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16513. std::stringstream body;
  16514. body << "--simpleboundary\r\n"
  16515. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16516. for (int i = 0; i < 101; i++) {
  16517. body << "X-Custom-Header-" << i << ": value\r\n";
  16518. }
  16519. body << "\r\n"
  16520. << "value1\r\n"
  16521. << "--simpleboundary--\r\n";
  16522. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16523. Client cli(HOST, PORT);
  16524. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16526. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16527. }
  16528. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16529. // A body that never contains the declared boundary must not be accumulated
  16530. // while the parser waits for it. Buffering it would also make every read
  16531. // rescan everything seen so far, which is quadratic in the body size.
  16532. Server svr;
  16533. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16534. res.set_content("ok", "text/plain");
  16535. });
  16536. auto port = svr.bind_to_any_port(HOST);
  16537. thread t = thread([&] { svr.listen_after_bind(); });
  16538. auto se = detail::scope_exit([&] {
  16539. svr.stop();
  16540. t.join();
  16541. ASSERT_FALSE(svr.is_running());
  16542. });
  16543. svr.wait_until_ready();
  16544. Client cli(HOST, port);
  16545. cli.set_read_timeout(60, 0);
  16546. cli.set_write_timeout(60, 0);
  16547. // '-' is the worst case: it matches the first character of the boundary, so
  16548. // every position has to be checked against it.
  16549. auto post_dashes = [&](size_t size) {
  16550. const std::string body(size, '-');
  16551. auto start = std::chrono::steady_clock::now();
  16552. auto res =
  16553. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16554. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16555. std::chrono::steady_clock::now() - start)
  16556. .count();
  16557. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16558. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16559. return ms;
  16560. };
  16561. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16562. // Windows.
  16563. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16564. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16565. // Comparing the two sizes rather than checking an absolute duration keeps
  16566. // this meaningful across build types and CI load, both of which move the
  16567. // absolute numbers by more than an order of magnitude. Four times the bytes
  16568. // costs about four times the time when parsing is linear, and about sixteen
  16569. // times when the body is buffered and rescanned.
  16570. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16571. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16572. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16573. << "ms, which suggests the body is being buffered and rescanned";
  16574. }
  16575. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16576. // A boundary can only be followed by CRLF or by "--", so anything else is
  16577. // malformed no matter what comes next. The parser must say so right away
  16578. // instead of buffering the rest of the declared body.
  16579. Server svr;
  16580. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16581. res.set_content("ok", "text/plain");
  16582. });
  16583. auto port = svr.bind_to_any_port(HOST);
  16584. thread t = thread([&] { svr.listen_after_bind(); });
  16585. auto se = detail::scope_exit([&] {
  16586. svr.stop();
  16587. t.join();
  16588. ASSERT_FALSE(svr.is_running());
  16589. });
  16590. svr.wait_until_ready();
  16591. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16592. // buffers instead of failing would still be waiting for the remaining bytes.
  16593. const std::string body = "--zzzz\r\n"
  16594. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16595. "\r\n"
  16596. "text1"
  16597. "\r\n--zzzzXX";
  16598. const std::string req = "POST /post HTTP/1.1\r\n"
  16599. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16600. "Content-Length: 1048576\r\n"
  16601. "\r\n" +
  16602. body;
  16603. std::string response;
  16604. ASSERT_TRUE(send_request(3, req, &response, port));
  16605. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16606. EXPECT_EQ("400", response.substr(9, 3));
  16607. }
  16608. // Posts a multipart body split into two writes, so that the server sees the
  16609. // split at whatever offset the caller chose, and expects the single "text1"
  16610. // field to come through.
  16611. static void expect_split_multipart_ok(const std::string &body1,
  16612. const std::string &body2) {
  16613. auto handled = false;
  16614. Server svr;
  16615. svr.Post("/post", [&](const Request &req, Response &) {
  16616. EXPECT_EQ(1u, req.form.fields.size());
  16617. EXPECT_EQ("text1", req.form.get_field("text1"));
  16618. handled = true;
  16619. });
  16620. auto port = svr.bind_to_any_port(HOST);
  16621. thread t = thread([&] { svr.listen_after_bind(); });
  16622. auto se = detail::scope_exit([&] {
  16623. svr.stop();
  16624. t.join();
  16625. ASSERT_FALSE(svr.is_running());
  16626. ASSERT_TRUE(handled);
  16627. });
  16628. svr.wait_until_ready();
  16629. // "Connection: close" makes the server close once it has answered, so the
  16630. // response drain ends immediately instead of idling until the read timeout.
  16631. const std::string head =
  16632. "POST /post HTTP/1.1\r\n"
  16633. "Host: localhost\r\n"
  16634. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16635. "Connection: close\r\n"
  16636. "Content-Length: " +
  16637. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16638. std::string response;
  16639. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16640. ASSERT_GE(response.size(), 12u) << "no response";
  16641. EXPECT_EQ("200", response.substr(9, 3));
  16642. }
  16643. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16644. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16645. // ignored, including when it does not arrive in the same read as the
  16646. // close-delimiter itself.
  16647. expect_split_multipart_ok("--zzzz\r\n"
  16648. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16649. "\r\n"
  16650. "text1"
  16651. "\r\n--zzzz--",
  16652. "\r\nthis epilogue must be ignored\r\n");
  16653. }
  16654. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16655. // The initial boundary may be preceded by a preamble of any length and may
  16656. // straddle a read boundary. Discarding data while waiting for it must not
  16657. // throw away a partial boundary sitting at the end of the buffer.
  16658. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16659. "zz\r\n"
  16660. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16661. "\r\n"
  16662. "text1"
  16663. "\r\n--zzzz--\r\n");
  16664. }
  16665. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16666. // The received boundary was only checked for being non-empty, so it could be
  16667. // as long as a header is allowed to be. The parser scans the body for
  16668. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16669. // costs a nearly full comparison at nearly every position, making the
  16670. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16671. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16672. Server svr;
  16673. svr.Post("/post", [](const Request &req, Response &res) {
  16674. EXPECT_EQ(1u, req.form.fields.size());
  16675. EXPECT_EQ("text1", req.form.get_field("text1"));
  16676. res.set_content("ok", "text/plain");
  16677. });
  16678. auto port = svr.bind_to_any_port(HOST);
  16679. thread t = thread([&] { svr.listen_after_bind(); });
  16680. auto se = detail::scope_exit([&] {
  16681. svr.stop();
  16682. t.join();
  16683. ASSERT_FALSE(svr.is_running());
  16684. });
  16685. svr.wait_until_ready();
  16686. Client cli(HOST, port);
  16687. auto post_with_boundary_of_length = [&](size_t len) {
  16688. const std::string boundary(len, 'a');
  16689. const std::string body =
  16690. "--" + boundary +
  16691. "\r\n"
  16692. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16693. "\r\n"
  16694. "text1"
  16695. "\r\n--" +
  16696. boundary + "--\r\n";
  16697. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16698. };
  16699. auto res = post_with_boundary_of_length(70);
  16700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16701. EXPECT_EQ(StatusCode::OK_200, res->status);
  16702. res = post_with_boundary_of_length(71);
  16703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16704. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16705. }
  16706. TEST(MakeFileBodyTest, Basic) {
  16707. const std::string file_content(4096, 'Z');
  16708. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16709. {
  16710. std::ofstream ofs(tmp_path, std::ios::binary);
  16711. ofs.write(file_content.data(),
  16712. static_cast<std::streamsize>(file_content.size()));
  16713. }
  16714. auto handled = false;
  16715. Server svr;
  16716. svr.Post("/upload", [&](const Request &req, Response &res) {
  16717. EXPECT_EQ(file_content, req.body);
  16718. handled = true;
  16719. res.status = StatusCode::OK_200;
  16720. });
  16721. auto port = svr.bind_to_any_port(HOST);
  16722. auto t = thread([&] { svr.listen_after_bind(); });
  16723. auto se = detail::scope_exit([&] {
  16724. svr.stop();
  16725. t.join();
  16726. ASSERT_FALSE(svr.is_running());
  16727. ASSERT_TRUE(handled);
  16728. std::remove(tmp_path.c_str());
  16729. });
  16730. svr.wait_until_ready();
  16731. auto fb = make_file_body(tmp_path);
  16732. ASSERT_GT(fb.first, 0u);
  16733. Client cli(HOST, port);
  16734. auto res =
  16735. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16737. EXPECT_EQ(StatusCode::OK_200, res->status);
  16738. }
  16739. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16740. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16741. {
  16742. std::ofstream ofs(path, std::ios::binary);
  16743. const std::string content(100, 'A');
  16744. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16745. }
  16746. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16747. auto body = make_file_body(path);
  16748. ASSERT_EQ(100u, body.first);
  16749. ASSERT_TRUE(static_cast<bool>(body.second));
  16750. // Rewritten shorter after its length was measured - and, on a server, after
  16751. // that length has already gone out as Content-Length.
  16752. {
  16753. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16754. const std::string content(10, 'A');
  16755. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16756. }
  16757. std::string written;
  16758. DataSink sink;
  16759. sink.write = [&](const char *d, size_t l) {
  16760. written.append(d, l);
  16761. return true;
  16762. };
  16763. // The provider has to report failure. write_content_with_progress() advances
  16764. // its offset only by what was written, so a provider that returns true
  16765. // without completing the length it promised is called again straight away,
  16766. // and again.
  16767. EXPECT_FALSE(body.second(0, body.first, sink));
  16768. EXPECT_EQ(std::string(10, 'A'), written);
  16769. }
  16770. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16771. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16772. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16773. {
  16774. std::ofstream ofs(path, std::ios::binary);
  16775. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16776. }
  16777. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16778. auto body = make_file_body(path);
  16779. ASSERT_EQ(content.size(), body.first);
  16780. ASSERT_TRUE(static_cast<bool>(body.second));
  16781. std::string written;
  16782. DataSink sink;
  16783. sink.write = [&](const char *d, size_t l) {
  16784. written.append(d, l);
  16785. return true;
  16786. };
  16787. EXPECT_TRUE(body.second(0, body.first, sink));
  16788. EXPECT_EQ(content, written);
  16789. }
  16790. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16791. static constexpr unsigned int number_of_tasks{1000000};
  16792. std::atomic_uint count{0};
  16793. std::unique_ptr<TaskQueue> task_queue{
  16794. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16795. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16796. auto queued = task_queue->enqueue(
  16797. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16798. EXPECT_TRUE(queued);
  16799. }
  16800. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16801. task_queue->shutdown();
  16802. #else
  16803. EXPECT_NO_THROW(task_queue->shutdown());
  16804. #endif
  16805. EXPECT_EQ(number_of_tasks, count.load());
  16806. }
  16807. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16808. static constexpr unsigned int number_of_tasks{1000000};
  16809. static constexpr unsigned int qlimit{2};
  16810. unsigned int queued_count{0};
  16811. std::atomic_uint count{0};
  16812. std::unique_ptr<TaskQueue> task_queue{
  16813. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16814. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16815. if (task_queue->enqueue(
  16816. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16817. queued_count++;
  16818. }
  16819. }
  16820. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16821. task_queue->shutdown();
  16822. #else
  16823. EXPECT_NO_THROW(task_queue->shutdown());
  16824. #endif
  16825. EXPECT_EQ(queued_count, count.load());
  16826. EXPECT_TRUE(queued_count <= number_of_tasks);
  16827. EXPECT_TRUE(queued_count >= qlimit);
  16828. }
  16829. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16830. // Use a short idle timeout so a dynamic thread spawns, times out and
  16831. // exits during the test, and the pool keeps working afterwards.
  16832. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16833. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16834. /*idle_timeout_sec=*/1}};
  16835. std::atomic_uint count{0};
  16836. std::condition_variable cv;
  16837. std::mutex mtx;
  16838. bool release = false;
  16839. // Block the base thread so the second task spawns a dynamic thread.
  16840. EXPECT_TRUE(task_queue->enqueue([&] {
  16841. std::unique_lock<std::mutex> lock(mtx);
  16842. while (!release) {
  16843. cv.wait(lock);
  16844. }
  16845. count++;
  16846. }));
  16847. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16848. // Let the dynamic thread finish its task and exceed the idle timeout.
  16849. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16850. {
  16851. std::unique_lock<std::mutex> lock(mtx);
  16852. release = true;
  16853. }
  16854. cv.notify_all();
  16855. // The pool must still accept and run tasks after the dynamic thread exited.
  16856. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16857. task_queue->shutdown();
  16858. EXPECT_EQ(3u, count.load());
  16859. }
  16860. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16861. static constexpr size_t number_of_tasks{32};
  16862. std::unique_ptr<TaskQueue> task_queue{
  16863. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16864. // Let the base threads go idle so the burst below finds them waiting.
  16865. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16866. std::mutex mtx;
  16867. std::condition_variable cv;
  16868. size_t running = 0;
  16869. bool release = false;
  16870. for (size_t i = 0; i < number_of_tasks; i++) {
  16871. EXPECT_TRUE(task_queue->enqueue([&] {
  16872. std::unique_lock<std::mutex> lock(mtx);
  16873. running++;
  16874. cv.notify_all();
  16875. cv.wait(lock, [&] { return release; });
  16876. }));
  16877. }
  16878. {
  16879. std::unique_lock<std::mutex> lock(mtx);
  16880. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16881. [&] { return running == number_of_tasks; }));
  16882. release = true;
  16883. }
  16884. cv.notify_all();
  16885. task_queue->shutdown();
  16886. }
  16887. TEST(TaskQueueTest, MaxQueuedRequests) {
  16888. static constexpr unsigned int qlimit{3};
  16889. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16890. std::condition_variable sem_cv;
  16891. std::mutex sem_mtx;
  16892. int credits = 0;
  16893. bool queued;
  16894. /* Fill up the queue with tasks that will block until we give them credits to
  16895. * complete. */
  16896. for (unsigned int n = 0; n <= qlimit;) {
  16897. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16898. std::unique_lock<std::mutex> lock(sem_mtx);
  16899. while (credits <= 0) {
  16900. sem_cv.wait(lock);
  16901. }
  16902. /* Consume the credit and signal the test code if they are all gone. */
  16903. if (--credits == 0) { sem_cv.notify_one(); }
  16904. });
  16905. if (n < qlimit) {
  16906. /* The first qlimit enqueues must succeed. */
  16907. EXPECT_TRUE(queued);
  16908. } else {
  16909. /* The last one will succeed only when the worker thread
  16910. * starts and dequeues the first blocking task. Although
  16911. * not necessary for the correctness of this test, we sleep for
  16912. * a short while to avoid busy waiting. */
  16913. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16914. }
  16915. if (queued) { n++; }
  16916. }
  16917. /* Further enqueues must fail since the queue is full. */
  16918. for (auto i = 0; i < 4; i++) {
  16919. queued = task_queue->enqueue([] {});
  16920. EXPECT_FALSE(queued);
  16921. }
  16922. /* Give the credits to allow the previous tasks to complete. */
  16923. {
  16924. std::unique_lock<std::mutex> lock(sem_mtx);
  16925. credits += qlimit + 1;
  16926. }
  16927. sem_cv.notify_all();
  16928. /* Wait for all the credits to be consumed. */
  16929. {
  16930. std::unique_lock<std::mutex> lock(sem_mtx);
  16931. while (credits > 0) {
  16932. sem_cv.wait(lock);
  16933. }
  16934. }
  16935. /* Check that we are able again to enqueue at least qlimit tasks. */
  16936. for (unsigned int i = 0; i < qlimit; i++) {
  16937. queued = task_queue->enqueue([] {});
  16938. EXPECT_TRUE(queued);
  16939. }
  16940. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16941. task_queue->shutdown();
  16942. #else
  16943. EXPECT_NO_THROW(task_queue->shutdown());
  16944. #endif
  16945. }
  16946. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16947. Server svr;
  16948. std::string method;
  16949. std::string body;
  16950. auto has_content_length = false;
  16951. auto has_transfer_encoding = false;
  16952. std::atomic<int> bad_requests{0};
  16953. // Leftover body bytes get parsed as a malformed request and answered with
  16954. // 400
  16955. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16956. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16957. });
  16958. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16959. res.set_redirect("/down", StatusCode::SeeOther_303);
  16960. });
  16961. svr.Get("/down", [&](const Request &req, Response &res) {
  16962. method = req.method;
  16963. body = req.body;
  16964. has_content_length = req.has_header("Content-Length");
  16965. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16966. res.set_content("ok", "text/plain");
  16967. });
  16968. auto port = svr.bind_to_any_port(HOST);
  16969. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16970. auto se = detail::scope_exit([&] {
  16971. svr.stop();
  16972. thread.join();
  16973. ASSERT_FALSE(svr.is_running());
  16974. });
  16975. svr.wait_until_ready();
  16976. const std::string payload = "SECRET-BODY";
  16977. auto check = [&](Client &cli, const Result &res) {
  16978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16979. EXPECT_EQ(StatusCode::OK_200, res->status);
  16980. EXPECT_EQ("ok", res->body);
  16981. EXPECT_EQ("GET", method);
  16982. EXPECT_TRUE(body.empty());
  16983. EXPECT_FALSE(has_content_length);
  16984. EXPECT_FALSE(has_transfer_encoding);
  16985. // Nothing of the original body may be left on the connection
  16986. auto res2 = cli.Get("/down");
  16987. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16988. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16989. EXPECT_EQ("ok", res2->body);
  16990. EXPECT_EQ(0, bad_requests);
  16991. };
  16992. // With content length
  16993. {
  16994. Client cli(HOST, port);
  16995. cli.set_keep_alive(true);
  16996. cli.set_follow_location(true);
  16997. auto res = cli.Post(
  16998. "/up", payload.size(),
  16999. [&](size_t offset, size_t length, DataSink &sink) {
  17000. return sink.write(payload.data() + offset, length);
  17001. },
  17002. "text/plain");
  17003. check(cli, res);
  17004. }
  17005. // Without content length (chunked)
  17006. {
  17007. Client cli(HOST, port);
  17008. cli.set_keep_alive(true);
  17009. cli.set_follow_location(true);
  17010. auto res = cli.Post(
  17011. "/up",
  17012. [&](size_t /*offset*/, DataSink &sink) {
  17013. sink.write(payload.data(), payload.size());
  17014. sink.done();
  17015. return true;
  17016. },
  17017. "text/plain");
  17018. check(cli, res);
  17019. }
  17020. }
  17021. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17022. Server svr;
  17023. std::string target;
  17024. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17025. // Echo the still-encoded name back in the Location
  17026. const std::string prefix = "/start/";
  17027. res.status = StatusCode::Found_302;
  17028. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17029. });
  17030. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17031. target = req.target;
  17032. res.set_content("ok", "text/plain");
  17033. });
  17034. auto port = svr.bind_to_any_port(HOST);
  17035. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17036. auto se = detail::scope_exit([&] {
  17037. svr.stop();
  17038. thread.join();
  17039. ASSERT_FALSE(svr.is_running());
  17040. });
  17041. svr.wait_until_ready();
  17042. // Decoding the Location path would turn the first four into a path
  17043. // separator, a query delimiter, a fragment delimiter and a different
  17044. // percent-encoded octet. The rest must keep reaching the server as they are.
  17045. const std::vector<std::string> names = {
  17046. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17047. };
  17048. for (auto path_encode : {true, false}) {
  17049. Client cli(HOST, port);
  17050. cli.set_follow_location(true);
  17051. cli.set_path_encode(path_encode);
  17052. for (const auto &name : names) {
  17053. target.clear();
  17054. auto res = cli.Get("/start/" + name);
  17055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17056. EXPECT_EQ(StatusCode::OK_200, res->status);
  17057. EXPECT_EQ("/dest/" + name, target);
  17058. }
  17059. }
  17060. }
  17061. TEST(RedirectTest, NotModifiedIsReturned) {
  17062. Server svr;
  17063. svr.Get("/cached", [](const Request &, Response &res) {
  17064. res.status = StatusCode::NotModified_304;
  17065. });
  17066. auto port = svr.bind_to_any_port(HOST);
  17067. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17068. auto se = detail::scope_exit([&] {
  17069. svr.stop();
  17070. thread.join();
  17071. ASSERT_FALSE(svr.is_running());
  17072. });
  17073. svr.wait_until_ready();
  17074. Client cli(HOST, port);
  17075. cli.set_follow_location(true);
  17076. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17079. }
  17080. TEST(RedirectTest, NoLocationIsReturned) {
  17081. Server svr;
  17082. svr.Get("/no-location", [](const Request &, Response &res) {
  17083. res.status = StatusCode::Found_302;
  17084. res.set_content("no location", "text/plain");
  17085. });
  17086. auto port = svr.bind_to_any_port(HOST);
  17087. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17088. auto se = detail::scope_exit([&] {
  17089. svr.stop();
  17090. thread.join();
  17091. ASSERT_FALSE(svr.is_running());
  17092. });
  17093. svr.wait_until_ready();
  17094. Client cli(HOST, port);
  17095. cli.set_follow_location(true);
  17096. auto res = cli.Get("/no-location");
  17097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17098. EXPECT_EQ(StatusCode::Found_302, res->status);
  17099. EXPECT_EQ("no location", res->body);
  17100. // The callbacks see the body of the response that is returned
  17101. auto handler_called = false;
  17102. auto progress_called = false;
  17103. std::string body;
  17104. auto res2 = cli.Get(
  17105. "/no-location",
  17106. [&](const Response &) {
  17107. handler_called = true;
  17108. return true;
  17109. },
  17110. [&](const char *data, size_t data_length) {
  17111. body.append(data, data_length);
  17112. return true;
  17113. },
  17114. [&](size_t, size_t) {
  17115. progress_called = true;
  17116. return true;
  17117. });
  17118. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17119. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17120. EXPECT_TRUE(handler_called);
  17121. EXPECT_TRUE(progress_called);
  17122. EXPECT_EQ("no location", body);
  17123. }
  17124. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17125. Server svr;
  17126. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17127. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17128. });
  17129. svr.Get("/hello", [](const Request &req, Response &res) {
  17130. res.set_content(req.get_param_value("key"), "text/plain");
  17131. });
  17132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17133. auto se = detail::scope_exit([&] {
  17134. svr.stop();
  17135. thread.join();
  17136. ASSERT_FALSE(svr.is_running());
  17137. });
  17138. svr.wait_until_ready();
  17139. {
  17140. Client cli(HOST, PORT);
  17141. cli.set_follow_location(true);
  17142. auto res = cli.Get("/");
  17143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17144. EXPECT_EQ(StatusCode::OK_200, res->status);
  17145. EXPECT_EQ("val&key2=val2", res->body);
  17146. }
  17147. }
  17148. #endif
  17149. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17150. Server svr;
  17151. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17152. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17153. });
  17154. svr.Get("/hello", [](const Request &req, Response &res) {
  17155. res.set_content(req.get_param_value("key"), "text/plain");
  17156. });
  17157. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17158. auto se = detail::scope_exit([&] {
  17159. svr.stop();
  17160. thread.join();
  17161. ASSERT_FALSE(svr.is_running());
  17162. });
  17163. svr.wait_until_ready();
  17164. {
  17165. Client cli(HOST, PORT);
  17166. cli.set_follow_location(true);
  17167. auto res = cli.Get("/");
  17168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17169. EXPECT_EQ(StatusCode::OK_200, res->status);
  17170. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17171. }
  17172. }
  17173. TEST(RedirectTest, RedirectWithPlusInPath) {
  17174. Server svr;
  17175. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17176. res.set_redirect("/a+b");
  17177. });
  17178. // Route pattern uses regex; escape + as \\+
  17179. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17180. res.set_content(req.path, "text/plain");
  17181. });
  17182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17183. auto se = detail::scope_exit([&] {
  17184. svr.stop();
  17185. thread.join();
  17186. ASSERT_FALSE(svr.is_running());
  17187. });
  17188. svr.wait_until_ready();
  17189. {
  17190. Client cli(HOST, PORT);
  17191. cli.set_follow_location(true);
  17192. auto res = cli.Get("/");
  17193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17194. EXPECT_EQ(StatusCode::OK_200, res->status);
  17195. EXPECT_EQ("/a+b", res->body);
  17196. }
  17197. }
  17198. TEST(RedirectTest, ResolveRelativeLocation) {
  17199. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17200. const std::vector<std::pair<std::string, std::string>> cases = {
  17201. {"g", "/b/c/g"},
  17202. {"./g", "/b/c/g"},
  17203. {"g/", "/b/c/g/"},
  17204. {"?y", "/b/c/d;p?y"},
  17205. {"g?y", "/b/c/g?y"},
  17206. {"#s", "/b/c/d;p?q#s"},
  17207. {"g#s", "/b/c/g#s"},
  17208. {"g?y#s", "/b/c/g?y#s"},
  17209. {";x", "/b/c/;x"},
  17210. {"g;x", "/b/c/g;x"},
  17211. {".", "/b/c/"},
  17212. {"./", "/b/c/"},
  17213. {"..", "/b/"},
  17214. {"../", "/b/"},
  17215. {"../g", "/b/g"},
  17216. {"../..", "/"},
  17217. {"../../", "/"},
  17218. {"../../g", "/g"},
  17219. {"../../../g", "/g"},
  17220. {"g.", "/b/c/g."},
  17221. {".g", "/b/c/.g"},
  17222. {"g..", "/b/c/g.."},
  17223. {"..g", "/b/c/..g"},
  17224. {"./../g", "/b/g"},
  17225. {"./g/.", "/b/c/g/"},
  17226. {"g/./h", "/b/c/g/h"},
  17227. {"g/../h", "/b/c/h"},
  17228. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17229. {"g;x=1/../y", "/b/c/y"},
  17230. {"g?y/./x", "/b/c/g?y/./x"},
  17231. {"g#s/../x", "/b/c/g#s/../x"},
  17232. // Not relative-path references, so left for parse_url.
  17233. {"/g", "/g"},
  17234. {"//g", "//g"},
  17235. {"http://g/x", "http://g/x"},
  17236. {"g:h", "g:h"},
  17237. };
  17238. for (const auto &c : cases) {
  17239. EXPECT_EQ(c.second,
  17240. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17241. << c.first;
  17242. }
  17243. }
  17244. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17245. Server svr;
  17246. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17247. res.set_redirect(req.get_param_value("to"));
  17248. });
  17249. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17250. res.set_content(req.target, "text/plain");
  17251. });
  17252. svr.Get("/other", [](const Request &req, Response &res) {
  17253. res.set_content(req.target, "text/plain");
  17254. });
  17255. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17256. auto se = detail::scope_exit([&] {
  17257. svr.stop();
  17258. thread.join();
  17259. ASSERT_FALSE(svr.is_running());
  17260. });
  17261. svr.wait_until_ready();
  17262. const std::vector<std::pair<std::string, std::string>> cases = {
  17263. {"next", "/dir/next"},
  17264. {"./next?x=1", "/dir/next?x=1"},
  17265. {"../other", "/other"},
  17266. };
  17267. for (const auto &c : cases) {
  17268. Client cli(HOST, PORT);
  17269. cli.set_follow_location(true);
  17270. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17271. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17272. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17273. EXPECT_EQ(c.second, res->body) << c.first;
  17274. }
  17275. }
  17276. #ifdef CPPHTTPLIB_SSL_ENABLED
  17277. TEST(RedirectTest, Issue2185_Online) {
  17278. SSLClient client("github.com");
  17279. client.set_follow_location(true);
  17280. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17281. "Coollab-Windows.zip");
  17282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17283. EXPECT_EQ(StatusCode::OK_200, res->status);
  17284. EXPECT_EQ(9920427U, res->body.size());
  17285. }
  17286. #endif
  17287. TEST(VulnerabilityTest, CRLFInjection) {
  17288. Server svr;
  17289. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17290. res.set_content("Hello 1", "text/plain");
  17291. });
  17292. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17293. res.set_content("Hello 2", "text/plain");
  17294. });
  17295. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17296. res.set_content("Hello 3", "text/plain");
  17297. });
  17298. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17299. res.set_content("Hello 4", "text/plain");
  17300. });
  17301. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17302. for (const auto &x : req.headers) {
  17303. auto key = x.first;
  17304. EXPECT_STRNE("evil", key.c_str());
  17305. }
  17306. });
  17307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17308. auto se = detail::scope_exit([&] {
  17309. svr.stop();
  17310. thread.join();
  17311. ASSERT_FALSE(svr.is_running());
  17312. });
  17313. svr.wait_until_ready();
  17314. {
  17315. Client cli(HOST, PORT);
  17316. cli.Post("/test1", "A=B",
  17317. "application/x-www-form-urlencoded\r\nevil: hello1");
  17318. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17319. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17320. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17321. }
  17322. }
  17323. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17324. auto server_thread = std::thread([] {
  17325. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17326. default_socket_options(srv);
  17327. sockaddr_in addr{};
  17328. addr.sin_family = AF_INET;
  17329. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17330. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17331. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17332. ::listen(srv, 1);
  17333. sockaddr_in cli_addr{};
  17334. socklen_t cli_len = sizeof(cli_addr);
  17335. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17336. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17337. std::string buf_all;
  17338. char buf[2048];
  17339. ssize_t n;
  17340. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17341. buf_all.append(buf, static_cast<size_t>(n));
  17342. size_t pos;
  17343. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17344. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17345. auto e = request_block.find("\r\n");
  17346. if (e != std::string::npos) {
  17347. auto request_line = request_block.substr(0, e);
  17348. std::string msg =
  17349. "CRLF injection detected in request line: '" + request_line + "'";
  17350. EXPECT_FALSE(true) << msg;
  17351. }
  17352. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17353. ::send(cli,
  17354. #ifdef _WIN32
  17355. static_cast<const char *>(resp.c_str()),
  17356. static_cast<int>(resp.size()),
  17357. #else
  17358. resp.c_str(), resp.size(),
  17359. #endif
  17360. 0);
  17361. buf_all.erase(0, pos + 4);
  17362. }
  17363. }
  17364. detail::close_socket(cli);
  17365. detail::close_socket(srv);
  17366. });
  17367. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17368. auto cli = Client("127.0.0.1", PORT + 1);
  17369. auto headers = Headers{
  17370. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17371. {"Connection", "keep-alive"}};
  17372. auto res = cli.Get("/hi", headers);
  17373. EXPECT_FALSE(res);
  17374. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17375. server_thread.join();
  17376. }
  17377. // A request rejected before any byte reaches the socket must fail right away
  17378. // instead of waiting for a response the server will never send.
  17379. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17380. // The kernel completes the TCP handshake from the listen backlog, so the
  17381. // client connects, but nothing ever reads, responds or closes.
  17382. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17383. default_socket_options(srv);
  17384. sockaddr_in addr{};
  17385. addr.sin_family = AF_INET;
  17386. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17387. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17388. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17389. ASSERT_EQ(0, ::listen(srv, 8));
  17390. auto cli = Client("127.0.0.1", PORT + 1);
  17391. cli.set_read_timeout(10, 0);
  17392. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17393. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17394. std::chrono::steady_clock::now() - start)
  17395. .count();
  17396. };
  17397. {
  17398. Request req;
  17399. req.method = "GE T";
  17400. req.path = "/";
  17401. auto start = std::chrono::steady_clock::now();
  17402. auto res = cli.send(req);
  17403. EXPECT_FALSE(res);
  17404. EXPECT_EQ(Error::Write, res.error());
  17405. EXPECT_LT(elapsed_ms(start), 1000);
  17406. }
  17407. {
  17408. auto start = std::chrono::steady_clock::now();
  17409. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17410. EXPECT_FALSE(res);
  17411. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17412. EXPECT_LT(elapsed_ms(start), 1000);
  17413. }
  17414. EXPECT_FALSE(cli.is_socket_open());
  17415. detail::close_socket(srv);
  17416. }
  17417. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17418. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17419. default_socket_options(srv);
  17420. sockaddr_in addr{};
  17421. addr.sin_family = AF_INET;
  17422. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17423. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17424. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17425. ASSERT_EQ(0, ::listen(srv, 1));
  17426. std::string received;
  17427. auto server_thread = std::thread([&] {
  17428. auto sock = ::accept(srv, nullptr, nullptr);
  17429. if (sock == INVALID_SOCKET) { return; }
  17430. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17431. char buf[2048];
  17432. ssize_t n;
  17433. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17434. received.append(buf, static_cast<size_t>(n));
  17435. }
  17436. detail::close_socket(sock);
  17437. });
  17438. {
  17439. auto cli = Client("127.0.0.1", PORT + 1);
  17440. // "Z" sorts after the default headers, so writing straight to the socket
  17441. // would have sent the request line and those headers before the rejection.
  17442. auto handle =
  17443. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17444. EXPECT_FALSE(handle.is_valid());
  17445. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17446. }
  17447. server_thread.join();
  17448. detail::close_socket(srv);
  17449. EXPECT_TRUE(received.empty()) << received;
  17450. }
  17451. TEST(PathParamsTest, StaticMatch) {
  17452. const auto pattern = "/users/all";
  17453. detail::PathParamsMatcher matcher(pattern);
  17454. Request request;
  17455. request.path = "/users/all";
  17456. ASSERT_TRUE(matcher.match(request));
  17457. std::unordered_map<std::string, std::string> expected_params = {};
  17458. EXPECT_EQ(request.path_params, expected_params);
  17459. }
  17460. TEST(PathParamsTest, StaticMismatch) {
  17461. const auto pattern = "/users/all";
  17462. detail::PathParamsMatcher matcher(pattern);
  17463. Request request;
  17464. request.path = "/users/1";
  17465. ASSERT_FALSE(matcher.match(request));
  17466. }
  17467. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17468. const auto pattern = "/users/:id/subscriptions";
  17469. detail::PathParamsMatcher matcher(pattern);
  17470. Request request;
  17471. request.path = "/users/42/subscriptions";
  17472. ASSERT_TRUE(matcher.match(request));
  17473. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17474. EXPECT_EQ(request.path_params, expected_params);
  17475. }
  17476. TEST(PathParamsTest, SingleParamInTheEnd) {
  17477. const auto pattern = "/users/:id";
  17478. detail::PathParamsMatcher matcher(pattern);
  17479. Request request;
  17480. request.path = "/users/24";
  17481. ASSERT_TRUE(matcher.match(request));
  17482. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17483. EXPECT_EQ(request.path_params, expected_params);
  17484. }
  17485. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17486. const auto pattern = "/users/:id/";
  17487. detail::PathParamsMatcher matcher(pattern);
  17488. Request request;
  17489. request.path = "/users/42/";
  17490. ASSERT_TRUE(matcher.match(request));
  17491. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17492. EXPECT_EQ(request.path_params, expected_params);
  17493. }
  17494. TEST(PathParamsTest, EmptyParam) {
  17495. const auto pattern = "/users/:id/";
  17496. detail::PathParamsMatcher matcher(pattern);
  17497. Request request;
  17498. request.path = "/users//";
  17499. ASSERT_TRUE(matcher.match(request));
  17500. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17501. EXPECT_EQ(request.path_params, expected_params);
  17502. }
  17503. TEST(PathParamsTest, FragmentMismatch) {
  17504. const auto pattern = "/users/:id/";
  17505. detail::PathParamsMatcher matcher(pattern);
  17506. Request request;
  17507. request.path = "/admins/24/";
  17508. ASSERT_FALSE(matcher.match(request));
  17509. }
  17510. TEST(PathParamsTest, ExtraFragments) {
  17511. const auto pattern = "/users/:id";
  17512. detail::PathParamsMatcher matcher(pattern);
  17513. Request request;
  17514. request.path = "/users/42/subscriptions";
  17515. ASSERT_FALSE(matcher.match(request));
  17516. }
  17517. TEST(PathParamsTest, MissingTrailingParam) {
  17518. const auto pattern = "/users/:id";
  17519. detail::PathParamsMatcher matcher(pattern);
  17520. Request request;
  17521. request.path = "/users";
  17522. ASSERT_FALSE(matcher.match(request));
  17523. }
  17524. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17525. const auto pattern = "/users/:id/subscriptions";
  17526. detail::PathParamsMatcher matcher(pattern);
  17527. Request request;
  17528. request.path = "/users/subscriptions";
  17529. ASSERT_FALSE(matcher.match(request));
  17530. }
  17531. TEST(PathParamsTest, MultipleParams) {
  17532. const auto pattern = "/users/:userid/subscriptions/:subid";
  17533. detail::PathParamsMatcher matcher(pattern);
  17534. Request request;
  17535. request.path = "/users/42/subscriptions/2";
  17536. ASSERT_TRUE(matcher.match(request));
  17537. std::unordered_map<std::string, std::string> expected_params = {
  17538. {"userid", "42"}, {"subid", "2"}};
  17539. EXPECT_EQ(request.path_params, expected_params);
  17540. }
  17541. TEST(PathParamsTest, SequenceOfParams) {
  17542. const auto pattern = "/values/:x/:y/:z";
  17543. detail::PathParamsMatcher matcher(pattern);
  17544. Request request;
  17545. request.path = "/values/1/2/3";
  17546. ASSERT_TRUE(matcher.match(request));
  17547. std::unordered_map<std::string, std::string> expected_params = {
  17548. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17549. EXPECT_EQ(request.path_params, expected_params);
  17550. }
  17551. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17552. const auto pattern = "/prefix:suffix";
  17553. detail::PathParamsMatcher matcher(pattern);
  17554. Request request;
  17555. request.path = "/prefix:suffix";
  17556. ASSERT_TRUE(matcher.match(request));
  17557. const std::unordered_map<std::string, std::string> expected_params = {};
  17558. EXPECT_EQ(request.path_params, expected_params);
  17559. }
  17560. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17561. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17562. // calling thread's stack on a long enough path for a quantified pattern;
  17563. // RegexMatcher must refuse to run regex matching on paths beyond
  17564. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17565. detail::RegexMatcher matcher("/files/(.*)");
  17566. Request within_limit;
  17567. within_limit.path = "/files/" + std::string(10, 'A');
  17568. EXPECT_TRUE(matcher.match(within_limit));
  17569. Request over_limit;
  17570. over_limit.path =
  17571. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17572. EXPECT_FALSE(matcher.match(over_limit));
  17573. }
  17574. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17575. Server svr;
  17576. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17577. res.set_content("ok", "text/plain");
  17578. });
  17579. auto port = svr.bind_to_any_port(HOST);
  17580. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17581. auto se = detail::scope_exit([&] {
  17582. svr.stop();
  17583. thread.join();
  17584. ASSERT_FALSE(svr.is_running());
  17585. });
  17586. svr.wait_until_ready();
  17587. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17588. // request URI limit; this used to be able to crash the process.
  17589. std::string path =
  17590. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17591. std::string req = "GET " + path +
  17592. " HTTP/1.1\r\n"
  17593. "Host: " +
  17594. std::string(HOST) + ":" + std::to_string(port) +
  17595. "\r\n"
  17596. "Connection: close\r\n"
  17597. "\r\n";
  17598. std::string response;
  17599. ASSERT_TRUE(send_request(5, req, &response, port));
  17600. EXPECT_NE(std::string::npos, response.find("404"));
  17601. }
  17602. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17603. Server svr;
  17604. auto handler = [](const Request & /*req*/, Response &res) {
  17605. res.set_content("hit", "text/plain");
  17606. };
  17607. // No regex metacharacter, so this one is compared literally
  17608. svr.Get("/literal/route", handler);
  17609. // '.' is a regex metacharacter, so this one must keep regex semantics
  17610. svr.Get("/a.c", handler);
  17611. auto port = svr.bind_to_any_port(HOST);
  17612. std::thread t([&]() { svr.listen_after_bind(); });
  17613. auto se = detail::scope_exit([&] {
  17614. svr.stop();
  17615. t.join();
  17616. ASSERT_FALSE(svr.is_running());
  17617. });
  17618. svr.wait_until_ready();
  17619. Client cli(HOST, port);
  17620. struct {
  17621. const char *path;
  17622. int status;
  17623. } cases[] = {
  17624. {"/literal/route", StatusCode::OK_200},
  17625. {"/literal/routes", StatusCode::NotFound_404},
  17626. {"/literal/rout", StatusCode::NotFound_404},
  17627. {"/abc", StatusCode::OK_200},
  17628. {"/a.c", StatusCode::OK_200},
  17629. };
  17630. for (const auto &x : cases) {
  17631. auto res = cli.Get(x.path);
  17632. ASSERT_TRUE(res) << x.path;
  17633. EXPECT_EQ(x.status, res->status) << x.path;
  17634. }
  17635. }
  17636. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17637. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17638. // from exhausting the stack, so it must only constrain routes that actually
  17639. // run a regular expression. A literal route is matched by comparison and
  17640. // stays usable at any length.
  17641. Server svr;
  17642. const std::string pattern =
  17643. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17644. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17645. res.set_content("hit", "text/plain");
  17646. });
  17647. auto port = svr.bind_to_any_port(HOST);
  17648. std::thread t([&]() { svr.listen_after_bind(); });
  17649. auto se = detail::scope_exit([&] {
  17650. svr.stop();
  17651. t.join();
  17652. ASSERT_FALSE(svr.is_running());
  17653. });
  17654. svr.wait_until_ready();
  17655. Client cli(HOST, port);
  17656. auto res = cli.Get(pattern);
  17657. ASSERT_TRUE(res);
  17658. EXPECT_EQ(StatusCode::OK_200, res->status);
  17659. }
  17660. TEST(ParseUrlTest, VariousPatterns) {
  17661. {
  17662. detail::UrlComponents uc;
  17663. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17664. EXPECT_EQ("http", uc.scheme);
  17665. EXPECT_EQ("example.com", uc.host);
  17666. EXPECT_EQ("8080", uc.port);
  17667. EXPECT_EQ("/path", uc.path);
  17668. EXPECT_EQ("?q=1", uc.query);
  17669. }
  17670. {
  17671. detail::UrlComponents uc;
  17672. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17673. EXPECT_EQ("https", uc.scheme);
  17674. EXPECT_EQ("example.com", uc.host);
  17675. EXPECT_TRUE(uc.port.empty());
  17676. EXPECT_EQ("/path", uc.path);
  17677. }
  17678. {
  17679. detail::UrlComponents uc;
  17680. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17681. EXPECT_EQ("::1", uc.host);
  17682. EXPECT_EQ("8080", uc.port);
  17683. EXPECT_EQ("/path", uc.path);
  17684. }
  17685. {
  17686. detail::UrlComponents uc;
  17687. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17688. }
  17689. {
  17690. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17691. // the path while the connection still targets the bracketed host.
  17692. detail::UrlComponents uc;
  17693. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17694. }
  17695. {
  17696. detail::UrlComponents uc;
  17697. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17698. }
  17699. {
  17700. detail::UrlComponents uc;
  17701. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17702. EXPECT_EQ("::1", uc.host);
  17703. EXPECT_TRUE(uc.port.empty());
  17704. EXPECT_EQ("/path", uc.path);
  17705. }
  17706. {
  17707. detail::UrlComponents uc;
  17708. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17709. EXPECT_TRUE(uc.scheme.empty());
  17710. EXPECT_EQ("example.com", uc.host);
  17711. EXPECT_EQ("/path", uc.path);
  17712. EXPECT_EQ("?q=1", uc.query);
  17713. }
  17714. {
  17715. detail::UrlComponents uc;
  17716. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17717. EXPECT_TRUE(uc.host.empty());
  17718. EXPECT_EQ("/path", uc.path);
  17719. EXPECT_EQ("?q=1", uc.query);
  17720. }
  17721. {
  17722. detail::UrlComponents uc;
  17723. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17724. EXPECT_EQ("example.com", uc.host);
  17725. EXPECT_EQ("8080", uc.port);
  17726. }
  17727. {
  17728. // Unix socket path — must not be parsed as host
  17729. detail::UrlComponents uc;
  17730. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17731. EXPECT_TRUE(uc.host.empty());
  17732. }
  17733. {
  17734. detail::UrlComponents uc;
  17735. ASSERT_TRUE(detail::parse_url("", uc));
  17736. EXPECT_TRUE(uc.host.empty());
  17737. EXPECT_TRUE(uc.path.empty());
  17738. }
  17739. {
  17740. detail::UrlComponents uc;
  17741. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17742. }
  17743. {
  17744. detail::UrlComponents uc;
  17745. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17746. }
  17747. {
  17748. // Accepted by parse_url; callers restrict to http/https
  17749. detail::UrlComponents uc;
  17750. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17751. EXPECT_EQ("ftp", uc.scheme);
  17752. }
  17753. {
  17754. detail::UrlComponents uc;
  17755. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17756. }
  17757. {
  17758. detail::UrlComponents uc;
  17759. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17760. }
  17761. }
  17762. TEST(ParseUrlTest, FragmentHandling) {
  17763. {
  17764. detail::UrlComponents uc;
  17765. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17766. EXPECT_EQ("/path", uc.path);
  17767. EXPECT_TRUE(uc.query.empty());
  17768. }
  17769. {
  17770. detail::UrlComponents uc;
  17771. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17772. EXPECT_TRUE(uc.path.empty());
  17773. EXPECT_TRUE(uc.query.empty());
  17774. }
  17775. }
  17776. TEST(ParseUrlTest, UserinfoHandling) {
  17777. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17778. // parsers would see evil.com as the host.
  17779. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17780. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17781. for (auto url : urls) {
  17782. detail::UrlComponents uc;
  17783. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17784. }
  17785. }
  17786. TEST(ParseUrlTest, IPv6EdgeCases) {
  17787. {
  17788. detail::UrlComponents uc;
  17789. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17790. EXPECT_TRUE(uc.scheme.empty());
  17791. EXPECT_EQ("::1", uc.host);
  17792. EXPECT_EQ("8080", uc.port);
  17793. }
  17794. {
  17795. // Zone ID '%25' is not in [a-fA-F0-9:]
  17796. detail::UrlComponents uc;
  17797. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17798. }
  17799. }
  17800. TEST(ParseUrlTest, SchemeEdgeCases) {
  17801. {
  17802. detail::UrlComponents uc;
  17803. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17804. }
  17805. {
  17806. detail::UrlComponents uc;
  17807. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17808. }
  17809. {
  17810. detail::UrlComponents uc;
  17811. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17812. }
  17813. }
  17814. TEST(ParseUrlTest, PortEdgeCases) {
  17815. {
  17816. detail::UrlComponents uc;
  17817. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17818. EXPECT_TRUE(uc.port.empty());
  17819. EXPECT_EQ("/path", uc.path);
  17820. }
  17821. {
  17822. // parse_url accepts any port string; validation is done by parse_port
  17823. detail::UrlComponents uc;
  17824. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17825. EXPECT_EQ("abc", uc.port);
  17826. }
  17827. }
  17828. TEST(ParseUrlTest, WebSocketPatterns) {
  17829. {
  17830. detail::UrlComponents uc;
  17831. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17832. EXPECT_EQ("ws", uc.scheme);
  17833. EXPECT_EQ("echo.example.com", uc.host);
  17834. EXPECT_EQ("8080", uc.port);
  17835. EXPECT_EQ("/ws", uc.path);
  17836. }
  17837. {
  17838. detail::UrlComponents uc;
  17839. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17840. EXPECT_EQ("wss", uc.scheme);
  17841. EXPECT_EQ("echo.example.com", uc.host);
  17842. EXPECT_TRUE(uc.port.empty());
  17843. EXPECT_EQ("/ws", uc.path);
  17844. }
  17845. }
  17846. TEST(ParseUrlTest, QueryOnly) {
  17847. detail::UrlComponents uc;
  17848. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17849. EXPECT_TRUE(uc.host.empty());
  17850. EXPECT_TRUE(uc.path.empty());
  17851. EXPECT_EQ("?q=1&r=2", uc.query);
  17852. }
  17853. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17854. detail::UrlComponents uc;
  17855. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17856. EXPECT_TRUE(uc.scheme.empty());
  17857. EXPECT_EQ("example.com", uc.host);
  17858. EXPECT_EQ("443", uc.port);
  17859. EXPECT_EQ("/path", uc.path);
  17860. }
  17861. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17862. // If ipv6 regex working, regex match codepath is taken.
  17863. // else port will default to 80 in Client impl
  17864. int clientImplMagicPort = 80;
  17865. int port = 4321;
  17866. // above ports must be different to avoid false negative
  17867. EXPECT_NE(clientImplMagicPort, port);
  17868. std::string ipV6TestURL = "http://[ff06::c3]";
  17869. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17870. CLIENT_PRIVATE_KEY_FILE);
  17871. EXPECT_EQ(cli.port(), port);
  17872. }
  17873. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17874. auto file_path = "./www/dir/index.html";
  17875. auto dir_path = "./www/dir";
  17876. detail::FileStat stat_file(file_path);
  17877. EXPECT_TRUE(stat_file.is_file());
  17878. EXPECT_FALSE(stat_file.is_dir());
  17879. detail::FileStat stat_dir(dir_path);
  17880. EXPECT_FALSE(stat_dir.is_file());
  17881. EXPECT_TRUE(stat_dir.is_dir());
  17882. }
  17883. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17884. // IPv4 with default HTTP port (80)
  17885. EXPECT_EQ("example.com",
  17886. detail::make_host_and_port_string("example.com", 80, false));
  17887. // IPv4 with default HTTPS port (443)
  17888. EXPECT_EQ("example.com",
  17889. detail::make_host_and_port_string("example.com", 443, true));
  17890. // IPv4 with non-default HTTP port
  17891. EXPECT_EQ("example.com:8080",
  17892. detail::make_host_and_port_string("example.com", 8080, false));
  17893. // IPv4 with non-default HTTPS port
  17894. EXPECT_EQ("example.com:8443",
  17895. detail::make_host_and_port_string("example.com", 8443, true));
  17896. // IPv6 with default HTTP port (80)
  17897. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17898. // IPv6 with default HTTPS port (443)
  17899. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17900. // IPv6 with non-default HTTP port
  17901. EXPECT_EQ("[::1]:8080",
  17902. detail::make_host_and_port_string("::1", 8080, false));
  17903. // IPv6 with non-default HTTPS port
  17904. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17905. // IPv6 full address with default port
  17906. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17907. detail::make_host_and_port_string(
  17908. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17909. // IPv6 full address with non-default port
  17910. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17911. detail::make_host_and_port_string(
  17912. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17913. // IPv6 localhost with non-default port
  17914. EXPECT_EQ("[::1]:3000",
  17915. detail::make_host_and_port_string("::1", 3000, false));
  17916. // IPv6 with zone ID (link-local address) with default port
  17917. EXPECT_EQ("[fe80::1%eth0]",
  17918. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17919. // IPv6 with zone ID (link-local address) with non-default port
  17920. EXPECT_EQ("[fe80::1%eth0]:8080",
  17921. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17922. // Edge case: Port 443 with is_ssl=false (should add port)
  17923. EXPECT_EQ("example.com:443",
  17924. detail::make_host_and_port_string("example.com", 443, false));
  17925. // Edge case: Port 80 with is_ssl=true (should add port)
  17926. EXPECT_EQ("example.com:80",
  17927. detail::make_host_and_port_string("example.com", 80, true));
  17928. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17929. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17930. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17931. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17932. // Security fix: Already bracketed IPv6 should not get double brackets
  17933. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17934. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17935. EXPECT_EQ("[::1]:8080",
  17936. detail::make_host_and_port_string("[::1]", 8080, false));
  17937. EXPECT_EQ("[2001:db8::1]:8080",
  17938. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17939. EXPECT_EQ("[fe80::1%eth0]",
  17940. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17941. EXPECT_EQ("[fe80::1%eth0]:8080",
  17942. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17943. // Edge case: Empty host (should return as-is)
  17944. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17945. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17946. // This is a known limitation but shouldn't crash
  17947. EXPECT_EQ("[host:name]",
  17948. detail::make_host_and_port_string("host:name", 80, false));
  17949. // Port number edge cases (no validation, but should not crash)
  17950. EXPECT_EQ("example.com:0",
  17951. detail::make_host_and_port_string("example.com", 0, false));
  17952. EXPECT_EQ("example.com:-1",
  17953. detail::make_host_and_port_string("example.com", -1, false));
  17954. EXPECT_EQ("example.com:65535",
  17955. detail::make_host_and_port_string("example.com", 65535, false));
  17956. EXPECT_EQ("example.com:65536",
  17957. detail::make_host_and_port_string("example.com", 65536, false));
  17958. }
  17959. #ifdef CPPHTTPLIB_SSL_ENABLED
  17960. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17961. httplib::SSLClient cli("roblox.com", 443);
  17962. cli.set_follow_location(true);
  17963. auto res = cli.Get("/");
  17964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17965. EXPECT_EQ(StatusCode::OK_200, res->status);
  17966. }
  17967. #endif
  17968. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17969. Server svr;
  17970. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17971. EXPECT_EQ(res.status, 400);
  17972. });
  17973. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17974. auto se = detail::scope_exit([&] {
  17975. svr.stop();
  17976. thread.join();
  17977. ASSERT_FALSE(svr.is_running());
  17978. });
  17979. svr.wait_until_ready();
  17980. Client cli(HOST, PORT);
  17981. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17982. }
  17983. TEST(InvalidHeaderCharsTest, is_field_name) {
  17984. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17985. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17986. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17987. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17988. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17989. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17990. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17991. EXPECT_FALSE(detail::fields::is_field_name(""));
  17992. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17993. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17994. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17995. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17996. }
  17997. TEST(InvalidHeaderCharsTest, is_field_value) {
  17998. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17999. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18000. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18001. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18002. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18003. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18004. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18005. EXPECT_TRUE(detail::fields::is_field_value(""));
  18006. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18007. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18008. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18009. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18010. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18011. }
  18012. TEST(InvalidHeaderCharsTest, OnServer) {
  18013. Server svr;
  18014. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18015. std::string header = "Not Set";
  18016. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18017. res.set_header(header, "value");
  18018. res.set_content("Page Content Page Content", "text/plain");
  18019. });
  18020. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18021. std::string header = "Not Set";
  18022. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18023. res.set_header("X-Test", header);
  18024. res.set_content("Page Content Page Content", "text/plain");
  18025. });
  18026. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18027. auto se = detail::scope_exit([&] {
  18028. svr.stop();
  18029. thread.join();
  18030. ASSERT_FALSE(svr.is_running());
  18031. });
  18032. svr.wait_until_ready();
  18033. Client cli(HOST, PORT);
  18034. {
  18035. auto res = cli.Get(
  18036. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18038. EXPECT_EQ("Page Content Page Content", res->body);
  18039. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18040. }
  18041. {
  18042. auto res = cli.Get(
  18043. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18045. EXPECT_EQ("Page Content Page Content", res->body);
  18046. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18047. }
  18048. }
  18049. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18050. auto handled = false;
  18051. Server svr;
  18052. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18053. thread t = thread([&] { svr.listen(HOST, PORT); });
  18054. auto se = detail::scope_exit([&] {
  18055. svr.stop();
  18056. t.join();
  18057. ASSERT_FALSE(svr.is_running());
  18058. ASSERT_FALSE(handled);
  18059. });
  18060. svr.wait_until_ready();
  18061. auto req = "POST /test HTTP/1.1\r\n"
  18062. "Content-Length: x\r\n"
  18063. "\r\n";
  18064. std::string response;
  18065. ASSERT_TRUE(send_request(1, req, &response));
  18066. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18067. response.substr(0, response.find("\r\n")));
  18068. }
  18069. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18070. // case-insensitive, and a server that receives a 100-continue expectation in
  18071. // an HTTP/1.0 request MUST ignore it.
  18072. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18073. std::string response;
  18074. ASSERT_TRUE(send_request(1, req, &response, port));
  18075. *got_100 = response.find("100 Continue") != std::string::npos;
  18076. }
  18077. class ExpectTokenTest : public ::testing::Test {
  18078. protected:
  18079. void SetUp() override {
  18080. svr_.Post("/p", [](const Request &, Response &res) {
  18081. res.set_content("ok", "text/plain");
  18082. });
  18083. port_ = svr_.bind_to_any_port(HOST);
  18084. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18085. svr_.wait_until_ready();
  18086. }
  18087. void TearDown() override {
  18088. svr_.stop();
  18089. if (thread_.joinable()) { thread_.join(); }
  18090. }
  18091. std::string request(const char *version, const char *expect_value) const {
  18092. return std::string("POST /p ") + version +
  18093. "\r\n"
  18094. "Host: localhost\r\n"
  18095. "Content-Length: 2\r\n"
  18096. "Connection: close\r\n"
  18097. "Expect: " +
  18098. expect_value +
  18099. "\r\n"
  18100. "\r\n"
  18101. "hi";
  18102. }
  18103. Server svr_;
  18104. int port_ = 0;
  18105. thread thread_;
  18106. };
  18107. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18108. bool got_100 = false;
  18109. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18110. EXPECT_TRUE(got_100);
  18111. }
  18112. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18113. bool got_100 = true;
  18114. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18115. EXPECT_FALSE(got_100);
  18116. }
  18117. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18118. bool got_100 = false;
  18119. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18120. EXPECT_TRUE(got_100);
  18121. }
  18122. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18123. bool got_100 = false;
  18124. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18125. EXPECT_TRUE(got_100);
  18126. }
  18127. // `100 Continue` is sent only when the server starts reading the body, so a
  18128. // request rejected before that never invites the client to send it. The
  18129. // requests below carry the expectation but withhold the body, as a client
  18130. // waiting for `100 Continue` would.
  18131. // A POST that expects `100 Continue` and withholds its two-byte body.
  18132. static std::string expect_headers_only(const std::string &path) {
  18133. return "POST " + path +
  18134. " HTTP/1.1\r\n"
  18135. "Host: localhost\r\n"
  18136. "Content-Length: 2\r\n"
  18137. "Expect: 100-continue\r\n"
  18138. "\r\n";
  18139. }
  18140. class ExpectLazyContinueTest : public ::testing::Test {
  18141. protected:
  18142. void SetUp() override {
  18143. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18144. if (req.path == "/pre-routing") {
  18145. res.status = StatusCode::Unauthorized_401;
  18146. return Server::HandlerResponse::Handled;
  18147. }
  18148. return Server::HandlerResponse::Unhandled;
  18149. });
  18150. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18151. if (req.matched_route == "/pre-request") {
  18152. res.status = StatusCode::Forbidden_403;
  18153. return Server::HandlerResponse::Handled;
  18154. }
  18155. return Server::HandlerResponse::Unhandled;
  18156. });
  18157. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18158. res.set_content("ok", "text/plain");
  18159. });
  18160. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18161. res.set_content("ok", "text/plain");
  18162. });
  18163. svr_.Post("/reader-used", [](const Request &, Response &res,
  18164. const ContentReader &content_reader) {
  18165. std::string body;
  18166. content_reader([&](const char *data, size_t len) {
  18167. body.append(data, len);
  18168. return true;
  18169. });
  18170. res.set_content(body, "text/plain");
  18171. });
  18172. svr_.Post("/reader-unused",
  18173. [](const Request &, Response &res, const ContentReader &) {
  18174. res.set_content("ignored", "text/plain");
  18175. });
  18176. port_ = svr_.bind_to_any_port(HOST);
  18177. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18178. svr_.wait_until_ready();
  18179. }
  18180. void TearDown() override {
  18181. svr_.stop();
  18182. if (thread_.joinable()) { thread_.join(); }
  18183. }
  18184. // Sends `req` and reads until the server closes the connection. Returns
  18185. // false if the read had to wait for the client-side timeout instead.
  18186. bool send_until_closed(const std::string &req, std::string *resp) const {
  18187. auto start = std::chrono::steady_clock::now();
  18188. if (!send_request(3, req, resp, port_)) { return false; }
  18189. auto elapsed = std::chrono::steady_clock::now() - start;
  18190. return elapsed < std::chrono::seconds(2);
  18191. }
  18192. // The final response comes without `100 Continue`, and the server closes
  18193. // the connection since the body may or may not follow.
  18194. void expect_final_without_interim(const std::string &path,
  18195. const char *status_line) const {
  18196. std::string resp;
  18197. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18198. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18199. EXPECT_EQ(0u, resp.find(status_line));
  18200. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18201. }
  18202. Server svr_;
  18203. int port_ = 0;
  18204. thread thread_;
  18205. };
  18206. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18207. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18208. }
  18209. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18210. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18211. }
  18212. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18213. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18214. }
  18215. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18216. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18217. }
  18218. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18219. // The body follows once `100 Continue` has had time to arrive.
  18220. auto req = expect_headers_only("/reader-used");
  18221. req.insert(req.size() - 2, "Connection: close\r\n");
  18222. std::string resp;
  18223. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18224. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18225. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18226. EXPECT_NE(std::string::npos, resp.find("hi"));
  18227. }
  18228. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18229. // Large enough for the client to add `Expect: 100-continue` itself.
  18230. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18231. std::atomic<bool> body_sent{false};
  18232. Client cli(HOST, port_);
  18233. auto res = cli.Post(
  18234. "/pre-request", length,
  18235. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18236. body_sent = true;
  18237. std::string chunk(len, 'x');
  18238. sink.write(chunk.data(), chunk.size());
  18239. return true;
  18240. },
  18241. "application/octet-stream");
  18242. ASSERT_TRUE(res);
  18243. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18244. EXPECT_FALSE(body_sent);
  18245. }
  18246. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18247. Server svr;
  18248. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18249. return StatusCode::ExpectationFailed_417;
  18250. });
  18251. svr.Post("/p", [](const Request &, Response &res) {
  18252. res.set_content("ok", "text/plain");
  18253. });
  18254. auto port = svr.bind_to_any_port(HOST);
  18255. thread t = thread([&] { svr.listen_after_bind(); });
  18256. auto se = detail::scope_exit([&] {
  18257. svr.stop();
  18258. t.join();
  18259. });
  18260. svr.wait_until_ready();
  18261. std::string resp;
  18262. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18263. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18264. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18265. // Exactly one response: the route handler must not run after the 417.
  18266. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18267. }
  18268. #ifndef _WIN32
  18269. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18270. static constexpr char reject[] = "Unauthorized";
  18271. static constexpr char accept[] = "Upload accepted";
  18272. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18273. Server svr;
  18274. svr.set_expect_100_continue_handler(
  18275. [](const Request & /*req*/, Response &res) {
  18276. res.status = StatusCode::Unauthorized_401;
  18277. res.set_content(reject, "text/plain");
  18278. return res.status;
  18279. });
  18280. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18281. res.set_content(accept, "text/plain");
  18282. });
  18283. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18284. auto se = detail::scope_exit([&] {
  18285. svr.stop();
  18286. thread.join();
  18287. ASSERT_FALSE(svr.is_running());
  18288. });
  18289. svr.wait_until_ready();
  18290. {
  18291. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18292. curl_easy_init(), &curl_easy_cleanup};
  18293. ASSERT_NE(curl, nullptr);
  18294. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18295. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18296. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18297. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18298. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18299. &curl_slist_free_all};
  18300. ASSERT_NE(list, nullptr);
  18301. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18302. struct read_data {
  18303. uint64_t read_size;
  18304. uint64_t total_size;
  18305. } data = {0, total_size};
  18306. using read_callback_t =
  18307. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18308. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18309. void *userdata) -> size_t {
  18310. read_data *d = (read_data *)userdata;
  18311. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18312. std::fill_n(ptr, size * nmemb, 'A');
  18313. d->read_size += size * nmemb;
  18314. return size * nmemb;
  18315. };
  18316. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18317. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18318. std::vector<char> buffer;
  18319. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18320. using write_callback_t =
  18321. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18322. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18323. void *userdata) -> size_t {
  18324. std::vector<char> *buf = (std::vector<char> *)userdata;
  18325. buf->reserve(buf->size() + size * nmemb + 1);
  18326. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18327. return size * nmemb;
  18328. };
  18329. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18330. {
  18331. const auto res = curl_easy_perform(curl.get());
  18332. ASSERT_EQ(res, CURLE_OK);
  18333. }
  18334. {
  18335. auto response_code = long{};
  18336. const auto res =
  18337. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18338. ASSERT_EQ(res, CURLE_OK);
  18339. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18340. }
  18341. {
  18342. auto dl = curl_off_t{};
  18343. const auto res =
  18344. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18345. ASSERT_EQ(res, CURLE_OK);
  18346. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18347. }
  18348. {
  18349. buffer.push_back('\0');
  18350. ASSERT_STRCASEEQ(buffer.data(), reject);
  18351. }
  18352. }
  18353. }
  18354. #endif
  18355. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18356. // Regression test for #2458.
  18357. //
  18358. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18359. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18360. // ticket can make the client socket spuriously readable during the
  18361. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18362. // the client withholds the body and then blocks reading a response that never
  18363. // comes, failing with `Failed to read connection`.
  18364. //
  18365. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18366. // within the timeout. This raw OpenSSL server deliberately never sends
  18367. // `100 Continue`; the client must still deliver the body and receive 200.
  18368. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18369. signal(SIGPIPE, SIG_IGN);
  18370. const auto port = PORT + 4;
  18371. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18372. ASSERT_NE(srv, INVALID_SOCKET);
  18373. int opt = 1;
  18374. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18375. sockaddr_in addr{};
  18376. addr.sin_family = AF_INET;
  18377. addr.sin_port = htons(static_cast<uint16_t>(port));
  18378. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18379. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18380. ASSERT_EQ(0, ::listen(srv, 1));
  18381. std::atomic<size_t> server_body_bytes{0};
  18382. auto server_thread = std::thread([&] {
  18383. sockaddr_in cli_addr{};
  18384. socklen_t cli_len = sizeof(cli_addr);
  18385. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18386. if (cli == INVALID_SOCKET) { return; }
  18387. // Bound the lifetime of the server side so a buggy client (which never
  18388. // sends the body) cannot make this thread block forever on join.
  18389. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18390. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18391. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18392. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18393. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18394. SSL *ssl = SSL_new(ctx);
  18395. SSL_set_fd(ssl, static_cast<int>(cli));
  18396. if (SSL_accept(ssl) > 0) {
  18397. // Read the request headers. Reading here also flushes the TLS 1.3
  18398. // session tickets to the client. Deliberately do NOT send
  18399. // `100 Continue`.
  18400. std::string buf;
  18401. char tmp[1024];
  18402. while (buf.find("\r\n\r\n") == std::string::npos) {
  18403. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18404. if (n <= 0) { break; }
  18405. buf.append(tmp, static_cast<size_t>(n));
  18406. }
  18407. // A correct client sends the body now; count what arrives.
  18408. auto pos = buf.find("\r\n\r\n");
  18409. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18410. while (body < 4096) {
  18411. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18412. if (n <= 0) { break; }
  18413. body += static_cast<size_t>(n);
  18414. }
  18415. server_body_bytes = body;
  18416. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18417. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18418. SSL_shutdown(ssl);
  18419. }
  18420. SSL_free(ssl);
  18421. detail::close_socket(cli);
  18422. SSL_CTX_free(ctx);
  18423. });
  18424. auto se = detail::scope_exit([&] {
  18425. server_thread.join();
  18426. detail::close_socket(srv);
  18427. });
  18428. SSLClient cli("127.0.0.1", port);
  18429. cli.enable_server_certificate_verification(false);
  18430. cli.set_connection_timeout(5, 0);
  18431. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18432. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18433. std::string body(4096, 'A');
  18434. auto res = cli.Put("/api/test", body, "application/json");
  18435. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18436. EXPECT_EQ(StatusCode::OK_200, res->status);
  18437. EXPECT_EQ(body.size(), server_body_bytes.load());
  18438. }
  18439. #endif
  18440. template <typename S, typename C>
  18441. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18442. svr.Get("/stream", [&](const Request &, Response &res) {
  18443. auto data = new std::string("01234567890123456789");
  18444. res.set_content_provider(
  18445. data->size(), "text/plain",
  18446. [&, data](size_t offset, size_t length, DataSink &sink) {
  18447. const size_t DATA_CHUNK_SIZE = 4;
  18448. const auto &d = *data;
  18449. std::this_thread::sleep_for(std::chrono::seconds(1));
  18450. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18451. return true;
  18452. },
  18453. [data](bool success) {
  18454. EXPECT_FALSE(success);
  18455. delete data;
  18456. });
  18457. });
  18458. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18459. auto i = new size_t(0);
  18460. res.set_content_provider(
  18461. "text/plain",
  18462. [i](size_t, DataSink &sink) {
  18463. if (*i < 5) {
  18464. std::this_thread::sleep_for(std::chrono::seconds(1));
  18465. sink.write("abcd", 4);
  18466. (*i)++;
  18467. } else {
  18468. sink.done();
  18469. }
  18470. return true;
  18471. },
  18472. [i](bool success) {
  18473. EXPECT_FALSE(success);
  18474. delete i;
  18475. });
  18476. });
  18477. svr.Get("/chunked", [&](const Request &, Response &res) {
  18478. auto i = new size_t(0);
  18479. res.set_chunked_content_provider(
  18480. "text/plain",
  18481. [i](size_t, DataSink &sink) {
  18482. if (*i < 5) {
  18483. std::this_thread::sleep_for(std::chrono::seconds(1));
  18484. sink.os << "abcd";
  18485. (*i)++;
  18486. } else {
  18487. sink.done();
  18488. }
  18489. return true;
  18490. },
  18491. [i](bool success) {
  18492. EXPECT_FALSE(success);
  18493. delete i;
  18494. });
  18495. });
  18496. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18497. auto se = detail::scope_exit([&] {
  18498. svr.stop();
  18499. listen_thread.join();
  18500. ASSERT_FALSE(svr.is_running());
  18501. });
  18502. svr.wait_until_ready();
  18503. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18504. {
  18505. auto start = std::chrono::steady_clock::now();
  18506. auto res = cli.Get("/stream");
  18507. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18508. std::chrono::steady_clock::now() - start)
  18509. .count();
  18510. ASSERT_FALSE(res);
  18511. EXPECT_EQ(Error::Read, res.error());
  18512. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18513. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18514. }
  18515. {
  18516. auto start = std::chrono::steady_clock::now();
  18517. auto res = cli.Get("/stream_without_length");
  18518. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18519. std::chrono::steady_clock::now() - start)
  18520. .count();
  18521. ASSERT_FALSE(res);
  18522. EXPECT_EQ(Error::Read, res.error());
  18523. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18524. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18525. }
  18526. {
  18527. auto start = std::chrono::steady_clock::now();
  18528. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18529. EXPECT_EQ("abcd", string(data, data_length));
  18530. return true;
  18531. });
  18532. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18533. std::chrono::steady_clock::now() - start)
  18534. .count();
  18535. ASSERT_FALSE(res);
  18536. EXPECT_EQ(Error::Read, res.error());
  18537. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18538. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18539. }
  18540. }
  18541. TEST(MaxTimeoutTest, ContentStream) {
  18542. time_t timeout = 2000;
  18543. time_t threshold = 200;
  18544. Server svr;
  18545. Client cli("localhost", PORT);
  18546. max_timeout_test(svr, cli, timeout, threshold);
  18547. }
  18548. #ifdef CPPHTTPLIB_SSL_ENABLED
  18549. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18550. time_t timeout = 2000;
  18551. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18553. SSLClient cli("localhost", PORT);
  18554. cli.enable_server_certificate_verification(false);
  18555. max_timeout_test(svr, cli, timeout, threshold);
  18556. }
  18557. #endif
  18558. class EventDispatcher {
  18559. public:
  18560. EventDispatcher() {}
  18561. bool wait_event(DataSink *sink) {
  18562. unique_lock<mutex> lk(m_);
  18563. int id = id_;
  18564. // Wait with timeout to prevent hanging if client disconnects
  18565. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18566. [&] { return cid_ == id; })) {
  18567. return false; // Timeout occurred
  18568. }
  18569. sink->write(message_.data(), message_.size());
  18570. return true;
  18571. }
  18572. void send_event(const string &message) {
  18573. lock_guard<mutex> lk(m_);
  18574. cid_ = id_++;
  18575. message_ = message;
  18576. cv_.notify_all();
  18577. }
  18578. private:
  18579. mutex m_;
  18580. condition_variable cv_;
  18581. atomic_int id_{0};
  18582. atomic_int cid_{-1};
  18583. string message_;
  18584. };
  18585. TEST(ClientInThreadTest, Issue2068) {
  18586. EventDispatcher ed;
  18587. Server svr;
  18588. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18589. res.set_chunked_content_provider("text/event-stream",
  18590. [&](size_t /*offset*/, DataSink &sink) {
  18591. return ed.wait_event(&sink);
  18592. });
  18593. });
  18594. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18595. svr.wait_until_ready();
  18596. thread event_thread([&] {
  18597. int id = 0;
  18598. while (svr.is_running()) {
  18599. this_thread::sleep_for(chrono::milliseconds(500));
  18600. std::stringstream ss;
  18601. ss << "data: " << id << "\n\n";
  18602. ed.send_event(ss.str());
  18603. id++;
  18604. }
  18605. });
  18606. auto se = detail::scope_exit([&] {
  18607. svr.stop();
  18608. listen_thread.join();
  18609. event_thread.join();
  18610. ASSERT_FALSE(svr.is_running());
  18611. });
  18612. {
  18613. auto client = detail::make_unique<Client>(HOST, PORT);
  18614. client->set_read_timeout(std::chrono::minutes(10));
  18615. std::atomic<bool> stop{false};
  18616. std::thread t([&] {
  18617. client->Get("/event1",
  18618. [&](const char *, size_t) -> bool { return !stop; });
  18619. });
  18620. std::this_thread::sleep_for(std::chrono::seconds(2));
  18621. stop = true;
  18622. client->stop();
  18623. t.join();
  18624. // Reset client after thread has finished
  18625. client.reset();
  18626. }
  18627. }
  18628. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18629. auto handled = false;
  18630. Server svr;
  18631. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18632. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18633. auto se = detail::scope_exit([&] {
  18634. svr.stop();
  18635. t.join();
  18636. ASSERT_FALSE(svr.is_running());
  18637. ASSERT_FALSE(handled);
  18638. });
  18639. svr.wait_until_ready();
  18640. // Two Content-Length headers with different values — must be rejected
  18641. auto req = "POST /test HTTP/1.1\r\n"
  18642. "Content-Length: 5\r\n"
  18643. "Content-Length: 10\r\n"
  18644. "\r\n"
  18645. "hello";
  18646. std::string response;
  18647. ASSERT_TRUE(send_request(1, req, &response));
  18648. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18649. response.substr(0, response.find("\r\n")));
  18650. }
  18651. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18652. auto handled = false;
  18653. Server svr;
  18654. svr.Post("/test", [&](const Request &, Response &res) {
  18655. handled = true;
  18656. res.set_content("ok", "text/plain");
  18657. });
  18658. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18659. auto se = detail::scope_exit([&] {
  18660. svr.stop();
  18661. t.join();
  18662. ASSERT_FALSE(svr.is_running());
  18663. ASSERT_TRUE(handled);
  18664. });
  18665. svr.wait_until_ready();
  18666. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18667. auto req = "POST /test HTTP/1.1\r\n"
  18668. "Host: localhost\r\n"
  18669. "Content-Length: 5\r\n"
  18670. "Content-Length: 5\r\n"
  18671. "\r\n"
  18672. "hello";
  18673. std::string response;
  18674. ASSERT_TRUE(send_request(1, req, &response));
  18675. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18676. }
  18677. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18678. Server svr;
  18679. svr.Get("/test", [](const Request &, Response &res) {
  18680. res.set_content("ok", "text/plain");
  18681. });
  18682. auto port = svr.bind_to_any_port(HOST);
  18683. thread t = thread([&] { svr.listen_after_bind(); });
  18684. auto se = detail::scope_exit([&] {
  18685. svr.stop();
  18686. t.join();
  18687. ASSERT_FALSE(svr.is_running());
  18688. });
  18689. svr.wait_until_ready();
  18690. auto status_line = [&](const std::string &host_lines) {
  18691. std::string res;
  18692. send_request(
  18693. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18694. &res, port);
  18695. return res.substr(0, res.find("\r\n"));
  18696. };
  18697. const char *accepted[] = {
  18698. "Host: localhost\r\n",
  18699. "Host: a.example:8080\r\n",
  18700. "Host: my_service\r\n",
  18701. "Host: [::1]:8080\r\n",
  18702. "Host: [fe80::1%25eth0]\r\n",
  18703. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18704. };
  18705. for (auto host_lines : accepted) {
  18706. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18707. }
  18708. const char *rejected[] = {
  18709. "Host: a.example\r\nHost: b.example\r\n",
  18710. "Host: a.example\r\nHost: a.example\r\n",
  18711. "Host: a@b.example\r\n",
  18712. "Host: a.example/b\r\n",
  18713. "Host: a.example\\b\r\n",
  18714. "Host: a.example?b\r\n",
  18715. "Host: a.example#b\r\n",
  18716. "Host: a.example b.example\r\n",
  18717. };
  18718. for (auto host_lines : rejected) {
  18719. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18720. << host_lines;
  18721. }
  18722. }
  18723. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18724. Server svr;
  18725. svr.Get("/", [](const Request &req, Response &res) {
  18726. EXPECT_EQ(2U, req.trailers.size());
  18727. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18728. // Denied
  18729. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18730. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18731. // Accepted
  18732. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18733. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18734. EXPECT_TRUE(req.has_trailer("X-World"));
  18735. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18736. res.set_content("ok", "text/plain");
  18737. });
  18738. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18739. auto se = detail::scope_exit([&] {
  18740. svr.stop();
  18741. t.join();
  18742. ASSERT_FALSE(svr.is_running());
  18743. });
  18744. svr.wait_until_ready();
  18745. const std::string req = "GET / HTTP/1.1\r\n"
  18746. "Transfer-Encoding: chunked\r\n"
  18747. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18748. "\r\n"
  18749. "0\r\n"
  18750. "Content-Length: 10\r\n"
  18751. "Host: internal.local\r\n"
  18752. "Content-Type: malicious/content\r\n"
  18753. "Cookie: any\r\n"
  18754. "Set-Cookie: any\r\n"
  18755. "X-Forwarded-For: attacker.com\r\n"
  18756. "X-Real-Ip: 1.1.1.1\r\n"
  18757. "X-Hello: hello\r\n"
  18758. "X-World: world\r\n"
  18759. "\r\n";
  18760. std::string res;
  18761. ASSERT_TRUE(send_request(1, req, &res));
  18762. }
  18763. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18764. // several field lines, and the combined value is what has to be parsed. A
  18765. // Trailer field split across lines therefore declares every name it lists;
  18766. // reading only the first line silently drops the trailers the later lines
  18767. // declare. The prohibited-trailer filter still applies to every line.
  18768. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18769. Server svr;
  18770. size_t observed_trailer_count = 0;
  18771. std::string observed_hello;
  18772. std::string observed_world;
  18773. bool observed_content_length = true;
  18774. svr.Get("/", [&](const Request &req, Response &res) {
  18775. observed_trailer_count = req.trailers.size();
  18776. observed_hello = req.get_trailer_value("X-Hello");
  18777. observed_world = req.get_trailer_value("X-World");
  18778. observed_content_length = req.has_trailer("Content-Length");
  18779. res.set_content("ok", "text/plain");
  18780. });
  18781. auto port = svr.bind_to_any_port(HOST);
  18782. thread t = thread([&]() { svr.listen_after_bind(); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. const std::string req = "GET / HTTP/1.1\r\n"
  18790. "Host: localhost\r\n"
  18791. "Transfer-Encoding: chunked\r\n"
  18792. "Trailer: X-Hello\r\n"
  18793. "Trailer: X-World, Content-Length\r\n"
  18794. "\r\n"
  18795. "0\r\n"
  18796. "X-Hello: hello\r\n"
  18797. "X-World: world\r\n"
  18798. "Content-Length: 10\r\n"
  18799. "\r\n";
  18800. std::string res;
  18801. ASSERT_TRUE(send_request(1, req, &res, port));
  18802. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18803. // Accepted: both field lines contribute to the declared set
  18804. EXPECT_EQ(2U, observed_trailer_count);
  18805. EXPECT_EQ(observed_hello, "hello");
  18806. EXPECT_EQ(observed_world, "world");
  18807. // Denied: a prohibited name stays prohibited on a later field line
  18808. EXPECT_FALSE(observed_content_length);
  18809. }
  18810. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18811. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18812. // unbounded run of fields that are never declared, because the counter would
  18813. // only advance for declared fields.
  18814. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18815. Server svr;
  18816. bool handler_called = false;
  18817. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18818. handler_called = true;
  18819. res.set_content("ok", "text/plain");
  18820. });
  18821. auto port = svr.bind_to_any_port(HOST);
  18822. thread t = thread([&]() { svr.listen_after_bind(); });
  18823. auto se = detail::scope_exit([&] {
  18824. svr.stop();
  18825. t.join();
  18826. ASSERT_FALSE(svr.is_running());
  18827. });
  18828. svr.wait_until_ready();
  18829. // Declare nothing, then send far more undeclared trailer fields than the
  18830. // header-count limit. Parsing must stop and reject the request rather than
  18831. // read every line.
  18832. std::string req = "GET / HTTP/1.1\r\n"
  18833. "Transfer-Encoding: chunked\r\n"
  18834. "\r\n"
  18835. "0\r\n";
  18836. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18837. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18838. }
  18839. req += "\r\n";
  18840. std::string res;
  18841. ASSERT_TRUE(send_request(1, req, &res, port));
  18842. // The request is rejected before the handler runs.
  18843. EXPECT_FALSE(handler_called);
  18844. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18845. }
  18846. // The set of declared trailer names is capped so a peer cannot grow it without
  18847. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18848. // declared past the cap is not honored, even if the field is actually sent.
  18849. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18850. Server svr;
  18851. // One name inside the cap and one past it, so the test tracks the cap rather
  18852. // than a fixed count.
  18853. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18854. const std::string within_cap_name = "X-T-0";
  18855. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18856. bool observed_within_cap = false;
  18857. bool observed_past_cap = false;
  18858. svr.Get("/", [&](const Request &req, Response &res) {
  18859. observed_within_cap = req.has_trailer(within_cap_name);
  18860. observed_past_cap = req.has_trailer(past_cap_name);
  18861. res.set_content("ok", "text/plain");
  18862. });
  18863. auto port = svr.bind_to_any_port(HOST);
  18864. thread t = thread([&]() { svr.listen_after_bind(); });
  18865. auto se = detail::scope_exit([&] {
  18866. svr.stop();
  18867. t.join();
  18868. ASSERT_FALSE(svr.is_running());
  18869. });
  18870. svr.wait_until_ready();
  18871. // Declare more trailer names than the cap in a single Trailer field, then
  18872. // actually send the first (within the cap) and the last (past it).
  18873. std::string trailer_decl = "Trailer: ";
  18874. for (int i = 0; i < declared_count; i++) {
  18875. if (i != 0) { trailer_decl += ", "; }
  18876. trailer_decl += "X-T-" + std::to_string(i);
  18877. }
  18878. trailer_decl += "\r\n";
  18879. const std::string req = "GET / HTTP/1.1\r\n"
  18880. "Host: localhost\r\n"
  18881. "Transfer-Encoding: chunked\r\n" +
  18882. trailer_decl +
  18883. "\r\n"
  18884. "0\r\n" +
  18885. within_cap_name + ": a\r\n" + past_cap_name +
  18886. ": b\r\n"
  18887. "\r\n";
  18888. std::string res;
  18889. ASSERT_TRUE(send_request(1, req, &res, port));
  18890. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18891. // A name within the cap is honored; one declared past the cap is dropped.
  18892. EXPECT_TRUE(observed_within_cap);
  18893. EXPECT_FALSE(observed_past_cap);
  18894. }
  18895. // A direct client that is not listed in trusted_proxies must not be able to
  18896. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18897. // the peer address on the actual TCP connection determines whether the
  18898. // header is honored.
  18899. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18900. Server svr;
  18901. // Deliberately does NOT include the loopback address the test client
  18902. // actually connects from, so the direct connection is not a trusted proxy.
  18903. svr.set_trusted_proxies({"203.0.113.66"});
  18904. std::string observed_remote_addr;
  18905. svr.Get("/ip", [&](const Request &req, Response &res) {
  18906. observed_remote_addr = req.remote_addr;
  18907. res.set_content("ok", "text/plain");
  18908. });
  18909. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18910. auto se = detail::scope_exit([&] {
  18911. svr.stop();
  18912. t.join();
  18913. ASSERT_FALSE(svr.is_running());
  18914. });
  18915. svr.wait_until_ready();
  18916. Client cli(HOST, PORT);
  18917. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18919. EXPECT_EQ(StatusCode::OK_200, res->status);
  18920. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18921. // ignored entirely and the real connection-level address retained.
  18922. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18923. observed_remote_addr == "127.0.0.1");
  18924. }
  18925. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18926. Server svr;
  18927. std::string observed_remote_addr;
  18928. std::string observed_xff;
  18929. svr.Get("/ip", [&](const Request &req, Response &res) {
  18930. observed_remote_addr = req.remote_addr;
  18931. observed_xff = req.get_header_value("X-Forwarded-For");
  18932. res.set_content("ok", "text/plain");
  18933. });
  18934. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18935. auto se = detail::scope_exit([&] {
  18936. svr.stop();
  18937. t.join();
  18938. ASSERT_FALSE(svr.is_running());
  18939. });
  18940. svr.wait_until_ready();
  18941. Client cli(HOST, PORT);
  18942. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18944. EXPECT_EQ(StatusCode::OK_200, res->status);
  18945. EXPECT_EQ(observed_xff, "203.0.113.66");
  18946. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18947. observed_remote_addr == "127.0.0.1");
  18948. }
  18949. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18950. Server svr;
  18951. svr.set_trusted_proxies({"203.0.113.66"});
  18952. std::string observed_remote_addr;
  18953. std::string observed_xff;
  18954. svr.Get("/ip", [&](const Request &req, Response &res) {
  18955. observed_remote_addr = req.remote_addr;
  18956. observed_xff = req.get_header_value("X-Forwarded-For");
  18957. res.set_content("ok", "text/plain");
  18958. });
  18959. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18960. auto se = detail::scope_exit([&] {
  18961. svr.stop();
  18962. t.join();
  18963. ASSERT_FALSE(svr.is_running());
  18964. });
  18965. svr.wait_until_ready();
  18966. Client cli(HOST, PORT);
  18967. auto res = cli.Get("/ip");
  18968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18969. EXPECT_EQ(StatusCode::OK_200, res->status);
  18970. EXPECT_EQ(observed_xff, "");
  18971. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18972. observed_remote_addr == "127.0.0.1");
  18973. }
  18974. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18975. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18976. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18977. Server svr;
  18978. svr.set_trusted_proxies({"127.0.0.1"});
  18979. svr.Get("/ip", [](const Request &req, Response &res) {
  18980. res.set_content(req.remote_addr, "text/plain");
  18981. });
  18982. auto port = svr.bind_to_any_port("::");
  18983. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18984. thread t = thread([&] { svr.listen_after_bind(); });
  18985. auto se = detail::scope_exit([&] {
  18986. svr.stop();
  18987. t.join();
  18988. ASSERT_FALSE(svr.is_running());
  18989. });
  18990. svr.wait_until_ready();
  18991. Client cli("127.0.0.1", port);
  18992. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  18993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18994. EXPECT_EQ("198.51.100.23", res->body);
  18995. }
  18996. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  18997. Server svr;
  18998. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18999. svr.Get("/ip", [](const Request &req, Response &res) {
  19000. res.set_content(req.remote_addr, "text/plain");
  19001. });
  19002. auto port = svr.bind_to_any_port(HOST);
  19003. ASSERT_GT(port, 0);
  19004. thread t = thread([&] { svr.listen_after_bind(); });
  19005. auto se = detail::scope_exit([&] {
  19006. svr.stop();
  19007. t.join();
  19008. ASSERT_FALSE(svr.is_running());
  19009. });
  19010. svr.wait_until_ready();
  19011. Client cli(HOST, port);
  19012. auto res = cli.Get(
  19013. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19015. EXPECT_EQ("198.51.100.23", res->body);
  19016. }
  19017. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19018. Server svr;
  19019. // Include the loopback address the test client actually connects from, so
  19020. // the direct connection itself is recognized as the trusted proxy hop.
  19021. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19022. std::string observed_remote_addr;
  19023. std::string observed_xff;
  19024. svr.Get("/ip", [&](const Request &req, Response &res) {
  19025. observed_remote_addr = req.remote_addr;
  19026. observed_xff = req.get_header_value("X-Forwarded-For");
  19027. res.set_content("ok", "text/plain");
  19028. });
  19029. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19030. auto se = detail::scope_exit([&] {
  19031. svr.stop();
  19032. t.join();
  19033. ASSERT_FALSE(svr.is_running());
  19034. });
  19035. svr.wait_until_ready();
  19036. Client cli(HOST, PORT);
  19037. auto res = cli.Get(
  19038. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19040. EXPECT_EQ(StatusCode::OK_200, res->status);
  19041. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19042. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19043. }
  19044. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19045. Server svr;
  19046. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19047. std::string observed_remote_addr;
  19048. std::string observed_xff;
  19049. svr.Get("/ip", [&](const Request &req, Response &res) {
  19050. observed_remote_addr = req.remote_addr;
  19051. observed_xff = req.get_header_value("X-Forwarded-For");
  19052. res.set_content("ok", "text/plain");
  19053. });
  19054. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19055. auto se = detail::scope_exit([&] {
  19056. svr.stop();
  19057. t.join();
  19058. ASSERT_FALSE(svr.is_running());
  19059. });
  19060. svr.wait_until_ready();
  19061. Client cli(HOST, PORT);
  19062. auto res = cli.Get(
  19063. "/ip",
  19064. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19066. EXPECT_EQ(StatusCode::OK_200, res->status);
  19067. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19068. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19069. }
  19070. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19071. Server svr;
  19072. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19073. std::string observed_remote_addr;
  19074. std::string observed_xff;
  19075. svr.Get("/ip", [&](const Request &req, Response &res) {
  19076. observed_remote_addr = req.remote_addr;
  19077. observed_xff = req.get_header_value("X-Forwarded-For");
  19078. res.set_content("ok", "text/plain");
  19079. });
  19080. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19081. auto se = detail::scope_exit([&] {
  19082. svr.stop();
  19083. t.join();
  19084. ASSERT_FALSE(svr.is_running());
  19085. });
  19086. svr.wait_until_ready();
  19087. Client cli(HOST, PORT);
  19088. auto res = cli.Get(
  19089. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19091. EXPECT_EQ(StatusCode::OK_200, res->status);
  19092. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19093. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19094. // and must not be selected.
  19095. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19096. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19097. }
  19098. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19099. Server svr;
  19100. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19101. std::string observed_remote_addr;
  19102. svr.Get("/ip", [&](const Request &req, Response &res) {
  19103. observed_remote_addr = req.remote_addr;
  19104. res.set_content("ok", "text/plain");
  19105. });
  19106. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19107. auto se = detail::scope_exit([&] {
  19108. svr.stop();
  19109. t.join();
  19110. ASSERT_FALSE(svr.is_running());
  19111. });
  19112. svr.wait_until_ready();
  19113. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19114. // a forged address and the trusted proxy's own address; the forged value must
  19115. // not win over the address the trusted proxy actually recorded.
  19116. Client cli(HOST, PORT);
  19117. auto res = cli.Get(
  19118. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19120. EXPECT_EQ(StatusCode::OK_200, res->status);
  19121. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19122. }
  19123. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19124. Server svr;
  19125. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19126. std::string observed_remote_addr;
  19127. std::string observed_xff;
  19128. svr.Get("/ip", [&](const Request &req, Response &res) {
  19129. observed_remote_addr = req.remote_addr;
  19130. observed_xff = req.get_header_value("X-Forwarded-For");
  19131. res.set_content("ok", "text/plain");
  19132. });
  19133. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19134. auto se = detail::scope_exit([&] {
  19135. svr.stop();
  19136. t.join();
  19137. ASSERT_FALSE(svr.is_running());
  19138. });
  19139. svr.wait_until_ready();
  19140. Client cli(HOST, PORT);
  19141. auto res = cli.Get(
  19142. "/ip",
  19143. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19145. EXPECT_EQ(StatusCode::OK_200, res->status);
  19146. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19147. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19148. }
  19149. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19150. Server svr;
  19151. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19152. std::string observed_remote_addr;
  19153. std::string observed_xff;
  19154. svr.Get("/ip", [&](const Request &req, Response &res) {
  19155. observed_remote_addr = req.remote_addr;
  19156. observed_xff = req.get_header_value("X-Forwarded-For");
  19157. res.set_content("ok", "text/plain");
  19158. });
  19159. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19160. auto se = detail::scope_exit([&] {
  19161. svr.stop();
  19162. t.join();
  19163. ASSERT_FALSE(svr.is_running());
  19164. });
  19165. svr.wait_until_ready();
  19166. std::string raw_req =
  19167. "GET /ip HTTP/1.1\r\n"
  19168. "Host: localhost\r\n"
  19169. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19170. "Connection: close\r\n"
  19171. "\r\n";
  19172. std::string out;
  19173. ASSERT_TRUE(send_request(5, raw_req, &out));
  19174. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19175. // Header parser trims surrounding whitespace of the header value
  19176. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19177. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19178. }
  19179. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19180. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19181. // their own X-Forwarded-For as a separate field line rather than extending the
  19182. // one the client sent, so every occurrence has to be taken into account.
  19183. // Reading only the first one hands back the address the client chose.
  19184. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19185. Server svr;
  19186. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19187. std::string observed_remote_addr;
  19188. size_t observed_xff_count = 0;
  19189. svr.Get("/ip", [&](const Request &req, Response &res) {
  19190. observed_remote_addr = req.remote_addr;
  19191. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19192. res.set_content("ok", "text/plain");
  19193. });
  19194. auto port = svr.bind_to_any_port(HOST);
  19195. thread t = thread([&]() { svr.listen_after_bind(); });
  19196. auto se = detail::scope_exit([&] {
  19197. svr.stop();
  19198. t.join();
  19199. ASSERT_FALSE(svr.is_running());
  19200. });
  19201. svr.wait_until_ready();
  19202. // The client supplies the first field line; the trusted proxy appends the
  19203. // address it observed as a second one.
  19204. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19205. "Host: localhost\r\n"
  19206. "X-Forwarded-For: 1.2.3.4\r\n"
  19207. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19208. "Connection: close\r\n"
  19209. "\r\n";
  19210. std::string out;
  19211. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19212. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19213. EXPECT_EQ(observed_xff_count, 2U);
  19214. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19215. // The same chain spread over one field line per hop derives the same client
  19216. // address, i.e. the split and the comma-joined representations agree.
  19217. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19218. "Host: localhost\r\n"
  19219. "X-Forwarded-For: 1.2.3.4\r\n"
  19220. "X-Forwarded-For: 198.51.100.23\r\n"
  19221. "X-Forwarded-For: 192.0.2.45\r\n"
  19222. "Connection: close\r\n"
  19223. "\r\n";
  19224. out.clear();
  19225. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19226. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19227. EXPECT_EQ(observed_xff_count, 3U);
  19228. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19229. }
  19230. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19231. // crash the server (it used to call front() on an empty vector inside
  19232. // get_client_ip). The connection-level remote address must be retained instead.
  19233. static void run_malformed_xff_test(const std::string &xff_value) {
  19234. Server svr;
  19235. svr.set_trusted_proxies({"192.0.2.45"});
  19236. std::string observed_remote_addr;
  19237. svr.Get("/ip", [&](const Request &req, Response &res) {
  19238. observed_remote_addr = req.remote_addr;
  19239. res.set_content("ok", "text/plain");
  19240. });
  19241. int port = 0;
  19242. thread t = thread([&]() {
  19243. port = svr.bind_to_any_port(HOST);
  19244. svr.listen_after_bind();
  19245. });
  19246. auto se = detail::scope_exit([&] {
  19247. svr.stop();
  19248. t.join();
  19249. ASSERT_FALSE(svr.is_running());
  19250. });
  19251. svr.wait_until_ready();
  19252. Client cli(HOST, port);
  19253. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19255. EXPECT_EQ(StatusCode::OK_200, res->status);
  19256. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19257. observed_remote_addr == "127.0.0.1");
  19258. }
  19259. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19260. run_malformed_xff_test("");
  19261. }
  19262. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19263. run_malformed_xff_test(",");
  19264. }
  19265. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19266. run_malformed_xff_test(", , ,");
  19267. }
  19268. // The same rule applies to Accept: a request whose acceptable types are spread
  19269. // over several field lines must be negotiated against all of them.
  19270. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19271. // case-insensitive connection options. Comparing the whole field value against
  19272. // one option misses a client that sends several of them, and misses every
  19273. // casing but the one written in the comparison.
  19274. //
  19275. // Sends req, reads the response, then reuses the same socket for a second
  19276. // request to find out whether the server kept the connection.
  19277. static void probe_connection_reuse(int port, const std::string &req,
  19278. bool *announced_close, bool *reusable) {
  19279. auto error = Error::Success;
  19280. auto sock = detail::create_client_socket(
  19281. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19282. /*connection_timeout_sec=*/5, 0,
  19283. /*read_timeout_sec=*/1, 0,
  19284. /*write_timeout_sec=*/5, 0, std::string(), error);
  19285. ASSERT_NE(sock, INVALID_SOCKET);
  19286. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19287. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19288. "Host: localhost\r\n"
  19289. "Connection: close\r\n"
  19290. "\r\n";
  19291. std::string first_response;
  19292. std::string second_response;
  19293. detail::process_client_socket(
  19294. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19295. [&](Stream &strm) {
  19296. if (strm.write(req.data(), req.size()) !=
  19297. static_cast<ssize_t>(req.size())) {
  19298. return false;
  19299. }
  19300. char buf[512];
  19301. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19302. // Headers plus the two-byte body of the handler below
  19303. while (reader.getline()) {
  19304. first_response += reader.ptr();
  19305. if (first_response.find("ok") != std::string::npos) { break; }
  19306. }
  19307. if (strm.write(second.data(), second.size()) !=
  19308. static_cast<ssize_t>(second.size())) {
  19309. return true;
  19310. }
  19311. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19312. while (reader2.getline()) {
  19313. second_response += reader2.ptr();
  19314. if (second_response.find("ok") != std::string::npos) { break; }
  19315. }
  19316. return true;
  19317. });
  19318. *announced_close =
  19319. first_response.find("Connection: close") != std::string::npos;
  19320. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19321. }
  19322. class ConnectionTokenTest : public ::testing::Test {
  19323. protected:
  19324. void SetUp() override {
  19325. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19326. res.set_content("ok", "text/plain");
  19327. });
  19328. port_ = svr_.bind_to_any_port(HOST);
  19329. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19330. svr_.wait_until_ready();
  19331. }
  19332. void TearDown() override {
  19333. svr_.stop();
  19334. if (thread_.joinable()) { thread_.join(); }
  19335. }
  19336. Server svr_;
  19337. int port_ = 0;
  19338. thread thread_;
  19339. };
  19340. // "close" alongside another option still closes the connection, and the
  19341. // response says so rather than leaving the peer to discover it.
  19342. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19343. bool announced_close = false;
  19344. bool reusable = true;
  19345. probe_connection_reuse(port_,
  19346. "GET /keepalive HTTP/1.1\r\n"
  19347. "Host: localhost\r\n"
  19348. "Connection: keep-alive, close\r\n"
  19349. "\r\n",
  19350. &announced_close, &reusable);
  19351. EXPECT_TRUE(announced_close);
  19352. EXPECT_FALSE(reusable);
  19353. }
  19354. // "close" split over two field lines is the same list, so it is honored too.
  19355. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19356. bool announced_close = false;
  19357. bool reusable = true;
  19358. probe_connection_reuse(port_,
  19359. "GET /keepalive HTTP/1.1\r\n"
  19360. "Host: localhost\r\n"
  19361. "Connection: keep-alive\r\n"
  19362. "Connection: close\r\n"
  19363. "\r\n",
  19364. &announced_close, &reusable);
  19365. EXPECT_TRUE(announced_close);
  19366. EXPECT_FALSE(reusable);
  19367. }
  19368. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19369. // keep-alive in the spelling everyone actually sends keeps its connection.
  19370. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19371. bool announced_close = false;
  19372. bool reusable = false;
  19373. probe_connection_reuse(port_,
  19374. "GET /keepalive HTTP/1.0\r\n"
  19375. "Host: localhost\r\n"
  19376. "Connection: keep-alive\r\n"
  19377. "\r\n",
  19378. &announced_close, &reusable);
  19379. EXPECT_FALSE(announced_close);
  19380. EXPECT_TRUE(reusable);
  19381. }
  19382. // A token the value merely contains is not the token itself.
  19383. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19384. bool announced_close = false;
  19385. bool reusable = false;
  19386. probe_connection_reuse(port_,
  19387. "GET /keepalive HTTP/1.1\r\n"
  19388. "Host: localhost\r\n"
  19389. "Connection: notclose\r\n"
  19390. "\r\n",
  19391. &announced_close, &reusable);
  19392. EXPECT_FALSE(announced_close);
  19393. EXPECT_TRUE(reusable);
  19394. }
  19395. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19396. Server svr;
  19397. std::vector<std::string> observed_types;
  19398. svr.Get("/", [&](const Request &req, Response &res) {
  19399. observed_types = req.accept_content_types;
  19400. res.set_content("ok", "text/plain");
  19401. });
  19402. auto port = svr.bind_to_any_port(HOST);
  19403. thread t = thread([&]() { svr.listen_after_bind(); });
  19404. auto se = detail::scope_exit([&] {
  19405. svr.stop();
  19406. t.join();
  19407. ASSERT_FALSE(svr.is_running());
  19408. });
  19409. svr.wait_until_ready();
  19410. Client cli(HOST, port);
  19411. Headers headers;
  19412. headers.emplace("Accept", "text/plain;q=0.5");
  19413. headers.emplace("Accept", "application/json");
  19414. auto res = cli.Get("/", headers);
  19415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19416. EXPECT_EQ(StatusCode::OK_200, res->status);
  19417. // Sorted by q-value, so the second field line's type comes first
  19418. ASSERT_EQ(2U, observed_types.size());
  19419. EXPECT_EQ("application/json", observed_types[0]);
  19420. EXPECT_EQ("text/plain", observed_types[1]);
  19421. }
  19422. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19423. // empty field line must not contribute a bare comma to the combined value.
  19424. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19425. Server svr;
  19426. std::vector<std::string> observed_types;
  19427. svr.Get("/", [&](const Request &req, Response &res) {
  19428. observed_types = req.accept_content_types;
  19429. res.set_content("ok", "text/plain");
  19430. });
  19431. auto port = svr.bind_to_any_port(HOST);
  19432. thread t = thread([&]() { svr.listen_after_bind(); });
  19433. auto se = detail::scope_exit([&] {
  19434. svr.stop();
  19435. t.join();
  19436. ASSERT_FALSE(svr.is_running());
  19437. });
  19438. svr.wait_until_ready();
  19439. // Empty first field line, then a real one
  19440. std::string raw_req = "GET / HTTP/1.1\r\n"
  19441. "Host: localhost\r\n"
  19442. "Accept:\r\n"
  19443. "Accept: application/json\r\n"
  19444. "Connection: close\r\n"
  19445. "\r\n";
  19446. std::string out;
  19447. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19448. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19449. ASSERT_EQ(1U, observed_types.size());
  19450. EXPECT_EQ("application/json", observed_types[0]);
  19451. }
  19452. // The skip in get_combined_header_value() is what keeps an empty field line
  19453. // from contributing a bare comma. Only a trailing empty field line exercises
  19454. // it: a leading one is already covered by the "combined is still empty" check,
  19455. // and parse_accept_header() now ignores the empty element either way, so the
  19456. // request-level test above can no longer tell the two apart.
  19457. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19458. Headers headers;
  19459. headers.emplace("Accept", "text/html");
  19460. headers.emplace("Accept", "");
  19461. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19462. headers.clear();
  19463. headers.emplace("Accept", "");
  19464. headers.emplace("Accept", "application/json");
  19465. EXPECT_EQ("application/json",
  19466. detail::get_combined_header_value(headers, "Accept"));
  19467. }
  19468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19469. // An encoding offered on a later Accept-Encoding field line is still offered.
  19470. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19471. Server svr;
  19472. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19473. res.set_content(std::string(1024, 'x'), "text/plain");
  19474. });
  19475. auto port = svr.bind_to_any_port(HOST);
  19476. thread t = thread([&]() { svr.listen_after_bind(); });
  19477. auto se = detail::scope_exit([&] {
  19478. svr.stop();
  19479. t.join();
  19480. ASSERT_FALSE(svr.is_running());
  19481. });
  19482. svr.wait_until_ready();
  19483. Client cli(HOST, port);
  19484. cli.set_decompress(false);
  19485. Headers headers;
  19486. headers.emplace("Accept-Encoding", "identity");
  19487. headers.emplace("Accept-Encoding", "gzip");
  19488. auto res = cli.Get("/", headers);
  19489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19490. EXPECT_EQ(StatusCode::OK_200, res->status);
  19491. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19492. }
  19493. #endif
  19494. #ifndef _WIN32
  19495. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19496. Server svr;
  19497. svr.Post("/post", [&](const Request &req, Response &res) {
  19498. res.set_content(req.body, "text/plain");
  19499. });
  19500. svr.Put("/put", [&](const Request &req, Response &res) {
  19501. res.set_content(req.body, "text/plain");
  19502. });
  19503. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19504. res.set_content(req.body, "text/plain");
  19505. });
  19506. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19507. res.set_content(req.body, "text/plain");
  19508. });
  19509. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19510. auto se = detail::scope_exit([&] {
  19511. svr.stop();
  19512. t.join();
  19513. ASSERT_FALSE(svr.is_running());
  19514. });
  19515. svr.wait_until_ready();
  19516. std::string resp;
  19517. // POST without Content-Length
  19518. ASSERT_TRUE(send_request(5,
  19519. "POST /post HTTP/1.1\r\n"
  19520. "Host: localhost\r\n"
  19521. "Connection: close\r\n"
  19522. "\r\n",
  19523. &resp));
  19524. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19525. // PUT without Content-Length
  19526. resp.clear();
  19527. ASSERT_TRUE(send_request(5,
  19528. "PUT /put HTTP/1.1\r\n"
  19529. "Host: localhost\r\n"
  19530. "Connection: close\r\n"
  19531. "\r\n",
  19532. &resp));
  19533. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19534. // PATCH without Content-Length
  19535. resp.clear();
  19536. ASSERT_TRUE(send_request(5,
  19537. "PATCH /patch HTTP/1.1\r\n"
  19538. "Host: localhost\r\n"
  19539. "Connection: close\r\n"
  19540. "\r\n",
  19541. &resp));
  19542. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19543. // DELETE without Content-Length
  19544. resp.clear();
  19545. ASSERT_TRUE(send_request(5,
  19546. "DELETE /delete HTTP/1.1\r\n"
  19547. "Host: localhost\r\n"
  19548. "Connection: close\r\n"
  19549. "\r\n",
  19550. &resp));
  19551. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19552. }
  19553. #endif
  19554. //==============================================================================
  19555. // open_stream() Tests
  19556. //==============================================================================
  19557. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19558. std::string result;
  19559. char buf[8192];
  19560. ssize_t n;
  19561. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19562. result.append(buf, static_cast<size_t>(n));
  19563. }
  19564. return result;
  19565. }
  19566. // Mock stream for unit tests
  19567. class MockStream : public Stream {
  19568. public:
  19569. std::string data;
  19570. size_t pos = 0;
  19571. ssize_t error_after = -1; // -1 = no error
  19572. explicit MockStream(const std::string &d, ssize_t err = -1)
  19573. : data(d), error_after(err) {}
  19574. bool is_readable() const override { return true; }
  19575. bool wait_readable() const override { return true; }
  19576. bool wait_writable() const override { return true; }
  19577. ssize_t read(char *ptr, size_t size) override {
  19578. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19579. if (pos >= data.size()) return 0;
  19580. size_t limit =
  19581. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19582. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19583. std::memcpy(ptr, data.data() + pos, to_read);
  19584. pos += to_read;
  19585. return static_cast<ssize_t>(to_read);
  19586. }
  19587. ssize_t write(const char *, size_t) override { return -1; }
  19588. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19589. ip = "127.0.0.1";
  19590. port = 0;
  19591. }
  19592. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19593. ip = "127.0.0.1";
  19594. port = 0;
  19595. }
  19596. socket_t socket() const override { return INVALID_SOCKET; }
  19597. time_t duration() const override { return 0; }
  19598. };
  19599. TEST(StreamHandleTest, Basic) {
  19600. ClientImpl::StreamHandle handle;
  19601. EXPECT_FALSE(handle.is_valid());
  19602. handle.response = detail::make_unique<Response>();
  19603. handle.error = Error::Connection;
  19604. EXPECT_FALSE(handle.is_valid());
  19605. handle.error = Error::Success;
  19606. EXPECT_TRUE(handle.is_valid());
  19607. }
  19608. TEST(BodyReaderTest, Basic) {
  19609. MockStream stream("Hello, World!");
  19610. detail::BodyReader reader;
  19611. reader.stream = &stream;
  19612. reader.content_length = 13;
  19613. char buf[32];
  19614. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19615. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19616. EXPECT_TRUE(reader.eof);
  19617. }
  19618. TEST(BodyReaderTest, NoStream) {
  19619. detail::BodyReader reader;
  19620. char buf[32];
  19621. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19622. EXPECT_EQ(Error::Connection, reader.last_error);
  19623. }
  19624. TEST(BodyReaderTest, Error) {
  19625. MockStream stream("Hello, World!", 5);
  19626. detail::BodyReader reader;
  19627. reader.stream = &stream;
  19628. reader.content_length = 13;
  19629. char buf[32];
  19630. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19631. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19632. EXPECT_EQ(Error::Read, reader.last_error);
  19633. }
  19634. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19635. // Mock-based StreamHandle tests relying on private internals are removed.
  19636. class OpenStreamTest : public ::testing::Test {
  19637. protected:
  19638. void SetUp() override {
  19639. svr_.Get("/hello", [](const Request &, Response &res) {
  19640. res.set_content("Hello World!", "text/plain");
  19641. });
  19642. svr_.Get("/large", [](const Request &, Response &res) {
  19643. res.set_content(std::string(10000, 'X'), "text/plain");
  19644. });
  19645. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19646. res.set_content("Hello World!", "image/jpeg");
  19647. res.set_header("Content-Encoding", "UTF-8");
  19648. });
  19649. svr_.Get("/chunked", [](const Request &, Response &res) {
  19650. res.set_chunked_content_provider("text/plain",
  19651. [](size_t offset, DataSink &sink) {
  19652. if (offset < 15) {
  19653. sink.write("chunk", 5);
  19654. return true;
  19655. }
  19656. sink.done();
  19657. return true;
  19658. });
  19659. });
  19660. svr_.Get("/compressible", [](const Request &, Response &res) {
  19661. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19662. DataSink &sink) {
  19663. if (offset < 100 * 1024) {
  19664. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19665. sink.write(chunk.data(), chunk.size());
  19666. return true;
  19667. }
  19668. sink.done();
  19669. return true;
  19670. });
  19671. });
  19672. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19673. [](const Request & /*req*/, Response &res) {
  19674. auto i = new int(0);
  19675. res.set_header("Trailer", "Content-Length, X-Allowed");
  19676. res.set_chunked_content_provider(
  19677. "text/plain",
  19678. [i](size_t /*offset*/, DataSink &sink) {
  19679. switch (*i) {
  19680. case 0: sink.os << "123"; break;
  19681. case 1: sink.os << "456"; break;
  19682. case 2: sink.os << "789"; break;
  19683. case 3: {
  19684. sink.done_with_trailer(
  19685. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19686. } break;
  19687. }
  19688. (*i)++;
  19689. return true;
  19690. },
  19691. [i](bool success) {
  19692. EXPECT_TRUE(success);
  19693. delete i;
  19694. });
  19695. });
  19696. // Echo headers endpoint for header-related tests
  19697. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19698. std::string body;
  19699. for (const auto &h : req.headers) {
  19700. body.append(h.first);
  19701. body.push_back(':');
  19702. body.append(h.second);
  19703. body.push_back('\n');
  19704. }
  19705. res.set_content(body, "text/plain");
  19706. });
  19707. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19708. std::string body;
  19709. for (const auto &h : req.headers) {
  19710. body.append(h.first);
  19711. body.push_back(':');
  19712. body.append(h.second);
  19713. body.push_back('\n');
  19714. }
  19715. res.set_content(body, "text/plain");
  19716. });
  19717. port_ = svr_.bind_to_any_port("127.0.0.1");
  19718. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19719. svr_.wait_until_ready();
  19720. }
  19721. void TearDown() override {
  19722. svr_.stop();
  19723. if (thread_.joinable()) thread_.join();
  19724. }
  19725. Server svr_;
  19726. std::thread thread_;
  19727. int port_ = 0;
  19728. };
  19729. TEST_F(OpenStreamTest, Basic) {
  19730. Client cli("127.0.0.1", port_);
  19731. auto handle = cli.open_stream("GET", "/hello");
  19732. EXPECT_TRUE(handle.is_valid());
  19733. EXPECT_EQ("Hello World!", read_all(handle));
  19734. }
  19735. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19736. Client cli("127.0.0.1", port_);
  19737. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19738. ASSERT_TRUE(handle.is_valid());
  19739. EXPECT_EQ("Hello World!", read_all(handle));
  19740. }
  19741. TEST_F(OpenStreamTest, SmallBuffer) {
  19742. Client cli("127.0.0.1", port_);
  19743. auto handle = cli.open_stream("GET", "/hello");
  19744. std::string result;
  19745. char buf[4];
  19746. ssize_t n;
  19747. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19748. result.append(buf, static_cast<size_t>(n));
  19749. EXPECT_EQ("Hello World!", result);
  19750. }
  19751. TEST_F(OpenStreamTest, DefaultHeaders) {
  19752. Client cli("127.0.0.1", port_);
  19753. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19754. {
  19755. auto handle = cli.open_stream("GET", "/echo-headers");
  19756. ASSERT_TRUE(handle.is_valid());
  19757. auto body = read_all(handle);
  19758. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19759. std::string::npos);
  19760. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19761. std::string::npos);
  19762. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19763. }
  19764. // open_stream POST with body and no explicit content_type should NOT add
  19765. // text/plain Content-Type (behavior differs from non-streaming path), but
  19766. // should include Content-Length
  19767. {
  19768. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19769. ASSERT_TRUE(handle.is_valid());
  19770. auto body = read_all(handle);
  19771. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19772. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19773. }
  19774. // open_stream POST with explicit Content-Type should preserve it
  19775. {
  19776. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19777. {{"Content-Type", "application/custom"}},
  19778. "{}", "application/custom");
  19779. ASSERT_TRUE(handle.is_valid());
  19780. auto body = read_all(handle);
  19781. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19782. }
  19783. // User-specified User-Agent must not be overwritten for stream API
  19784. {
  19785. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19786. {{"User-Agent", "MyAgent/1.2"}});
  19787. ASSERT_TRUE(handle.is_valid());
  19788. auto body = read_all(handle);
  19789. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19790. }
  19791. }
  19792. TEST_F(OpenStreamTest, Large) {
  19793. Client cli("127.0.0.1", port_);
  19794. auto handle = cli.open_stream("GET", "/large");
  19795. EXPECT_EQ(10000u, read_all(handle).size());
  19796. }
  19797. TEST_F(OpenStreamTest, ConnectionError) {
  19798. Client cli("127.0.0.1", 9999);
  19799. auto handle = cli.open_stream("GET", "/hello");
  19800. EXPECT_FALSE(handle.is_valid());
  19801. }
  19802. TEST_F(OpenStreamTest, Chunked) {
  19803. Client cli("127.0.0.1", port_);
  19804. auto handle = cli.open_stream("GET", "/chunked");
  19805. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19806. "Transfer-Encoding") == "chunked");
  19807. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19808. }
  19809. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19810. Client cli("127.0.0.1", port_);
  19811. auto handle =
  19812. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19813. ASSERT_TRUE(handle.is_valid());
  19814. // Consume body to allow trailers to be received/parsed
  19815. auto body = read_all(handle);
  19816. // Explicitly parse trailers (ensure trailers are available for assertion)
  19817. handle.parse_trailers_if_needed();
  19818. EXPECT_EQ(std::string("123456789"), body);
  19819. // The response should include a Trailer header declaring both names
  19820. ASSERT_TRUE(handle.response);
  19821. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19822. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19823. handle.response->get_header_value("Trailer"));
  19824. // Prohibited trailer must not be present
  19825. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19826. // Allowed trailer should be present
  19827. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19828. EXPECT_EQ(std::string("yes"),
  19829. handle.response->get_trailer_value("X-Allowed"));
  19830. // Verify trailers are NOT present as regular headers
  19831. EXPECT_EQ(std::string(""),
  19832. handle.response->get_header_value("Content-Length"));
  19833. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19834. }
  19835. // Accepts one connection on an OS-assigned port, which it hands over through
  19836. // port_promise, reads the request head and sends back response. after_send,
  19837. // if given, runs on the connection before it is closed.
  19838. static std::thread
  19839. serve_single_response(std::promise<int> &port_promise,
  19840. const std::string &response,
  19841. std::function<void(socket_t)> after_send = nullptr) {
  19842. return std::thread([&port_promise, response, after_send] {
  19843. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19844. default_socket_options(srv);
  19845. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19846. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19847. sockaddr_in addr{};
  19848. addr.sin_family = AF_INET;
  19849. addr.sin_port = htons(0); // Let OS assign a free port
  19850. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19851. int opt = 1;
  19852. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19853. #ifdef _WIN32
  19854. reinterpret_cast<const char *>(&opt),
  19855. #else
  19856. &opt,
  19857. #endif
  19858. sizeof(opt));
  19859. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19860. ::listen(srv, 1) != 0) {
  19861. port_promise.set_value(-1);
  19862. detail::close_socket(srv);
  19863. return;
  19864. }
  19865. socklen_t addr_len = sizeof(addr);
  19866. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19867. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19868. sockaddr_in cli_addr{};
  19869. socklen_t cli_len = sizeof(cli_addr);
  19870. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19871. if (cli != INVALID_SOCKET) {
  19872. // Read the complete HTTP request (until the blank line that terminates
  19873. // headers) before sending the response. If the server closes the socket
  19874. // while the client's request data is still unread in the kernel receive
  19875. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19876. // connection on both sides: it discards the client's receive buffer
  19877. // (which already holds our response) and causes any in-progress write on
  19878. // the client to fail with ECONNRESET. Reading all request data first
  19879. // ensures close() emits a graceful FIN.
  19880. {
  19881. char rbuf[256];
  19882. std::string req;
  19883. while (req.find("\r\n\r\n") == std::string::npos) {
  19884. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19885. if (n <= 0) { break; }
  19886. req.append(rbuf, static_cast<size_t>(n));
  19887. }
  19888. }
  19889. ::send(cli,
  19890. #ifdef _WIN32
  19891. static_cast<const char *>(response.c_str()),
  19892. static_cast<int>(response.size()),
  19893. #else
  19894. response.c_str(), response.size(),
  19895. #endif
  19896. 0);
  19897. if (after_send) { after_send(cli); }
  19898. detail::close_socket(cli);
  19899. }
  19900. detail::close_socket(srv);
  19901. });
  19902. }
  19903. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19904. #ifndef _WIN32
  19905. signal(SIGPIPE, SIG_IGN);
  19906. #endif
  19907. std::promise<int> port_promise;
  19908. auto port_future = port_promise.get_future();
  19909. auto server_thread =
  19910. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19911. "Content-Type: text/plain\r\n"
  19912. "Content-Length: not-a-number\r\n"
  19913. "Connection: close\r\n"
  19914. "\r\n"
  19915. "hello");
  19916. auto port = port_future.get();
  19917. ASSERT_GT(port, 0);
  19918. Client cli("127.0.0.1", port);
  19919. auto handle = cli.open_stream("GET", "/");
  19920. EXPECT_FALSE(handle.is_valid());
  19921. server_thread.join();
  19922. }
  19923. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19924. #ifndef _WIN32
  19925. signal(SIGPIPE, SIG_IGN);
  19926. #endif
  19927. std::promise<int> port_promise;
  19928. auto port_future = port_promise.get_future();
  19929. auto server_thread = serve_single_response(
  19930. port_promise, "HTTP/1.1 200 OK\r\n"
  19931. "Content-Type: text/plain\r\n"
  19932. "Content-Length: 99999999999999999999999999\r\n"
  19933. "Connection: close\r\n"
  19934. "\r\n"
  19935. "hello");
  19936. auto port = port_future.get();
  19937. ASSERT_GT(port, 0);
  19938. // Historically std::stoull would throw std::out_of_range here and crash
  19939. // the process, then parsing silently clamped to a bogus framing length and
  19940. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19941. // so the stream fails to open, matching the not-a-number case above. The
  19942. // process still must NOT terminate.
  19943. Client cli("127.0.0.1", port);
  19944. auto handle = cli.open_stream("GET", "/");
  19945. EXPECT_FALSE(handle.is_valid());
  19946. server_thread.join();
  19947. }
  19948. // Serves `response` to the single request `fn` makes with a fresh client.
  19949. template <typename Fn>
  19950. static void with_single_response(const std::string &response, Fn fn) {
  19951. #ifndef _WIN32
  19952. signal(SIGPIPE, SIG_IGN);
  19953. #endif
  19954. std::promise<int> port_promise;
  19955. auto port_future = port_promise.get_future();
  19956. auto server_thread = serve_single_response(port_promise, response);
  19957. auto se = detail::scope_exit([&] { server_thread.join(); });
  19958. auto port = port_future.get();
  19959. ASSERT_GT(port, 0);
  19960. Client cli("127.0.0.1", port);
  19961. fn(cli);
  19962. }
  19963. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19964. // Neither Content-Length nor chunked: the body ends at the close
  19965. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19966. "Connection: close\r\n"
  19967. "\r\n"
  19968. "hello";
  19969. with_single_response(close_delimited, [](Client &cli) {
  19970. auto handle = cli.open_stream("GET", "/");
  19971. ASSERT_TRUE(handle.is_valid());
  19972. EXPECT_EQ("hello", read_all(handle));
  19973. EXPECT_FALSE(handle.has_read_error());
  19974. });
  19975. // A close before the end of the Content-Length is still an error
  19976. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19977. "Content-Length: 10\r\n"
  19978. "\r\n"
  19979. "hello";
  19980. with_single_response(short_content_length, [](Client &cli) {
  19981. auto handle = cli.open_stream("GET", "/");
  19982. ASSERT_TRUE(handle.is_valid());
  19983. read_all(handle);
  19984. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19985. });
  19986. // So is a close before the last chunk
  19987. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19988. "Transfer-Encoding: chunked\r\n"
  19989. "\r\n"
  19990. "5\r\nhello\r\n";
  19991. with_single_response(short_chunked, [](Client &cli) {
  19992. auto handle = cli.open_stream("GET", "/");
  19993. ASSERT_TRUE(handle.is_valid());
  19994. read_all(handle);
  19995. EXPECT_TRUE(handle.has_read_error());
  19996. });
  19997. }
  19998. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19999. const char *responses[] = {
  20000. "HTTP/1.1 103 Early Hints\r\n"
  20001. "Link: </style.css>; rel=preload\r\n"
  20002. "\r\n"
  20003. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20004. "HTTP/1.1 100 Continue\r\n"
  20005. "X-Note: interim\r\n"
  20006. "\r\n"
  20007. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20008. };
  20009. for (auto response : responses) {
  20010. with_single_response(response, [](Client &cli) {
  20011. auto res = cli.Get("/");
  20012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20013. EXPECT_EQ(StatusCode::OK_200, res->status);
  20014. EXPECT_EQ("ok", res->body);
  20015. });
  20016. }
  20017. }
  20018. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20019. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20020. const std::string final_response =
  20021. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20022. std::string interims;
  20023. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20024. interims += interim;
  20025. }
  20026. with_single_response(interims + final_response, [](Client &cli) {
  20027. auto res = cli.Get("/");
  20028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20029. EXPECT_EQ("ok", res->body);
  20030. });
  20031. with_single_response(interims + interim + final_response, [](Client &cli) {
  20032. auto res = cli.Get("/");
  20033. ASSERT_FALSE(res);
  20034. EXPECT_EQ(Error::Read, res.error());
  20035. });
  20036. }
  20037. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20038. #ifndef _WIN32
  20039. signal(SIGPIPE, SIG_IGN);
  20040. #endif
  20041. // The server answers the head without asking for the body. Bytes it then
  20042. // reads on the connection would be taken for the body the request declared.
  20043. auto closed_by_client = false;
  20044. std::promise<int> port_promise;
  20045. auto server_thread = serve_single_response(
  20046. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20047. [&](socket_t sock) {
  20048. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20049. char buf[256];
  20050. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20051. });
  20052. Client cli("127.0.0.1", port_promise.get_future().get());
  20053. cli.set_keep_alive(true);
  20054. cli.set_read_timeout(1, 0);
  20055. // Long enough for the client to send Expect: 100-continue.
  20056. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20058. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20059. cli.Get("/second");
  20060. server_thread.join();
  20061. EXPECT_TRUE(closed_by_client);
  20062. }
  20063. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20064. // Long enough for the client to send Expect: 100-continue
  20065. with_single_response(
  20066. "HTTP/1.1 103 Early Hints\r\n"
  20067. "Link: </style.css>; rel=preload\r\n"
  20068. "\r\n"
  20069. "HTTP/1.1 401 Unauthorized\r\n"
  20070. "Content-Length: 0\r\n\r\n",
  20071. [](Client &cli) {
  20072. cli.set_read_timeout(2, 0);
  20073. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20075. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20076. });
  20077. }
  20078. #ifdef CPPHTTPLIB_SSL_ENABLED
  20079. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20080. #ifndef _WIN32
  20081. signal(SIGPIPE, SIG_IGN);
  20082. #endif
  20083. auto reused = false;
  20084. std::promise<int> port_promise;
  20085. auto server_thread = serve_single_response(
  20086. port_promise,
  20087. "HTTP/1.1 401 Unauthorized\r\n"
  20088. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20089. "Content-Length: 0\r\n\r\n",
  20090. [&](socket_t sock) {
  20091. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20092. char buf[256];
  20093. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20094. });
  20095. Client cli("127.0.0.1", port_promise.get_future().get());
  20096. cli.set_keep_alive(true);
  20097. cli.set_digest_auth("user", "pass");
  20098. cli.set_read_timeout(1, 0);
  20099. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20100. server_thread.join();
  20101. EXPECT_FALSE(reused);
  20102. }
  20103. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20104. // Any other answer to CONNECT would read as the origin's response.
  20105. struct {
  20106. const char *response;
  20107. bool passed_on;
  20108. } cases[] = {
  20109. {"HTTP/1.1 201 Created\r\n"
  20110. "Set-Cookie: session=from-proxy\r\n"
  20111. "Content-Length: 0\r\n\r\n",
  20112. false},
  20113. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20114. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20115. "Content-Length: 0\r\n\r\n",
  20116. true},
  20117. };
  20118. for (const auto &c : cases) {
  20119. std::promise<int> port_promise;
  20120. auto server_thread = serve_single_response(port_promise, c.response);
  20121. SSLClient cli("example.com", 443);
  20122. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20123. auto res = cli.Get("/");
  20124. server_thread.join();
  20125. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20126. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20127. if (res) {
  20128. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20129. }
  20130. }
  20131. }
  20132. #endif
  20133. // Records the client's error logger calls as "error METHOD path", or
  20134. // "error null" for a call without a request
  20135. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20136. return [&log](const Error &err, const Request *req) {
  20137. log.push_back(to_string(err) + " " +
  20138. (req ? req->method + " " + req->path : "null"));
  20139. };
  20140. }
  20141. // A failed request is reported once, with the request the caller made
  20142. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20143. Server svr;
  20144. svr.Get("/big", [](const Request &, Response &res) {
  20145. res.set_content(std::string(100000, 'b'), "text/plain");
  20146. });
  20147. auto port = svr.bind_to_any_port(HOST);
  20148. std::thread t([&]() { svr.listen_after_bind(); });
  20149. auto se = detail::scope_exit([&] {
  20150. svr.stop();
  20151. t.join();
  20152. });
  20153. svr.wait_until_ready();
  20154. Client cli(HOST, port);
  20155. std::vector<std::string> log;
  20156. cli.set_error_logger(record_errors(log));
  20157. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20158. cli.Get("/big", [](const char *, size_t) { return false; });
  20159. EXPECT_EQ(expected, log);
  20160. log.clear();
  20161. cli.Get("/big", [](size_t, size_t) { return false; });
  20162. EXPECT_EQ(expected, log);
  20163. }
  20164. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20165. // Fails while the body is read
  20166. auto broken = [](const Request &, Response &res) {
  20167. res.set_content_provider(10, "text/plain",
  20168. [](size_t, size_t, DataSink &) { return false; });
  20169. };
  20170. Server other;
  20171. other.Get("/broken", broken);
  20172. auto other_port = other.bind_to_any_port(HOST);
  20173. std::thread other_t([&]() { other.listen_after_bind(); });
  20174. auto other_se = detail::scope_exit([&] {
  20175. other.stop();
  20176. other_t.join();
  20177. });
  20178. other.wait_until_ready();
  20179. Server svr;
  20180. svr.Get("/broken", broken);
  20181. svr.Get("/same-origin",
  20182. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20183. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20184. res.set_redirect("http://" + std::string(HOST) + ":" +
  20185. std::to_string(other_port) + "/broken");
  20186. });
  20187. auto port = svr.bind_to_any_port(HOST);
  20188. std::thread t([&]() { svr.listen_after_bind(); });
  20189. auto se = detail::scope_exit([&] {
  20190. svr.stop();
  20191. t.join();
  20192. });
  20193. svr.wait_until_ready();
  20194. Client cli(HOST, port);
  20195. cli.set_follow_location(true);
  20196. std::vector<std::string> log;
  20197. cli.set_error_logger(record_errors(log));
  20198. for (auto path : {"/same-origin", "/cross-origin"}) {
  20199. log.clear();
  20200. auto res = cli.Get(path);
  20201. ASSERT_FALSE(res);
  20202. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20203. log);
  20204. }
  20205. }
  20206. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20207. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20208. std::vector<std::string> log;
  20209. cli.set_error_logger(record_errors(log));
  20210. auto handle = cli.open_stream("GET", "/x");
  20211. EXPECT_FALSE(handle.is_valid());
  20212. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20213. log);
  20214. });
  20215. }
  20216. #ifdef CPPHTTPLIB_SSL_ENABLED
  20217. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20218. // Not a TLS server, so the handshake fails. It waits for a request line in
  20219. // the handshake bytes, so a short read timeout lets it close quickly.
  20220. Server svr;
  20221. svr.set_read_timeout(0, 100000);
  20222. svr.Get("/x", [](const Request &, Response &res) {
  20223. res.set_content("x", "text/plain");
  20224. });
  20225. auto port = svr.bind_to_any_port(HOST);
  20226. std::thread t([&]() { svr.listen_after_bind(); });
  20227. auto se = detail::scope_exit([&] {
  20228. svr.stop();
  20229. t.join();
  20230. });
  20231. svr.wait_until_ready();
  20232. std::vector<std::string> log;
  20233. SSLClient cli(HOST, port);
  20234. cli.enable_server_certificate_verification(false);
  20235. cli.set_error_logger(record_errors(log));
  20236. auto res = cli.Get("/x");
  20237. ASSERT_FALSE(res);
  20238. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20239. log.clear();
  20240. auto handle = cli.open_stream("GET", "/x");
  20241. EXPECT_FALSE(handle.is_valid());
  20242. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20243. log.clear();
  20244. SSLClient no_ca(HOST, port);
  20245. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20246. no_ca.set_error_logger(record_errors(log));
  20247. res = no_ca.Get("/x");
  20248. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20249. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20250. }
  20251. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20252. #ifndef _WIN32
  20253. signal(SIGPIPE, SIG_IGN);
  20254. #endif
  20255. // Refused, answered with a challenge, or closed without an answer
  20256. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20257. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20258. "Content-Length: 0\r\n\r\n",
  20259. ""}) {
  20260. std::promise<int> port_promise;
  20261. auto server_thread = serve_single_response(port_promise, response);
  20262. SSLClient cli("example.com", 443);
  20263. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20264. std::vector<std::string> log;
  20265. cli.set_error_logger(record_errors(log));
  20266. auto res = cli.Get("/");
  20267. server_thread.join();
  20268. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20269. << response;
  20270. }
  20271. }
  20272. #endif
  20273. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20274. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20275. // the chunked coding and drop Content-Length, so a front-end that trusts
  20276. // Content-Length would disagree about where the body ends (response
  20277. // smuggling). The client must reject such a response.
  20278. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20279. for (const char *te : {"chunked", "gzip, chunked"}) {
  20280. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20281. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20282. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20283. "5\r\nhello\r\n0\r\n\r\n";
  20284. with_single_response(response, [&](Client &cli) {
  20285. auto res = cli.Get("/");
  20286. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20287. EXPECT_EQ(Error::Read, res.error()) << te;
  20288. });
  20289. with_single_response(response, [&](Client &cli) {
  20290. auto handle = cli.open_stream("GET", "/");
  20291. EXPECT_FALSE(handle.is_valid()) << te;
  20292. EXPECT_EQ(Error::Read, handle.error) << te;
  20293. });
  20294. }
  20295. }
  20296. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20297. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20298. // closing the connection (unlike a request, which must be rejected).
  20299. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20300. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20301. "Transfer-Encoding: chunked\r\n"
  20302. "Connection: close\r\n"
  20303. "\r\n"
  20304. "5\r\nhello\r\n0\r\n\r\n",
  20305. "HTTP/1.1 200 OK\r\n"
  20306. "Transfer-Encoding: gzip\r\n"
  20307. "Connection: close\r\n"
  20308. "\r\n"
  20309. "hello"}) {
  20310. with_single_response(response, [&](Client &cli) {
  20311. auto res = cli.Get("/");
  20312. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20313. EXPECT_EQ("hello", res->body);
  20314. });
  20315. with_single_response(response, [&](Client &cli) {
  20316. auto handle = cli.open_stream("GET", "/");
  20317. ASSERT_TRUE(handle.is_valid()) << response;
  20318. EXPECT_EQ("hello", read_all(handle));
  20319. });
  20320. }
  20321. }
  20322. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20323. // framing headers describe nothing to read and must not be rejected.
  20324. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20325. const std::string framing = "Content-Length: 5\r\n"
  20326. "Transfer-Encoding: chunked\r\n"
  20327. "Connection: close\r\n"
  20328. "\r\n";
  20329. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20330. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20331. });
  20332. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20333. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20334. });
  20335. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20336. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20337. with_single_response(response, [&](Client &cli) {
  20338. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20339. });
  20340. with_single_response(response, [&](Client &cli) {
  20341. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20342. });
  20343. }
  20344. }
  20345. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20346. // header section, so a stream opened on one has nothing to read, whatever
  20347. // framing or coding headers it carries.
  20348. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20349. struct Case {
  20350. const char *method;
  20351. const char *status;
  20352. };
  20353. // A reader of the declared body reports an early close when nothing
  20354. // follows, and hands back what does.
  20355. struct Framing {
  20356. const char *headers;
  20357. const char *after;
  20358. };
  20359. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20360. Case{"GET", "304 Not Modified"}}) {
  20361. for (const auto &f :
  20362. {Framing{"Content-Length: 5\r\n", ""},
  20363. Framing{"Content-Length: 5\r\n", "hello"},
  20364. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20365. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20366. // Not decoded, so a build without Brotli opens it too
  20367. Framing{"Content-Encoding: br\r\n", ""}}) {
  20368. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20369. "Connection: close\r\n"
  20370. "\r\n" +
  20371. f.after;
  20372. with_single_response(response, [&](Client &cli) {
  20373. auto handle = cli.open_stream(c.method, "/");
  20374. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20375. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20376. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20377. });
  20378. }
  20379. }
  20380. }
  20381. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20382. // response, is faulty framing, so the connection is not reused after it.
  20383. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20384. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20385. "Content-Length: 0\r\n"
  20386. "Transfer-Encoding: chunked\r\n"
  20387. "\r\n"
  20388. "5\r\nhello\r\n0\r\n\r\n",
  20389. "HTTP/1.0 200 Connection established\r\n"
  20390. "Connection: keep-alive\r\n"
  20391. "Transfer-Encoding: chunked\r\n"
  20392. "\r\n"
  20393. "5\r\nhello\r\n0\r\n\r\n"}) {
  20394. with_single_response(response, [&](Client &cli) {
  20395. cli.set_keep_alive(true);
  20396. auto res = cli.Get("/");
  20397. ASSERT_TRUE(res) << response;
  20398. EXPECT_EQ("hello", res->body);
  20399. EXPECT_FALSE(cli.is_socket_open()) << response;
  20400. });
  20401. }
  20402. }
  20403. // A payload max length of 0 means no limit, however the body is framed.
  20404. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20405. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20406. "Transfer-Encoding: chunked\r\n"
  20407. "\r\n"
  20408. "5\r\nhello\r\n0\r\n\r\n",
  20409. "HTTP/1.1 200 OK\r\n"
  20410. "Connection: close\r\n"
  20411. "\r\n"
  20412. "hello"}) {
  20413. with_single_response(response, [&](Client &cli) {
  20414. cli.set_payload_max_length(0);
  20415. auto res = cli.Get("/");
  20416. ASSERT_TRUE(res) << response;
  20417. EXPECT_EQ("hello", res->body) << response;
  20418. });
  20419. }
  20420. }
  20421. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20422. Server svr;
  20423. svr.set_payload_max_length(0);
  20424. svr.Post("/echo", [](const Request &req, Response &res) {
  20425. res.set_content(req.body, "text/plain");
  20426. });
  20427. auto port = svr.bind_to_any_port(HOST);
  20428. thread t = thread([&] { svr.listen_after_bind(); });
  20429. auto se = detail::scope_exit([&] {
  20430. svr.stop();
  20431. t.join();
  20432. ASSERT_FALSE(svr.is_running());
  20433. });
  20434. svr.wait_until_ready();
  20435. Client cli(HOST, port);
  20436. auto res = cli.Post(
  20437. "/echo",
  20438. [](size_t /*offset*/, DataSink &sink) {
  20439. sink.write("hello", 5);
  20440. sink.done();
  20441. return true;
  20442. },
  20443. "text/plain");
  20444. ASSERT_TRUE(res);
  20445. EXPECT_EQ(StatusCode::OK_200, res->status);
  20446. EXPECT_EQ("hello", res->body);
  20447. }
  20448. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20449. TEST_F(OpenStreamTest, Gzip) {
  20450. Client cli("127.0.0.1", port_);
  20451. auto handle = cli.open_stream("GET", "/compressible", {},
  20452. {{"Accept-Encoding", "gzip"}});
  20453. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20454. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20455. }
  20456. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20457. Client cli("127.0.0.1", port_);
  20458. auto handle =
  20459. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20460. {{"Accept-Encoding", "gzip"}});
  20461. ASSERT_TRUE(handle.is_valid());
  20462. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20463. EXPECT_EQ("123456789", read_all(handle));
  20464. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20465. }
  20466. #endif
  20467. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20468. TEST_F(OpenStreamTest, Brotli) {
  20469. Client cli("127.0.0.1", port_);
  20470. auto handle =
  20471. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20472. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20473. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20474. }
  20475. #endif
  20476. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20477. TEST_F(OpenStreamTest, Zstd) {
  20478. Client cli("127.0.0.1", port_);
  20479. auto handle = cli.open_stream("GET", "/compressible", {},
  20480. {{"Accept-Encoding", "zstd"}});
  20481. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20482. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20483. }
  20484. #endif
  20485. #ifdef CPPHTTPLIB_SSL_ENABLED
  20486. class SSLOpenStreamTest : public ::testing::Test {
  20487. protected:
  20488. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20489. void SetUp() override {
  20490. svr_.Get("/hello", [](const Request &, Response &res) {
  20491. res.set_content("Hello SSL World!", "text/plain");
  20492. });
  20493. svr_.Get("/chunked", [](const Request &, Response &res) {
  20494. res.set_chunked_content_provider("text/plain",
  20495. [](size_t offset, DataSink &sink) {
  20496. if (offset < 15) {
  20497. sink.write("chunk", 5);
  20498. return true;
  20499. }
  20500. sink.done();
  20501. return true;
  20502. });
  20503. });
  20504. svr_.Post("/echo", [](const Request &req, Response &res) {
  20505. res.set_content(req.body, req.get_header_value("Content-Type"));
  20506. });
  20507. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20508. std::string body = req.body;
  20509. res.set_chunked_content_provider(
  20510. "text/plain", [body](size_t offset, DataSink &sink) {
  20511. if (offset < body.size()) {
  20512. sink.write(body.data() + offset, body.size() - offset);
  20513. }
  20514. sink.done();
  20515. return true;
  20516. });
  20517. });
  20518. port_ = svr_.bind_to_any_port("127.0.0.1");
  20519. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20520. svr_.wait_until_ready();
  20521. }
  20522. void TearDown() override {
  20523. svr_.stop();
  20524. if (thread_.joinable()) thread_.join();
  20525. }
  20526. SSLServer svr_;
  20527. std::thread thread_;
  20528. int port_ = 0;
  20529. };
  20530. TEST_F(SSLOpenStreamTest, Basic) {
  20531. SSLClient cli("127.0.0.1", port_);
  20532. cli.enable_server_certificate_verification(false);
  20533. auto handle = cli.open_stream("GET", "/hello");
  20534. ASSERT_TRUE(handle.is_valid());
  20535. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20536. }
  20537. TEST_F(SSLOpenStreamTest, Chunked) {
  20538. SSLClient cli("127.0.0.1", port_);
  20539. cli.enable_server_certificate_verification(false);
  20540. auto handle = cli.open_stream("GET", "/chunked");
  20541. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20542. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20543. "Transfer-Encoding") == "chunked");
  20544. auto body = read_all(handle);
  20545. EXPECT_EQ("chunkchunkchunk", body);
  20546. }
  20547. TEST_F(SSLOpenStreamTest, Post) {
  20548. SSLClient cli("127.0.0.1", port_);
  20549. cli.enable_server_certificate_verification(false);
  20550. auto handle =
  20551. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20552. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20553. EXPECT_EQ(200, handle.response->status);
  20554. auto body = read_all(handle);
  20555. EXPECT_EQ("Hello SSL POST", body);
  20556. }
  20557. TEST_F(SSLOpenStreamTest, PostChunked) {
  20558. SSLClient cli("127.0.0.1", port_);
  20559. cli.enable_server_certificate_verification(false);
  20560. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20561. "Chunked SSL Data", "text/plain");
  20562. ASSERT_TRUE(handle.is_valid());
  20563. EXPECT_EQ(200, handle.response->status);
  20564. auto body = read_all(handle);
  20565. EXPECT_EQ("Chunked SSL Data", body);
  20566. }
  20567. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20568. // Content-Length is terminated by the server closing the connection. When the
  20569. // SSL peer sends a close_notify after the body, the client must treat it as a
  20570. // clean EOF and return a successful response rather than an error.
  20571. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20572. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20573. ASSERT_TRUE(svr.is_valid());
  20574. svr.set_keep_alive_max_count(1);
  20575. const std::string expected_body = "Hello from connection-close response!";
  20576. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20577. res.set_content_provider("text/plain",
  20578. [&](size_t offset, DataSink &sink) -> bool {
  20579. if (offset < expected_body.size()) {
  20580. sink.write(expected_body.data() + offset,
  20581. expected_body.size() - offset);
  20582. }
  20583. sink.done();
  20584. return true;
  20585. });
  20586. });
  20587. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20588. auto se = detail::scope_exit([&] {
  20589. svr.stop();
  20590. listen_thread.join();
  20591. ASSERT_FALSE(svr.is_running());
  20592. });
  20593. svr.wait_until_ready();
  20594. SSLClient cli(HOST, PORT);
  20595. cli.enable_server_certificate_verification(false);
  20596. auto res = cli.Get("/no-content-length");
  20597. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20598. EXPECT_EQ(StatusCode::OK_200, res->status);
  20599. EXPECT_EQ(expected_body, res->body);
  20600. }
  20601. #endif // CPPHTTPLIB_SSL_ENABLED
  20602. //==============================================================================
  20603. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20604. // results for various scenarios.
  20605. //==============================================================================
  20606. TEST(ParityTest, GetVsOpenStream) {
  20607. Server svr;
  20608. const std::string path = "/parity";
  20609. const std::string content = "Parity test content: hello world";
  20610. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20611. res.set_content(content, "text/plain");
  20612. });
  20613. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20614. auto se = detail::scope_exit([&] {
  20615. svr.stop();
  20616. t.join();
  20617. ASSERT_FALSE(svr.is_running());
  20618. });
  20619. svr.wait_until_ready();
  20620. Client cli(HOST, PORT);
  20621. // Non-stream path
  20622. auto r1 = cli.Get(path);
  20623. ASSERT_TRUE(r1);
  20624. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20625. // Stream path
  20626. auto h = cli.open_stream("GET", path);
  20627. ASSERT_TRUE(h.is_valid());
  20628. EXPECT_EQ(r1->body, read_all(h));
  20629. }
  20630. // Helper to compress data with provided compressor type T
  20631. template <typename Compressor>
  20632. static std::string compress_payload_for_parity(const std::string &in) {
  20633. std::string out;
  20634. Compressor compressor;
  20635. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20636. [&](const char *data, size_t n) {
  20637. out.append(data, n);
  20638. return true;
  20639. });
  20640. EXPECT_TRUE(ok);
  20641. return out;
  20642. }
  20643. // Helper function for compression parity tests
  20644. template <typename Compressor>
  20645. static void test_compression_parity(const std::string &original,
  20646. const std::string &path,
  20647. const std::string &encoding) {
  20648. const std::string compressed =
  20649. compress_payload_for_parity<Compressor>(original);
  20650. Server svr;
  20651. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20652. res.set_content(compressed, "application/octet-stream");
  20653. res.set_header("Content-Encoding", encoding);
  20654. });
  20655. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20656. auto se = detail::scope_exit([&] {
  20657. svr.stop();
  20658. t.join();
  20659. ASSERT_FALSE(svr.is_running());
  20660. });
  20661. svr.wait_until_ready();
  20662. Client cli(HOST, PORT);
  20663. // Non-streaming
  20664. {
  20665. auto res = cli.Get(path);
  20666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20667. EXPECT_EQ(StatusCode::OK_200, res->status);
  20668. EXPECT_EQ(original, res->body);
  20669. }
  20670. // Streaming
  20671. {
  20672. auto h = cli.open_stream("GET", path);
  20673. ASSERT_TRUE(h.is_valid());
  20674. EXPECT_EQ(original, read_all(h));
  20675. }
  20676. }
  20677. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20678. TEST(ParityTest, Gzip) {
  20679. test_compression_parity<detail::gzip_compressor>(
  20680. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20681. }
  20682. #endif
  20683. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20684. TEST(ParityTest, Brotli) {
  20685. test_compression_parity<detail::brotli_compressor>(
  20686. "Hello, brotli parity test payload", "/parity-br", "br");
  20687. }
  20688. #endif
  20689. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20690. TEST(ParityTest, Zstd) {
  20691. test_compression_parity<detail::zstd_compressor>(
  20692. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20693. }
  20694. #endif
  20695. //==============================================================================
  20696. // New Stream API Tests
  20697. //==============================================================================
  20698. inline std::string read_body(httplib::stream::Result &result) {
  20699. std::string body;
  20700. while (result.next()) {
  20701. body.append(result.data(), result.size());
  20702. }
  20703. return body;
  20704. }
  20705. TEST(ClientConnectionTest, Basic) {
  20706. httplib::ClientConnection conn;
  20707. EXPECT_FALSE(conn.is_open());
  20708. conn.sock = 1;
  20709. EXPECT_TRUE(conn.is_open());
  20710. httplib::ClientConnection conn2(std::move(conn));
  20711. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20712. conn2.sock = INVALID_SOCKET;
  20713. }
  20714. // Unified test server for all stream::* tests
  20715. class StreamApiTest : public ::testing::Test {
  20716. protected:
  20717. void SetUp() override {
  20718. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20719. res.set_content("Hello World!", "text/plain");
  20720. });
  20721. svr_.Get("/echo-params",
  20722. [](const httplib::Request &req, httplib::Response &res) {
  20723. std::string r;
  20724. for (const auto &p : req.params) {
  20725. if (!r.empty()) r += "&";
  20726. r += p.first + "=" + p.second;
  20727. }
  20728. res.set_content(r, "text/plain");
  20729. });
  20730. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20731. res.set_content(req.body, req.get_header_value("Content-Type"));
  20732. });
  20733. svr_.Post("/echo-headers",
  20734. [](const httplib::Request &req, httplib::Response &res) {
  20735. std::string r;
  20736. for (const auto &h : req.headers)
  20737. r += h.first + ": " + h.second + "\n";
  20738. res.set_content(r, "text/plain");
  20739. });
  20740. svr_.Post("/echo-params",
  20741. [](const httplib::Request &req, httplib::Response &res) {
  20742. std::string r = "params:";
  20743. for (const auto &p : req.params)
  20744. r += p.first + "=" + p.second + ";";
  20745. res.set_content(r + " body:" + req.body, "text/plain");
  20746. });
  20747. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20748. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20749. });
  20750. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20751. res.set_content("PUT:" + req.body, "text/plain");
  20752. });
  20753. svr_.Patch("/echo",
  20754. [](const httplib::Request &req, httplib::Response &res) {
  20755. res.set_content("PATCH:" + req.body, "text/plain");
  20756. });
  20757. svr_.Delete(
  20758. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20759. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20760. "text/plain");
  20761. });
  20762. svr_.Get("/head-test",
  20763. [](const httplib::Request &, httplib::Response &res) {
  20764. res.set_content("body for HEAD", "text/plain");
  20765. });
  20766. svr_.Options("/options",
  20767. [](const httplib::Request &, httplib::Response &res) {
  20768. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20769. });
  20770. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20771. svr_.wait_until_ready();
  20772. }
  20773. void TearDown() override {
  20774. svr_.stop();
  20775. if (thread_.joinable()) thread_.join();
  20776. }
  20777. httplib::Server svr_;
  20778. std::thread thread_;
  20779. };
  20780. // stream::Get tests
  20781. TEST_F(StreamApiTest, GetBasic) {
  20782. httplib::Client cli(HOST, PORT);
  20783. auto result = httplib::stream::Get(cli, "/hello");
  20784. ASSERT_TRUE(result.is_valid());
  20785. EXPECT_EQ(200, result.status());
  20786. EXPECT_EQ("Hello World!", read_body(result));
  20787. }
  20788. TEST_F(StreamApiTest, GetWithParams) {
  20789. httplib::Client cli(HOST, PORT);
  20790. httplib::Params params{{"foo", "bar"}};
  20791. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20792. ASSERT_TRUE(result.is_valid());
  20793. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20794. }
  20795. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20796. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20797. httplib::Client cli(HOST, PORT);
  20798. cli.set_payload_max_length(0);
  20799. auto result = httplib::stream::Get(cli, "/hello");
  20800. ASSERT_TRUE(result.is_valid());
  20801. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20802. EXPECT_EQ("Hello World!", read_body(result));
  20803. }
  20804. #endif
  20805. TEST_F(StreamApiTest, GetConnectionError) {
  20806. httplib::Client cli(HOST, 9999);
  20807. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20808. }
  20809. TEST_F(StreamApiTest, Get404) {
  20810. httplib::Client cli(HOST, PORT);
  20811. auto result = httplib::stream::Get(cli, "/nonexistent");
  20812. EXPECT_TRUE(result.is_valid());
  20813. EXPECT_EQ(404, result.status());
  20814. }
  20815. // stream::Post tests
  20816. TEST_F(StreamApiTest, PostBasic) {
  20817. httplib::Client cli(HOST, PORT);
  20818. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20819. "application/json");
  20820. ASSERT_TRUE(result.is_valid());
  20821. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20822. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20823. }
  20824. TEST_F(StreamApiTest, PostWithHeaders) {
  20825. httplib::Client cli(HOST, PORT);
  20826. httplib::Headers headers{{"X-Custom", "value"}};
  20827. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20828. "text/plain");
  20829. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20830. }
  20831. TEST_F(StreamApiTest, PostWithParams) {
  20832. httplib::Client cli(HOST, PORT);
  20833. httplib::Params params{{"k", "v"}};
  20834. auto result =
  20835. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20836. auto body = read_body(result);
  20837. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20838. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20839. }
  20840. TEST_F(StreamApiTest, PostLarge) {
  20841. httplib::Client cli(HOST, PORT);
  20842. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20843. size_t total = 0;
  20844. while (result.next()) {
  20845. total += result.size();
  20846. }
  20847. EXPECT_EQ(100u * 1024u, total);
  20848. }
  20849. // stream::Put/Patch tests
  20850. TEST_F(StreamApiTest, PutAndPatch) {
  20851. httplib::Client cli(HOST, PORT);
  20852. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20853. EXPECT_EQ("PUT:test", read_body(put));
  20854. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20855. EXPECT_EQ("PATCH:test", read_body(patch));
  20856. }
  20857. // stream::Delete tests
  20858. TEST_F(StreamApiTest, Delete) {
  20859. httplib::Client cli(HOST, PORT);
  20860. auto del1 = httplib::stream::Delete(cli, "/resource");
  20861. EXPECT_EQ("Deleted", read_body(del1));
  20862. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20863. EXPECT_EQ("Deleted:data", read_body(del2));
  20864. }
  20865. // stream::Head/Options tests
  20866. TEST_F(StreamApiTest, HeadAndOptions) {
  20867. httplib::Client cli(HOST, PORT);
  20868. auto head = httplib::stream::Head(cli, "/head-test");
  20869. EXPECT_TRUE(head.is_valid());
  20870. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20871. auto opts = httplib::stream::Options(cli, "/options");
  20872. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20873. }
  20874. // SSL stream::* tests
  20875. #ifdef CPPHTTPLIB_SSL_ENABLED
  20876. class SSLStreamApiTest : public ::testing::Test {
  20877. protected:
  20878. void SetUp() override {
  20879. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20880. res.set_content("Hello SSL!", "text/plain");
  20881. });
  20882. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20883. res.set_content(req.body, "text/plain");
  20884. });
  20885. port_ = svr_.bind_to_any_port("127.0.0.1");
  20886. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20887. svr_.wait_until_ready();
  20888. }
  20889. void TearDown() override {
  20890. svr_.stop();
  20891. if (thread_.joinable()) thread_.join();
  20892. }
  20893. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20894. std::thread thread_;
  20895. int port_ = 0;
  20896. };
  20897. TEST_F(SSLStreamApiTest, GetAndPost) {
  20898. httplib::SSLClient cli("127.0.0.1", port_);
  20899. cli.enable_server_certificate_verification(false);
  20900. auto get = httplib::stream::Get(cli, "/hello");
  20901. EXPECT_EQ("Hello SSL!", read_body(get));
  20902. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20903. EXPECT_EQ("test", read_body(post));
  20904. }
  20905. #endif
  20906. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20907. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20908. // BodyReader
  20909. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20910. // Test that read timeout during streaming is detected
  20911. // Use a large content-length response where server delays mid-stream
  20912. Server svr;
  20913. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20914. // Send a large response with delay in the middle
  20915. res.set_content_provider(
  20916. 1000, // content_length
  20917. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20918. if (offset < 100) {
  20919. // Send first 100 bytes immediately
  20920. std::string data(100, 'A');
  20921. sink.write(data.c_str(), data.size());
  20922. return true;
  20923. }
  20924. // Then delay longer than client timeout
  20925. std::this_thread::sleep_for(std::chrono::seconds(3));
  20926. std::string data(900, 'B');
  20927. sink.write(data.c_str(), data.size());
  20928. return true;
  20929. });
  20930. });
  20931. auto port = 8091;
  20932. std::thread t([&]() { svr.listen("localhost", port); });
  20933. svr.wait_until_ready();
  20934. Client cli("localhost", port);
  20935. cli.set_read_timeout(1, 0); // 1 second timeout
  20936. auto handle = cli.open_stream("GET", "/slow-stream");
  20937. ASSERT_TRUE(handle.is_valid());
  20938. char buf[256];
  20939. ssize_t total = 0;
  20940. ssize_t n;
  20941. bool got_error = false;
  20942. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20943. total += n;
  20944. }
  20945. if (n < 0) {
  20946. got_error = true;
  20947. // Should be timeout or read error
  20948. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20949. handle.get_read_error() == Error::Read)
  20950. << "Actual error: " << to_string(handle.get_read_error());
  20951. }
  20952. // Either we got an error, or we got less data than expected
  20953. EXPECT_TRUE(got_error || total < 1000)
  20954. << "Expected timeout but got all " << total << " bytes";
  20955. svr.stop();
  20956. t.join();
  20957. }
  20958. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20959. // Test connection closed detection via BodyReader
  20960. Server svr;
  20961. std::atomic<bool> close_now{false};
  20962. svr.Get("/will-close", [&](const Request &, Response &res) {
  20963. res.set_content_provider(
  20964. 10000, // Large content_length that we won't fully send
  20965. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20966. if (offset < 100) {
  20967. std::string data(100, 'X');
  20968. sink.write(data.c_str(), data.size());
  20969. return true;
  20970. }
  20971. // Wait for signal then abort
  20972. while (!close_now) {
  20973. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20974. }
  20975. return false; // Abort - server will close connection
  20976. });
  20977. });
  20978. auto port = 8092;
  20979. std::thread t([&]() { svr.listen("localhost", port); });
  20980. svr.wait_until_ready();
  20981. Client cli("localhost", port);
  20982. auto handle = cli.open_stream("GET", "/will-close");
  20983. ASSERT_TRUE(handle.is_valid());
  20984. char buf[256];
  20985. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20986. EXPECT_GT(n, 0) << "First read should succeed";
  20987. // Signal server to close
  20988. close_now = true;
  20989. // Keep reading until error or EOF
  20990. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20991. // Keep reading
  20992. }
  20993. // Should get an error since content_length wasn't satisfied
  20994. if (n < 0) {
  20995. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20996. handle.get_read_error() == Error::Read)
  20997. << "Actual error: " << to_string(handle.get_read_error());
  20998. }
  20999. svr.stop();
  21000. t.join();
  21001. }
  21002. #ifdef CPPHTTPLIB_SSL_ENABLED
  21003. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21004. // Test that read timeout during SSL streaming is detected
  21005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21006. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21007. res.set_content_provider(
  21008. 1000, "text/plain",
  21009. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21010. if (offset < 100) {
  21011. std::string data(100, 'A');
  21012. sink.write(data.c_str(), data.size());
  21013. return true;
  21014. }
  21015. std::this_thread::sleep_for(std::chrono::seconds(3));
  21016. std::string data(900, 'B');
  21017. sink.write(data.c_str(), data.size());
  21018. return true;
  21019. });
  21020. });
  21021. auto port = 8093;
  21022. std::thread t([&]() { svr.listen("localhost", port); });
  21023. svr.wait_until_ready();
  21024. SSLClient cli("localhost", port);
  21025. cli.enable_server_certificate_verification(false);
  21026. cli.set_read_timeout(1, 0); // 1 second timeout
  21027. auto handle = cli.open_stream("GET", "/slow-stream");
  21028. ASSERT_TRUE(handle.is_valid());
  21029. char buf[256];
  21030. ssize_t total = 0;
  21031. ssize_t n;
  21032. bool got_error = false;
  21033. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21034. total += n;
  21035. }
  21036. if (n < 0) {
  21037. got_error = true;
  21038. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21039. handle.get_read_error() == Error::Read)
  21040. << "Actual error: " << to_string(handle.get_read_error());
  21041. }
  21042. EXPECT_TRUE(got_error || total < 1000)
  21043. << "Expected timeout but got all " << total << " bytes";
  21044. svr.stop();
  21045. t.join();
  21046. }
  21047. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21048. // Test SSL connection closed detection
  21049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21050. std::atomic<bool> close_now{false};
  21051. svr.Get("/will-close", [&](const Request &, Response &res) {
  21052. res.set_content_provider(
  21053. 10000, "text/plain",
  21054. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21055. if (offset < 100) {
  21056. std::string data(100, 'X');
  21057. sink.write(data.c_str(), data.size());
  21058. return true;
  21059. }
  21060. while (!close_now) {
  21061. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21062. }
  21063. return false;
  21064. });
  21065. });
  21066. auto port = 8094;
  21067. std::thread t([&]() { svr.listen("localhost", port); });
  21068. svr.wait_until_ready();
  21069. SSLClient cli("localhost", port);
  21070. cli.enable_server_certificate_verification(false);
  21071. auto handle = cli.open_stream("GET", "/will-close");
  21072. ASSERT_TRUE(handle.is_valid());
  21073. char buf[256];
  21074. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21075. EXPECT_GT(n, 0);
  21076. // Signal server to close
  21077. close_now = true;
  21078. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21079. // Keep reading
  21080. }
  21081. if (n < 0) {
  21082. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21083. handle.get_read_error() == Error::Read)
  21084. << "Actual error: " << to_string(handle.get_read_error());
  21085. }
  21086. svr.stop();
  21087. t.join();
  21088. }
  21089. #endif
  21090. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21091. using namespace httplib;
  21092. // Create a test file
  21093. const char *fname = "etag_testfile.txt";
  21094. const char *content = "etag-content";
  21095. {
  21096. std::ofstream ofs(fname);
  21097. ofs << content;
  21098. ASSERT_TRUE(ofs.good());
  21099. }
  21100. Server svr;
  21101. svr.set_mount_point("/static", ".");
  21102. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21103. svr.wait_until_ready();
  21104. Client cli(HOST, PORT);
  21105. // First request: should get 200 with ETag header
  21106. auto res1 = cli.Get("/static/etag_testfile.txt");
  21107. ASSERT_TRUE(res1);
  21108. ASSERT_EQ(200, res1->status);
  21109. ASSERT_TRUE(res1->has_header("ETag"));
  21110. std::string etag = res1->get_header_value("ETag");
  21111. EXPECT_FALSE(etag.empty());
  21112. // Verify ETag format: W/"hex-hex"
  21113. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21114. EXPECT_EQ('W', etag[0]);
  21115. EXPECT_EQ('/', etag[1]);
  21116. EXPECT_EQ('"', etag[2]);
  21117. EXPECT_EQ('"', etag.back());
  21118. // Exact match: expect 304 Not Modified
  21119. Headers h2 = {{"If-None-Match", etag}};
  21120. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21121. ASSERT_TRUE(res2);
  21122. EXPECT_EQ(304, res2->status);
  21123. // Wildcard match: expect 304 Not Modified
  21124. Headers h3 = {{"If-None-Match", "*"}};
  21125. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21126. ASSERT_TRUE(res3);
  21127. EXPECT_EQ(304, res3->status);
  21128. // Non-matching ETag: expect 200
  21129. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21130. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21131. ASSERT_TRUE(res4);
  21132. EXPECT_EQ(200, res4->status);
  21133. // Multiple ETags with one matching: expect 304
  21134. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21135. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21136. ASSERT_TRUE(res5);
  21137. EXPECT_EQ(304, res5->status);
  21138. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21139. // that equivalent to the single comma-separated list above, so the match on
  21140. // the second line must still be found.
  21141. Headers h6;
  21142. h6.emplace("If-None-Match", "W/\"other\"");
  21143. h6.emplace("If-None-Match", etag);
  21144. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21145. ASSERT_TRUE(res6);
  21146. EXPECT_EQ(304, res6->status);
  21147. svr.stop();
  21148. t.join();
  21149. std::remove(fname);
  21150. }
  21151. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21152. using namespace httplib;
  21153. Server svr;
  21154. svr.set_mount_point("/static", ".");
  21155. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21156. svr.wait_until_ready();
  21157. Client cli(HOST, PORT);
  21158. // Send If-None-Match: * to a non-existent file
  21159. Headers h = {{"If-None-Match", "*"}};
  21160. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21162. EXPECT_EQ(404, res->status);
  21163. svr.stop();
  21164. t.join();
  21165. }
  21166. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21167. using namespace httplib;
  21168. // Create a test file
  21169. const char *fname = "etag_boundary_testfile.txt";
  21170. const char *content = "boundary-test";
  21171. {
  21172. std::ofstream ofs(fname);
  21173. ofs << content;
  21174. ASSERT_TRUE(ofs.good());
  21175. }
  21176. Server svr;
  21177. svr.set_mount_point("/static", ".");
  21178. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21179. svr.wait_until_ready();
  21180. Client cli(HOST, PORT);
  21181. // Get the actual ETag
  21182. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21183. ASSERT_TRUE(res1);
  21184. ASSERT_EQ(200, res1->status);
  21185. ASSERT_TRUE(res1->has_header("ETag"));
  21186. std::string etag = res1->get_header_value("ETag");
  21187. // Test 1: Very long ETag value (longer than actual ETag)
  21188. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21189. Headers h1 = {{"If-None-Match", "W/"
  21190. "\"very-long-etag-value-that-is-much-longer-"
  21191. "than-the-actual-etag-value\""}};
  21192. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21193. ASSERT_TRUE(res2);
  21194. EXPECT_EQ(200, res2->status); // Should not match
  21195. // Test 2: Long string followed by wildcard
  21196. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21197. // string)
  21198. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21199. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21200. ASSERT_TRUE(res3);
  21201. EXPECT_EQ(304, res3->status); // Should match on "*"
  21202. // Test 3: Wildcard followed by long string
  21203. // Should match on "*" immediately and return 304
  21204. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21205. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21206. ASSERT_TRUE(res4);
  21207. EXPECT_EQ(304, res4->status); // Should match on "*"
  21208. // Test 4: Multiple long non-matching values
  21209. // Should NOT match and return 200 (test that all comparisons are safe)
  21210. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21211. "W/\"second-long-non-matching-value\", "
  21212. "W/\"third-long-non-matching-value\""}};
  21213. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21214. ASSERT_TRUE(res5);
  21215. EXPECT_EQ(200, res5->status); // Should not match
  21216. // Test 5: Single character that is not "*" (edge case)
  21217. Headers h5 = {{"If-None-Match", "X"}};
  21218. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21219. ASSERT_TRUE(res6);
  21220. EXPECT_EQ(200, res6->status); // Should not match
  21221. svr.stop();
  21222. t.join();
  21223. std::remove(fname);
  21224. }
  21225. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21226. using namespace httplib;
  21227. // Create a test file
  21228. const char *fname = "ims_testfile.txt";
  21229. const char *content = "if-modified-since-test";
  21230. {
  21231. std::ofstream ofs(fname);
  21232. ofs << content;
  21233. ASSERT_TRUE(ofs.good());
  21234. }
  21235. Server svr;
  21236. svr.set_mount_point("/static", ".");
  21237. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21238. svr.wait_until_ready();
  21239. Client cli(HOST, PORT);
  21240. // First request: should get 200 with Last-Modified header
  21241. auto res1 = cli.Get("/static/ims_testfile.txt");
  21242. ASSERT_TRUE(res1);
  21243. ASSERT_EQ(200, res1->status);
  21244. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21245. std::string last_modified = res1->get_header_value("Last-Modified");
  21246. EXPECT_FALSE(last_modified.empty());
  21247. // If-Modified-Since with same time: expect 304
  21248. Headers h2 = {{"If-Modified-Since", last_modified}};
  21249. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21250. ASSERT_TRUE(res2);
  21251. EXPECT_EQ(304, res2->status);
  21252. // If-Modified-Since with future time: expect 304
  21253. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21254. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21255. ASSERT_TRUE(res3);
  21256. EXPECT_EQ(304, res3->status);
  21257. // If-Modified-Since with past time: expect 200
  21258. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21259. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21260. ASSERT_TRUE(res4);
  21261. EXPECT_EQ(200, res4->status);
  21262. // If-None-Match takes precedence over If-Modified-Since
  21263. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21264. ASSERT_TRUE(res1->has_header("ETag"));
  21265. std::string etag = res1->get_header_value("ETag");
  21266. Headers h5 = {{"If-None-Match", etag},
  21267. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21268. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21269. ASSERT_TRUE(res5);
  21270. EXPECT_EQ(304, res5->status);
  21271. svr.stop();
  21272. t.join();
  21273. std::remove(fname);
  21274. }
  21275. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21276. using namespace httplib;
  21277. Server svr;
  21278. // Endpoint that returns compressible content
  21279. svr.Get("/compressible", [](const Request &, Response &res) {
  21280. // Return a large enough body to trigger compression
  21281. std::string body(1000, 'a');
  21282. res.set_content(body, "text/plain");
  21283. });
  21284. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21285. svr.wait_until_ready();
  21286. Client cli(HOST, PORT);
  21287. // Request with gzip support: should get Vary header when compressed
  21288. cli.set_compress(true);
  21289. auto res1 = cli.Get("/compressible");
  21290. ASSERT_TRUE(res1);
  21291. EXPECT_EQ(200, res1->status);
  21292. // If Content-Encoding is set, Vary should also be set
  21293. if (res1->has_header("Content-Encoding")) {
  21294. EXPECT_TRUE(res1->has_header("Vary"));
  21295. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21296. }
  21297. // Request without Accept-Encoding header: should not have compression
  21298. Headers h_no_compress;
  21299. auto res2 = cli.Get("/compressible", h_no_compress);
  21300. ASSERT_TRUE(res2);
  21301. EXPECT_EQ(200, res2->status);
  21302. // Verify Vary header is present when compression is applied
  21303. // (the exact behavior depends on server configuration)
  21304. svr.stop();
  21305. t.join();
  21306. }
  21307. TEST(ETagTest, IfRangeWithETag) {
  21308. using namespace httplib;
  21309. // Create a test file with known content
  21310. const char *fname = "if_range_testfile.txt";
  21311. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21312. {
  21313. std::ofstream ofs(fname);
  21314. ofs << content;
  21315. ASSERT_TRUE(ofs.good());
  21316. }
  21317. Server svr;
  21318. svr.set_mount_point("/static", ".");
  21319. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21320. svr.wait_until_ready();
  21321. Client cli(HOST, PORT);
  21322. // First request: get ETag
  21323. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21324. ASSERT_TRUE(res1);
  21325. ASSERT_EQ(200, res1->status);
  21326. ASSERT_TRUE(res1->has_header("ETag"));
  21327. std::string etag = res1->get_header_value("ETag");
  21328. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21329. // Since our server generates weak ETags (W/"..."), If-Range with our
  21330. // ETag should NOT result in partial content - it should return full content.
  21331. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21332. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21333. ASSERT_TRUE(res2);
  21334. // Weak ETag in If-Range -> full content (200), not partial (206)
  21335. EXPECT_EQ(200, res2->status);
  21336. EXPECT_EQ(content, res2->body);
  21337. EXPECT_FALSE(res2->has_header("Content-Range"));
  21338. // Range request with non-matching If-Range (ETag): should get 200 (full
  21339. // content)
  21340. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21341. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21342. ASSERT_TRUE(res3);
  21343. EXPECT_EQ(200, res3->status);
  21344. EXPECT_EQ(content, res3->body);
  21345. EXPECT_FALSE(res3->has_header("Content-Range"));
  21346. // Range request with strong ETag (hypothetical - our server doesn't generate
  21347. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21348. // should return full content)
  21349. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21350. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21351. ASSERT_TRUE(res4);
  21352. EXPECT_EQ(200, res4->status);
  21353. EXPECT_EQ(content, res4->body);
  21354. EXPECT_FALSE(res4->has_header("Content-Range"));
  21355. svr.stop();
  21356. t.join();
  21357. std::remove(fname);
  21358. }
  21359. TEST(ETagTest, IfRangeWithDate) {
  21360. using namespace httplib;
  21361. // Create a test file
  21362. const char *fname = "if_range_date_testfile.txt";
  21363. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21364. {
  21365. std::ofstream ofs(fname);
  21366. ofs << content;
  21367. ASSERT_TRUE(ofs.good());
  21368. }
  21369. Server svr;
  21370. svr.set_mount_point("/static", ".");
  21371. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21372. svr.wait_until_ready();
  21373. Client cli(HOST, PORT);
  21374. // First request: get Last-Modified
  21375. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21376. ASSERT_TRUE(res1);
  21377. ASSERT_EQ(200, res1->status);
  21378. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21379. std::string last_modified = res1->get_header_value("Last-Modified");
  21380. // Range request with matching If-Range (date): should get 206
  21381. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21382. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21383. ASSERT_TRUE(res2);
  21384. EXPECT_EQ(206, res2->status);
  21385. EXPECT_EQ("FGHIJ", res2->body);
  21386. // Range request with old If-Range date: should get 200 (full content)
  21387. Headers h3 = {{"Range", "bytes=5-9"},
  21388. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21389. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21390. ASSERT_TRUE(res3);
  21391. EXPECT_EQ(200, res3->status);
  21392. EXPECT_EQ(content, res3->body);
  21393. // Range request with future If-Range date: should get 206
  21394. Headers h4 = {{"Range", "bytes=0-4"},
  21395. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21396. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21397. ASSERT_TRUE(res4);
  21398. EXPECT_EQ(206, res4->status);
  21399. EXPECT_EQ("ABCDE", res4->body);
  21400. svr.stop();
  21401. t.join();
  21402. std::remove(fname);
  21403. }
  21404. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21405. using namespace httplib;
  21406. const char *fname = "etag_malformed.txt";
  21407. const char *content = "malformed-etag";
  21408. {
  21409. std::ofstream ofs(fname);
  21410. ofs << content;
  21411. ASSERT_TRUE(ofs.good());
  21412. }
  21413. Server svr;
  21414. svr.set_mount_point("/static", ".");
  21415. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21416. svr.wait_until_ready();
  21417. Client cli(HOST, PORT);
  21418. // baseline: should get 200 and an ETag
  21419. auto res1 = cli.Get("/static/etag_malformed.txt");
  21420. ASSERT_TRUE(res1);
  21421. ASSERT_EQ(200, res1->status);
  21422. ASSERT_TRUE(res1->has_header("ETag"));
  21423. // Malformed ETag value (missing quotes) should be treated as non-matching
  21424. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21425. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21426. ASSERT_TRUE(res_bad);
  21427. EXPECT_EQ(200, res_bad->status);
  21428. // Whitespace-only header value should be considered invalid / non-matching
  21429. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21430. "Host: localhost\r\n"
  21431. "If-None-Match: \r\n"
  21432. "Connection: close\r\n"
  21433. "\r\n";
  21434. std::string out;
  21435. ASSERT_TRUE(send_request(5, raw_req, &out));
  21436. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21437. svr.stop();
  21438. t.join();
  21439. std::remove(fname);
  21440. }
  21441. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21442. using namespace httplib;
  21443. const char *fname = "ims_invalid_format.txt";
  21444. const char *content = "ims-bad-format";
  21445. {
  21446. std::ofstream ofs(fname);
  21447. ofs << content;
  21448. ASSERT_TRUE(ofs.good());
  21449. }
  21450. Server svr;
  21451. svr.set_mount_point("/static", ".");
  21452. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21453. svr.wait_until_ready();
  21454. Client cli(HOST, PORT);
  21455. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21456. ASSERT_TRUE(res1);
  21457. ASSERT_EQ(200, res1->status);
  21458. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21459. // If-Modified-Since with invalid format should not result in 304
  21460. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21461. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21462. ASSERT_TRUE(res_bad);
  21463. EXPECT_EQ(200, res_bad->status);
  21464. // If-Range with invalid date format should be treated as mismatch -> full
  21465. // content (200)
  21466. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21467. {"If-Range", "invalid-date"}};
  21468. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21469. ASSERT_TRUE(res_ifrange);
  21470. EXPECT_EQ(200, res_ifrange->status);
  21471. svr.stop();
  21472. t.join();
  21473. std::remove(fname);
  21474. }
  21475. TEST(ETagTest, IfRangeWithMalformedETag) {
  21476. using namespace httplib;
  21477. const char *fname = "ifrange_malformed.txt";
  21478. const std::string content = "0123456789";
  21479. {
  21480. std::ofstream ofs(fname);
  21481. ofs << content;
  21482. ASSERT_TRUE(ofs.good());
  21483. }
  21484. Server svr;
  21485. svr.set_mount_point("/static", ".");
  21486. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21487. svr.wait_until_ready();
  21488. Client cli(HOST, PORT);
  21489. // First request: get ETag
  21490. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21491. ASSERT_TRUE(res1);
  21492. ASSERT_EQ(200, res1->status);
  21493. ASSERT_TRUE(res1->has_header("ETag"));
  21494. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21495. // full content (200)
  21496. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21497. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21498. ASSERT_TRUE(res2);
  21499. EXPECT_EQ(200, res2->status);
  21500. EXPECT_EQ(content, res2->body);
  21501. svr.stop();
  21502. t.join();
  21503. std::remove(fname);
  21504. }
  21505. TEST(ETagTest, ExtremeLargeDateValues) {
  21506. using namespace httplib;
  21507. const char *fname = "ims_extreme_date.txt";
  21508. const char *content = "ims-extreme-date";
  21509. {
  21510. std::ofstream ofs(fname);
  21511. ofs << content;
  21512. ASSERT_TRUE(ofs.good());
  21513. }
  21514. Server svr;
  21515. svr.set_mount_point("/static", ".");
  21516. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21517. svr.wait_until_ready();
  21518. Client cli(HOST, PORT);
  21519. auto res1 = cli.Get(std::string("/static/") + fname);
  21520. ASSERT_TRUE(res1);
  21521. ASSERT_EQ(200, res1->status);
  21522. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21523. // Extremely large year that may overflow date parsing routines.
  21524. Headers h_large_date = {
  21525. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21526. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21527. ASSERT_TRUE(res_bad);
  21528. // Expect server to treat this as invalid/mismatch and return full content
  21529. EXPECT_EQ(200, res_bad->status);
  21530. // If-Range with extremely large date should be treated as mismatch -> full
  21531. // content (200)
  21532. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21533. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21534. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21535. ASSERT_TRUE(res_ifrange);
  21536. EXPECT_EQ(200, res_ifrange->status);
  21537. svr.stop();
  21538. t.join();
  21539. std::remove(fname);
  21540. }
  21541. TEST(ETagTest, NegativeFileModificationTime) {
  21542. using namespace httplib;
  21543. const char *fname = "ims_negative_mtime.txt";
  21544. const std::string content = "negative-mtime";
  21545. {
  21546. std::ofstream ofs(fname);
  21547. ofs << content;
  21548. ASSERT_TRUE(ofs.good());
  21549. }
  21550. // Try to set file mtime to a negative value. This may fail on some
  21551. // platforms/filesystems; if it fails, the test will still verify server
  21552. // behaves safely by performing a regular conditional request.
  21553. #if defined(__APPLE__) || defined(__linux__)
  21554. bool set_negative = false;
  21555. do {
  21556. struct timeval times[2];
  21557. // access time: now
  21558. times[0].tv_sec = time(nullptr);
  21559. times[0].tv_usec = 0;
  21560. // modification time: negative (e.g., -1)
  21561. times[1].tv_sec = -1;
  21562. times[1].tv_usec = 0;
  21563. if (utimes(fname, times) == 0) { set_negative = true; }
  21564. } while (0);
  21565. #else
  21566. bool set_negative = false;
  21567. #endif
  21568. Server svr;
  21569. svr.set_mount_point("/static", ".");
  21570. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21571. svr.wait_until_ready();
  21572. Client cli(HOST, PORT);
  21573. auto res1 = cli.Get(std::string("/static/") + fname);
  21574. ASSERT_TRUE(res1);
  21575. ASSERT_EQ(200, res1->status);
  21576. bool has_last_modified = res1->has_header("Last-Modified");
  21577. std::string last_modified;
  21578. if (has_last_modified) {
  21579. last_modified = res1->get_header_value("Last-Modified");
  21580. }
  21581. if (set_negative) {
  21582. // If we successfully set a negative mtime, ensure server returns a
  21583. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21584. // with an old date and ensure server handles it without crash.
  21585. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21586. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21587. ASSERT_TRUE(res2);
  21588. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21589. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21590. } else {
  21591. // Could not set negative mtime on this platform; fall back to verifying
  21592. // that normal invalid/malformed dates are treated safely (non-304).
  21593. Headers h_bad_date = {
  21594. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21595. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21596. ASSERT_TRUE(res_bad);
  21597. EXPECT_EQ(200, res_bad->status);
  21598. }
  21599. svr.stop();
  21600. t.join();
  21601. std::remove(fname);
  21602. }
  21603. //==============================================================================
  21604. // Integration Tests with Server
  21605. //==============================================================================
  21606. class SSEIntegrationTest : public ::testing::Test {
  21607. protected:
  21608. void SetUp() override {
  21609. stop_server_.store(false);
  21610. events_.clear();
  21611. server_ = httplib::detail::make_unique<Server>();
  21612. setup_server();
  21613. start_server();
  21614. }
  21615. void TearDown() override {
  21616. stop_server_.store(true);
  21617. event_cv_.notify_all();
  21618. server_->stop();
  21619. if (server_thread_.joinable()) { server_thread_.join(); }
  21620. }
  21621. void setup_server() {
  21622. // Simple SSE endpoint
  21623. server_->Get("/events", [this](const Request &req, Response &res) {
  21624. auto last_id = req.get_header_value("Last-Event-ID");
  21625. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21626. res.set_chunked_content_provider(
  21627. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21628. std::unique_lock<std::mutex> lock(event_mutex_);
  21629. if (event_cv_.wait_for(
  21630. lock, std::chrono::milliseconds(200), [this] {
  21631. return !events_.empty() || stop_server_.load();
  21632. })) {
  21633. if (stop_server_.load()) { return false; }
  21634. if (!events_.empty()) {
  21635. std::string event = events_.front();
  21636. events_.erase(events_.begin());
  21637. sink.write(event.data(), event.size());
  21638. return true;
  21639. }
  21640. }
  21641. return !stop_server_.load();
  21642. });
  21643. });
  21644. // Endpoint that returns error
  21645. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21646. res.status = 500;
  21647. res.set_content("Internal Server Error", "text/plain");
  21648. });
  21649. // Endpoint for custom event types
  21650. server_->Get("/custom-events", [](const Request &, Response &res) {
  21651. res.set_chunked_content_provider(
  21652. "text/event-stream", [](size_t offset, DataSink &sink) {
  21653. if (offset == 0) {
  21654. std::string event = "event: update\ndata: updated\n\n"
  21655. "event: delete\ndata: deleted\n\n";
  21656. sink.write(event.data(), event.size());
  21657. }
  21658. return false; // End stream after sending
  21659. });
  21660. });
  21661. }
  21662. void start_server() {
  21663. port_ = server_->bind_to_any_port(HOST);
  21664. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21665. // Wait for server to start
  21666. while (!server_->is_running()) {
  21667. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21668. }
  21669. }
  21670. int get_port() const { return port_; }
  21671. void send_event(const std::string &event) {
  21672. std::lock_guard<std::mutex> lock(event_mutex_);
  21673. events_.push_back(event);
  21674. event_cv_.notify_all();
  21675. }
  21676. std::unique_ptr<Server> server_;
  21677. std::thread server_thread_;
  21678. std::mutex event_mutex_;
  21679. std::condition_variable event_cv_;
  21680. std::vector<std::string> events_;
  21681. std::atomic<bool> stop_server_{false};
  21682. std::string last_received_event_id_;
  21683. int port_ = 0;
  21684. };
  21685. //==============================================================================
  21686. // SSE Parsing Tests
  21687. //==============================================================================
  21688. class SSEParsingTest : public SSEIntegrationTest {
  21689. protected:
  21690. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21691. // A trailing sentinel event tells when the whole stream has been parsed.
  21692. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21693. auto body = stream + "event: end\ndata: end\n\n";
  21694. server_->Get("/parse", [body](const Request &, Response &res) {
  21695. res.set_content(body, "text/event-stream");
  21696. });
  21697. return collect("/parse");
  21698. }
  21699. // Runs SSEClient against path until an "end" event arrives and returns the
  21700. // messages dispatched before it
  21701. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21702. Client client(HOST, get_port());
  21703. sse::SSEClient sse(client, path);
  21704. std::mutex mutex;
  21705. std::condition_variable cv;
  21706. std::vector<sse::SSEMessage> messages;
  21707. auto done = false;
  21708. sse.on_message([&](const sse::SSEMessage &msg) {
  21709. std::lock_guard<std::mutex> lock(mutex);
  21710. // Ignore a replay from a reconnect that races with stop()
  21711. if (!done) { messages.push_back(msg); }
  21712. });
  21713. sse.on_event("end", [&](const sse::SSEMessage &) {
  21714. std::lock_guard<std::mutex> lock(mutex);
  21715. done = true;
  21716. cv.notify_all();
  21717. });
  21718. sse.set_reconnect_interval(100);
  21719. sse.start_async();
  21720. {
  21721. std::unique_lock<std::mutex> lock(mutex);
  21722. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21723. }
  21724. sse.stop();
  21725. EXPECT_TRUE(done);
  21726. return messages;
  21727. }
  21728. };
  21729. TEST_F(SSEParsingTest, SingleLineData) {
  21730. auto msgs = parse("data: hello\n\n");
  21731. ASSERT_EQ(msgs.size(), 1u);
  21732. EXPECT_EQ(msgs[0].data, "hello");
  21733. EXPECT_EQ(msgs[0].event, "message");
  21734. }
  21735. TEST_F(SSEParsingTest, MultiLineData) {
  21736. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21737. ASSERT_EQ(msgs.size(), 1u);
  21738. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21739. }
  21740. TEST_F(SSEParsingTest, CustomEventType) {
  21741. auto msgs = parse("event: update\ndata: payload\n\n");
  21742. ASSERT_EQ(msgs.size(), 1u);
  21743. EXPECT_EQ(msgs[0].event, "update");
  21744. EXPECT_EQ(msgs[0].data, "payload");
  21745. }
  21746. TEST_F(SSEParsingTest, EventIdHandling) {
  21747. auto msgs = parse("id: 12345\ndata: test\n\n");
  21748. ASSERT_EQ(msgs.size(), 1u);
  21749. EXPECT_EQ(msgs[0].id, "12345");
  21750. }
  21751. TEST_F(SSEParsingTest, EmptyEventId) {
  21752. auto msgs = parse("id:\ndata: test\n\n");
  21753. ASSERT_EQ(msgs.size(), 1u);
  21754. EXPECT_EQ(msgs[0].id, "");
  21755. }
  21756. TEST_F(SSEParsingTest, CommentsIgnored) {
  21757. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21758. ASSERT_EQ(msgs.size(), 1u);
  21759. EXPECT_EQ(msgs[0].data, "hello");
  21760. EXPECT_EQ(msgs[0].event, "message");
  21761. }
  21762. TEST_F(SSEParsingTest, ColonInValue) {
  21763. auto msgs = parse("data: hello:world:test\n\n");
  21764. ASSERT_EQ(msgs.size(), 1u);
  21765. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21766. }
  21767. TEST_F(SSEParsingTest, FieldNameOnly) {
  21768. // A line without a colon is a field name with an empty value
  21769. auto msgs = parse("data\n\n");
  21770. ASSERT_EQ(msgs.size(), 1u);
  21771. EXPECT_EQ(msgs[0].data, "");
  21772. }
  21773. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21774. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21775. ASSERT_EQ(msgs.size(), 1u);
  21776. EXPECT_EQ(msgs[0].event, "update");
  21777. EXPECT_EQ(msgs[0].data, "hello");
  21778. }
  21779. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21780. auto msgs = parse("data\r\n\r\n");
  21781. ASSERT_EQ(msgs.size(), 1u);
  21782. EXPECT_EQ(msgs[0].data, "");
  21783. }
  21784. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21785. auto msgs = parse("event: update\rdata: hello\r\r");
  21786. ASSERT_EQ(msgs.size(), 1u);
  21787. EXPECT_EQ(msgs[0].event, "update");
  21788. EXPECT_EQ(msgs[0].data, "hello");
  21789. }
  21790. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21791. // Chunk boundaries fall inside every \r\n and right before the first one
  21792. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21793. "\n\r", "\nevent: end\ndata: end\n\n"};
  21794. server_->Get("/split", [chunks](const Request &, Response &res) {
  21795. auto i = std::make_shared<size_t>(0);
  21796. res.set_chunked_content_provider(
  21797. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21798. if (*i == chunks.size()) {
  21799. sink.done();
  21800. } else {
  21801. sink.write(chunks[*i].data(), chunks[*i].size());
  21802. (*i)++;
  21803. }
  21804. return true;
  21805. });
  21806. });
  21807. auto msgs = collect("/split");
  21808. ASSERT_EQ(msgs.size(), 1u);
  21809. EXPECT_EQ(msgs[0].event, "update");
  21810. EXPECT_EQ(msgs[0].data, "hello");
  21811. }
  21812. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21813. // Only a BOM at the start of the stream is ignored
  21814. auto msgs = parse("\xEF\xBB\xBF"
  21815. "data: first\n\n"
  21816. "\xEF\xBB\xBF"
  21817. "data: second\n\n");
  21818. ASSERT_EQ(msgs.size(), 1u);
  21819. EXPECT_EQ(msgs[0].data, "first");
  21820. }
  21821. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21822. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21823. ASSERT_EQ(msgs.size(), 1u);
  21824. EXPECT_EQ(msgs[0].data, "hello");
  21825. EXPECT_EQ(msgs[0].event, "message");
  21826. }
  21827. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21828. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21829. ASSERT_EQ(msgs.size(), 2u);
  21830. EXPECT_EQ(msgs[0].data, "hello");
  21831. EXPECT_EQ(msgs[1].data, "hello");
  21832. }
  21833. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21834. // An event without data is not dispatched, and its type must not leak
  21835. // into the next event
  21836. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21837. ASSERT_EQ(msgs.size(), 1u);
  21838. EXPECT_EQ(msgs[0].event, "message");
  21839. EXPECT_EQ(msgs[0].data, "hello");
  21840. }
  21841. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21842. // Also when the empty field replaces an earlier type
  21843. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21844. ASSERT_EQ(msgs.size(), 2u);
  21845. EXPECT_EQ(msgs[0].event, "message");
  21846. EXPECT_EQ(msgs[1].event, "message");
  21847. }
  21848. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21849. // The first connection sends only an id; the second echoes back the
  21850. // Last-Event-ID it was reconnected with
  21851. std::atomic<int> connection_count{0};
  21852. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21853. if (connection_count++ == 0) {
  21854. res.set_content("id: 42\n\n", "text/event-stream");
  21855. } else {
  21856. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21857. "\n\nevent: end\ndata: end\n\n",
  21858. "text/event-stream");
  21859. }
  21860. });
  21861. auto msgs = collect("/id-only");
  21862. ASSERT_EQ(msgs.size(), 1u);
  21863. EXPECT_EQ(msgs[0].data, "42");
  21864. }
  21865. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21866. // The first connection sets an id and then clears it with an empty one; the
  21867. // second reports whether it was reconnected with a Last-Event-ID
  21868. std::atomic<int> connection_count{0};
  21869. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21870. if (connection_count++ == 0) {
  21871. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21872. "text/event-stream");
  21873. } else {
  21874. res.set_content(
  21875. std::string("data: ") +
  21876. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21877. "\n\nevent: end\ndata: end\n\n",
  21878. "text/event-stream");
  21879. }
  21880. });
  21881. auto msgs = collect("/id-clear");
  21882. ASSERT_EQ(msgs.size(), 3u);
  21883. EXPECT_EQ(msgs[0].id, "1");
  21884. EXPECT_EQ(msgs[1].id, "");
  21885. EXPECT_EQ(msgs[2].data, "not sent");
  21886. }
  21887. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21888. // The first connection sets an id and then sends ids that cannot be carried
  21889. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21890. // with
  21891. std::atomic<int> connection_count{0};
  21892. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21893. if (connection_count++ == 0) {
  21894. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21895. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21896. "text/event-stream");
  21897. } else {
  21898. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21899. "\n\nevent: end\ndata: end\n\n",
  21900. "text/event-stream");
  21901. }
  21902. });
  21903. auto msgs = collect("/id-unsendable");
  21904. ASSERT_EQ(msgs.size(), 1u);
  21905. EXPECT_EQ(msgs[0].data, "42");
  21906. }
  21907. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21908. auto msgs = parse("event: notification\nid: evt-42\n"
  21909. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21910. ASSERT_EQ(msgs.size(), 1u);
  21911. EXPECT_EQ(msgs[0].event, "notification");
  21912. EXPECT_EQ(msgs[0].id, "evt-42");
  21913. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21914. }
  21915. TEST(SSEMessageTest, Clear) {
  21916. sse::SSEMessage msg;
  21917. msg.event = "custom";
  21918. msg.data = "some data";
  21919. msg.id = "123";
  21920. msg.clear();
  21921. EXPECT_EQ(msg.event, "message");
  21922. EXPECT_EQ(msg.data, "");
  21923. EXPECT_EQ(msg.id, "");
  21924. }
  21925. //==============================================================================
  21926. // SSE Integration Tests
  21927. //==============================================================================
  21928. // Test: Successful connection and on_open callback
  21929. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21930. // Add a simple endpoint that sends one event and closes
  21931. server_->Get("/simple-event", [](const Request &, Response &res) {
  21932. res.set_chunked_content_provider(
  21933. "text/event-stream", [](size_t offset, DataSink &sink) {
  21934. if (offset == 0) {
  21935. std::string event = "data: hello\n\n";
  21936. sink.write(event.data(), event.size());
  21937. }
  21938. return false; // Close stream after sending
  21939. });
  21940. });
  21941. Client client("localhost", get_port());
  21942. sse::SSEClient sse(client, "/simple-event");
  21943. std::atomic<bool> open_called{false};
  21944. std::atomic<bool> message_received{false};
  21945. sse.on_open([&open_called]() { open_called.store(true); });
  21946. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21947. if (msg.data == "hello") { message_received.store(true); }
  21948. });
  21949. sse.set_reconnect_interval(100);
  21950. sse.set_max_reconnect_attempts(1);
  21951. // Start async
  21952. sse.start_async();
  21953. // Wait for message to be processed
  21954. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21955. sse.stop();
  21956. EXPECT_TRUE(open_called.load());
  21957. EXPECT_TRUE(message_received.load());
  21958. }
  21959. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21960. // A data line that never ends.
  21961. server_->Get("/endless-line", [](const Request &, Response &res) {
  21962. res.set_chunked_content_provider(
  21963. "text/event-stream", [](size_t offset, DataSink &sink) {
  21964. if (offset == 0) { sink.write("data: ", 6); }
  21965. std::string chunk(64 * 1024, 'A');
  21966. return sink.write(chunk.data(), chunk.size());
  21967. });
  21968. });
  21969. Client client("localhost", get_port());
  21970. sse::SSEClient sse(client, "/endless-line");
  21971. std::atomic<bool> too_long{false};
  21972. sse.on_error([&](Error err) {
  21973. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21974. });
  21975. sse.set_max_reconnect_attempts(1);
  21976. sse.start_async();
  21977. for (int i = 0; i < 500 && !too_long; i++) {
  21978. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21979. }
  21980. sse.stop();
  21981. EXPECT_TRUE(too_long);
  21982. }
  21983. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21984. // Far more in all than the client's payload limit below.
  21985. server_->Get("/many-events", [](const Request &, Response &res) {
  21986. res.set_chunked_content_provider(
  21987. "text/event-stream", [](size_t offset, DataSink &sink) {
  21988. if (offset == 0) {
  21989. std::string events;
  21990. for (int i = 0; i < 1000; i++) {
  21991. events += "data: message\n\n";
  21992. }
  21993. sink.write(events.data(), events.size());
  21994. }
  21995. return false;
  21996. });
  21997. });
  21998. Client client("localhost", get_port());
  21999. client.set_payload_max_length(1024);
  22000. sse::SSEClient sse(client, "/many-events");
  22001. std::atomic<int> messages{0};
  22002. std::atomic<bool> too_large{false};
  22003. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22004. sse.on_error([&](Error err) {
  22005. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22006. });
  22007. sse.set_max_reconnect_attempts(1);
  22008. sse.start_async();
  22009. for (int i = 0; i < 500 && messages < 1000; i++) {
  22010. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22011. }
  22012. sse.stop();
  22013. EXPECT_GE(messages.load(), 1000);
  22014. EXPECT_FALSE(too_large);
  22015. }
  22016. // Test: on_message callback
  22017. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22018. // Endpoint that sends multiple events then closes
  22019. server_->Get("/multi-event", [](const Request &, Response &res) {
  22020. res.set_chunked_content_provider(
  22021. "text/event-stream", [](size_t offset, DataSink &sink) {
  22022. if (offset == 0) {
  22023. std::string events = "data: message1\n\ndata: message2\n\n";
  22024. sink.write(events.data(), events.size());
  22025. }
  22026. return false;
  22027. });
  22028. });
  22029. Client client("localhost", get_port());
  22030. sse::SSEClient sse(client, "/multi-event");
  22031. std::vector<std::string> received_messages;
  22032. std::mutex messages_mutex;
  22033. sse.on_message([&](const sse::SSEMessage &msg) {
  22034. std::lock_guard<std::mutex> lock(messages_mutex);
  22035. received_messages.push_back(msg.data);
  22036. });
  22037. sse.set_reconnect_interval(100);
  22038. sse.set_max_reconnect_attempts(1);
  22039. sse.start_async();
  22040. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22041. sse.stop();
  22042. std::lock_guard<std::mutex> lock(messages_mutex);
  22043. EXPECT_GE(received_messages.size(), 2u);
  22044. if (received_messages.size() >= 2) {
  22045. EXPECT_EQ(received_messages[0], "message1");
  22046. EXPECT_EQ(received_messages[1], "message2");
  22047. }
  22048. }
  22049. // Test: on_event for specific types
  22050. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22051. Client client("localhost", get_port());
  22052. sse::SSEClient sse(client, "/custom-events");
  22053. std::atomic<bool> update_received{false};
  22054. std::atomic<bool> delete_received{false};
  22055. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22056. if (msg.data == "updated") { update_received.store(true); }
  22057. });
  22058. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22059. if (msg.data == "deleted") { delete_received.store(true); }
  22060. });
  22061. sse.set_max_reconnect_attempts(1);
  22062. sse.start_async();
  22063. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22064. sse.stop();
  22065. EXPECT_TRUE(update_received.load());
  22066. EXPECT_TRUE(delete_received.load());
  22067. }
  22068. // Test: on_error callback on connection failure
  22069. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22070. // Connect to a non-existent port
  22071. Client client("localhost", 59999);
  22072. sse::SSEClient sse(client, "/events");
  22073. std::atomic<bool> error_called{false};
  22074. Error received_error = Error::Success;
  22075. sse.on_error([&](Error err) {
  22076. error_called.store(true);
  22077. received_error = err;
  22078. });
  22079. sse.set_reconnect_interval(50);
  22080. sse.set_max_reconnect_attempts(1);
  22081. sse.start_async();
  22082. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22083. sse.stop();
  22084. EXPECT_TRUE(error_called.load());
  22085. EXPECT_NE(received_error, Error::Success);
  22086. }
  22087. // Test: Last-Event-ID header sent on reconnect
  22088. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22089. // Endpoint that sends event with ID
  22090. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22091. res.set_chunked_content_provider(
  22092. "text/event-stream", [](size_t offset, DataSink &sink) {
  22093. if (offset == 0) {
  22094. std::string event = "id: evt-123\ndata: test\n\n";
  22095. sink.write(event.data(), event.size());
  22096. }
  22097. return false;
  22098. });
  22099. });
  22100. Client client("localhost", get_port());
  22101. sse::SSEClient sse(client, "/event-with-id");
  22102. std::atomic<bool> id_received{false};
  22103. sse.on_message([&](const sse::SSEMessage &msg) {
  22104. if (!msg.id.empty()) { id_received.store(true); }
  22105. });
  22106. sse.set_reconnect_interval(100);
  22107. sse.set_max_reconnect_attempts(1);
  22108. sse.start_async();
  22109. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22110. sse.stop();
  22111. EXPECT_TRUE(id_received.load());
  22112. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22113. }
  22114. // Test: Manual stop
  22115. TEST_F(SSEIntegrationTest, ManualStop) {
  22116. // Endpoint that sends one event and stays open briefly. The server outlives
  22117. // this test body, so the provider uses the fixture's flag, not a local.
  22118. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22119. res.set_chunked_content_provider(
  22120. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22121. if (offset == 0) {
  22122. std::string event = "data: connected\n\n";
  22123. sink.write(event.data(), event.size());
  22124. }
  22125. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22126. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22127. }
  22128. return false;
  22129. });
  22130. });
  22131. Client client("localhost", get_port());
  22132. sse::SSEClient sse(client, "/stay-open");
  22133. std::atomic<bool> connected{false};
  22134. sse.on_open([&connected]() { connected.store(true); });
  22135. sse.set_reconnect_interval(100);
  22136. sse.set_max_reconnect_attempts(1);
  22137. sse.start_async();
  22138. // Wait for connection to establish
  22139. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22140. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22141. }
  22142. EXPECT_TRUE(connected.load());
  22143. EXPECT_TRUE(sse.is_connected());
  22144. // Signal handler to stop
  22145. stop_server_.store(true);
  22146. // Stop SSE client
  22147. sse.stop();
  22148. EXPECT_FALSE(sse.is_connected());
  22149. }
  22150. // Sends one event, then nothing until stop is set
  22151. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22152. return [&stop](const Request &, Response &res) {
  22153. res.set_chunked_content_provider(
  22154. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22155. if (offset == 0) {
  22156. std::string event = "data: hello\n\n";
  22157. sink.write(event.data(), event.size());
  22158. }
  22159. while (!stop.load()) {
  22160. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22161. }
  22162. return false;
  22163. });
  22164. };
  22165. }
  22166. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22167. static void check_stop_interrupts_blocked_read(Client &client) {
  22168. client.set_read_timeout(30, 0);
  22169. for (auto by_destructor : {false, true}) {
  22170. std::atomic<bool> received{false};
  22171. std::chrono::steady_clock::time_point start;
  22172. {
  22173. sse::SSEClient sse(client, "/idle-stream");
  22174. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22175. sse.start_async();
  22176. for (int i = 0; i < 500 && !received.load(); ++i) {
  22177. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22178. }
  22179. ASSERT_TRUE(received.load());
  22180. // Let the client block in the next read
  22181. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22182. start = std::chrono::steady_clock::now();
  22183. if (!by_destructor) { sse.stop(); }
  22184. }
  22185. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22186. std::chrono::seconds(2));
  22187. }
  22188. }
  22189. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22190. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22191. Client client("localhost", get_port());
  22192. check_stop_interrupts_blocked_read(client);
  22193. }
  22194. #ifdef CPPHTTPLIB_SSL_ENABLED
  22195. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22197. std::atomic<bool> done{false};
  22198. svr.Get("/idle-stream", idle_event_stream(done));
  22199. auto port = svr.bind_to_any_port(HOST);
  22200. std::thread t([&] { svr.listen_after_bind(); });
  22201. auto se = detail::scope_exit([&] {
  22202. done.store(true);
  22203. svr.stop();
  22204. t.join();
  22205. });
  22206. svr.wait_until_ready();
  22207. Client client("https://localhost:" + std::to_string(port));
  22208. client.enable_server_certificate_verification(false);
  22209. check_stop_interrupts_blocked_read(client);
  22210. }
  22211. #endif
  22212. // Test: SSEClient with custom headers
  22213. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22214. // Setup a server endpoint that checks for custom header
  22215. std::atomic<bool> header_received{false};
  22216. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22217. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22218. header_received.store(true);
  22219. }
  22220. res.set_chunked_content_provider("text/event-stream",
  22221. [](size_t, DataSink &) { return false; });
  22222. });
  22223. Client client("localhost", get_port());
  22224. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22225. sse::SSEClient sse(client, "/header-check", headers);
  22226. sse.set_max_reconnect_attempts(1);
  22227. sse.start_async();
  22228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22229. sse.stop();
  22230. EXPECT_TRUE(header_received.load());
  22231. }
  22232. // Test: Reconnect interval configuration
  22233. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22234. Client client("localhost", get_port());
  22235. sse::SSEClient sse(client, "/events");
  22236. auto &result = sse.set_reconnect_interval(500);
  22237. // Builder pattern should return reference to self
  22238. EXPECT_EQ(&result, &sse);
  22239. }
  22240. // Test: Max reconnect attempts
  22241. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22242. // Connect to non-existent port to force reconnects
  22243. Client client("localhost", 59998);
  22244. sse::SSEClient sse(client, "/events");
  22245. std::atomic<int> error_count{0};
  22246. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22247. sse.set_reconnect_interval(50);
  22248. sse.set_max_reconnect_attempts(2);
  22249. auto start = std::chrono::steady_clock::now();
  22250. sse.start(); // Blocking call
  22251. auto end = std::chrono::steady_clock::now();
  22252. // Should have stopped after 2 failed attempts
  22253. EXPECT_GE(error_count.load(), 2);
  22254. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22255. auto duration =
  22256. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22257. #ifdef _WIN32
  22258. // Windows is much slower for socket connection failures
  22259. EXPECT_LT(duration.count(), 7000);
  22260. #else
  22261. EXPECT_LT(duration.count(), 1000);
  22262. #endif
  22263. }
  22264. // Test: Multi-line data in integration
  22265. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22266. // Endpoint with multi-line data
  22267. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22268. res.set_chunked_content_provider(
  22269. "text/event-stream", [](size_t offset, DataSink &sink) {
  22270. if (offset == 0) {
  22271. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22272. sink.write(event.data(), event.size());
  22273. }
  22274. return false;
  22275. });
  22276. });
  22277. Client client("localhost", get_port());
  22278. sse::SSEClient sse(client, "/multiline-data");
  22279. std::string received_data;
  22280. std::mutex data_mutex;
  22281. sse.on_message([&](const sse::SSEMessage &msg) {
  22282. std::lock_guard<std::mutex> lock(data_mutex);
  22283. received_data = msg.data;
  22284. });
  22285. sse.set_reconnect_interval(100);
  22286. sse.set_max_reconnect_attempts(1);
  22287. sse.start_async();
  22288. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22289. sse.stop();
  22290. std::lock_guard<std::mutex> lock(data_mutex);
  22291. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22292. }
  22293. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22294. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22295. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22296. DataSink &sink) {
  22297. if (offset == 0) {
  22298. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22299. sink.write(events.data(), events.size());
  22300. }
  22301. return false;
  22302. });
  22303. });
  22304. Client client("localhost", get_port());
  22305. sse::SSEClient sse(client, "/empty-data-lines");
  22306. std::mutex mutex;
  22307. std::condition_variable cv;
  22308. std::vector<std::string> received;
  22309. sse.on_message([&](const sse::SSEMessage &msg) {
  22310. std::lock_guard<std::mutex> lock(mutex);
  22311. received.push_back(msg.data);
  22312. cv.notify_all();
  22313. });
  22314. sse.set_max_reconnect_attempts(1);
  22315. sse.start_async();
  22316. {
  22317. std::unique_lock<std::mutex> lock(mutex);
  22318. cv.wait_for(lock, std::chrono::seconds(2),
  22319. [&] { return received.size() >= 3; });
  22320. }
  22321. sse.stop();
  22322. ASSERT_GE(received.size(), 3u);
  22323. EXPECT_EQ(received[0], "");
  22324. EXPECT_EQ(received[1], "\nhello");
  22325. EXPECT_EQ(received[2], "");
  22326. }
  22327. // Test: Auto-reconnect after server disconnection
  22328. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22329. std::atomic<int> connection_count{0};
  22330. std::atomic<int> message_count{0};
  22331. // Endpoint that sends one event and closes, forcing reconnect
  22332. server_->Get("/reconnect-test",
  22333. [&connection_count](const Request &, Response &res) {
  22334. connection_count.fetch_add(1);
  22335. res.set_chunked_content_provider(
  22336. "text/event-stream", [](size_t offset, DataSink &sink) {
  22337. if (offset == 0) {
  22338. std::string event = "data: hello\n\n";
  22339. sink.write(event.data(), event.size());
  22340. }
  22341. return false; // Close connection after sending
  22342. });
  22343. });
  22344. Client client("localhost", get_port());
  22345. sse::SSEClient sse(client, "/reconnect-test");
  22346. sse.on_message([&message_count](const sse::SSEMessage &) {
  22347. message_count.fetch_add(1);
  22348. });
  22349. sse.set_reconnect_interval(100);
  22350. sse.set_max_reconnect_attempts(3);
  22351. sse.start_async();
  22352. // Wait long enough for multiple reconnects
  22353. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22354. sse.stop();
  22355. // Should have connected multiple times (initial + reconnects)
  22356. EXPECT_GE(connection_count.load(), 2);
  22357. // Should have received messages from multiple connections
  22358. EXPECT_GE(message_count.load(), 2);
  22359. }
  22360. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22361. std::atomic<int> connection_count{0};
  22362. // Neither Content-Length nor chunked: the close ends the stream
  22363. server_->Get("/close-delimited",
  22364. [&connection_count](const Request &, Response &res) {
  22365. connection_count.fetch_add(1);
  22366. res.set_content_provider(
  22367. "text/event-stream", [](size_t offset, DataSink &sink) {
  22368. if (offset == 0) {
  22369. std::string event = "data: hello\n\n";
  22370. sink.write(event.data(), event.size());
  22371. } else {
  22372. sink.done();
  22373. }
  22374. return true;
  22375. });
  22376. });
  22377. Client client("localhost", get_port());
  22378. sse::SSEClient sse(client, "/close-delimited");
  22379. std::atomic<int> error_count{0};
  22380. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22381. sse.set_reconnect_interval(100);
  22382. sse.start_async();
  22383. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22384. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22385. }
  22386. sse.stop();
  22387. // Reconnects as after any end of the stream, but reports no error
  22388. EXPECT_GE(connection_count.load(), 2);
  22389. EXPECT_EQ(0, error_count.load());
  22390. }
  22391. // Test: A retry field that is not all ASCII digits is ignored
  22392. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22393. std::atomic<int> connection_count{0};
  22394. server_->Get("/bad-retry",
  22395. [&connection_count](const Request &, Response &res) {
  22396. connection_count.fetch_add(1);
  22397. res.set_chunked_content_provider(
  22398. "text/event-stream", [](size_t offset, DataSink &sink) {
  22399. if (offset == 0) {
  22400. std::string event = "retry: -1\ndata: hello\n\n";
  22401. sink.write(event.data(), event.size());
  22402. }
  22403. return false;
  22404. });
  22405. });
  22406. Client client("localhost", get_port());
  22407. sse::SSEClient sse(client, "/bad-retry");
  22408. sse.set_reconnect_interval(10000);
  22409. sse.start_async();
  22410. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22411. sse.stop();
  22412. EXPECT_EQ(connection_count.load(), 1);
  22413. }
  22414. // Test: A retry field of all ASCII digits sets the reconnection time
  22415. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22416. std::mutex mutex;
  22417. std::condition_variable cv;
  22418. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22419. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22420. {
  22421. std::lock_guard<std::mutex> lock(mutex);
  22422. connected_at.push_back(std::chrono::steady_clock::now());
  22423. cv.notify_all();
  22424. }
  22425. res.set_chunked_content_provider(
  22426. "text/event-stream", [](size_t offset, DataSink &sink) {
  22427. if (offset == 0) {
  22428. std::string event = "retry: 0\ndata: hello\n\n";
  22429. sink.write(event.data(), event.size());
  22430. }
  22431. return false;
  22432. });
  22433. });
  22434. Client client("localhost", get_port());
  22435. sse::SSEClient sse(client, "/zero-retry");
  22436. sse.set_reconnect_interval(10000);
  22437. sse.start_async();
  22438. {
  22439. std::unique_lock<std::mutex> lock(mutex);
  22440. cv.wait_for(lock, std::chrono::seconds(5),
  22441. [&] { return connected_at.size() >= 2; });
  22442. }
  22443. sse.stop();
  22444. // The server-supplied interval is applied, but never below 100ms, so
  22445. // "retry: 0" does not cause a busy reconnect loop
  22446. std::lock_guard<std::mutex> lock(mutex);
  22447. ASSERT_GE(connected_at.size(), 2u);
  22448. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22449. connected_at[1] - connected_at[0])
  22450. .count();
  22451. EXPECT_GE(interval_ms, 100);
  22452. }
  22453. // Test: Last-Event-ID sent on reconnect
  22454. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22455. std::atomic<int> connection_count{0};
  22456. std::vector<std::string> received_last_event_ids;
  22457. std::mutex id_mutex;
  22458. // Endpoint that checks Last-Event-ID header and sends event with ID
  22459. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22460. int conn = connection_count.fetch_add(1);
  22461. // Capture the Last-Event-ID header from each connection
  22462. {
  22463. std::lock_guard<std::mutex> lock(id_mutex);
  22464. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22465. }
  22466. res.set_chunked_content_provider(
  22467. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22468. if (offset == 0) {
  22469. std::string event =
  22470. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22471. sink.write(event.data(), event.size());
  22472. }
  22473. return false;
  22474. });
  22475. });
  22476. Client client("localhost", get_port());
  22477. sse::SSEClient sse(client, "/reconnect-with-id");
  22478. sse.set_reconnect_interval(100);
  22479. sse.set_max_reconnect_attempts(3);
  22480. sse.start_async();
  22481. // Wait for at least 2 connections
  22482. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22483. sse.stop();
  22484. // Verify behavior
  22485. std::lock_guard<std::mutex> lock(id_mutex);
  22486. EXPECT_GE(received_last_event_ids.size(), 2u);
  22487. // First connection should have no Last-Event-ID
  22488. if (!received_last_event_ids.empty()) {
  22489. EXPECT_EQ(received_last_event_ids[0], "");
  22490. }
  22491. // Second connection should have Last-Event-ID from first connection
  22492. if (received_last_event_ids.size() >= 2) {
  22493. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22494. }
  22495. }
  22496. // Test: set_headers updates headers used on reconnect
  22497. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22498. std::vector<std::string> received_tokens;
  22499. std::mutex token_mutex;
  22500. // Endpoint that captures Authorization header
  22501. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22502. {
  22503. std::lock_guard<std::mutex> lock(token_mutex);
  22504. received_tokens.push_back(req.get_header_value("Authorization"));
  22505. }
  22506. res.set_chunked_content_provider(
  22507. "text/event-stream", [](size_t offset, DataSink &sink) {
  22508. if (offset == 0) {
  22509. std::string event = "data: hello\n\n";
  22510. sink.write(event.data(), event.size());
  22511. }
  22512. return false; // Close connection to trigger reconnect
  22513. });
  22514. });
  22515. Client client("localhost", get_port());
  22516. Headers headers = {{"Authorization", "Bearer old-token"}};
  22517. sse::SSEClient sse(client, "/auth-check", headers);
  22518. // Update headers on each successful connection
  22519. sse.on_open(
  22520. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22521. sse.set_reconnect_interval(100);
  22522. sse.set_max_reconnect_attempts(3);
  22523. sse.start_async();
  22524. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22525. sse.stop();
  22526. std::lock_guard<std::mutex> lock(token_mutex);
  22527. ASSERT_GE(received_tokens.size(), 2u);
  22528. // First connection uses original header
  22529. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22530. // Second connection uses updated header from set_headers
  22531. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22532. }
  22533. // Test: 401 allows reconnection (so on_error can refresh headers)
  22534. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22535. std::atomic<int> connection_count{0};
  22536. // Endpoint: returns 401 on first attempt, 200 on second
  22537. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22538. int conn = connection_count.fetch_add(1);
  22539. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22540. res.status = StatusCode::Unauthorized_401;
  22541. res.set_content("Unauthorized", "text/plain");
  22542. return;
  22543. }
  22544. res.set_chunked_content_provider(
  22545. "text/event-stream", [](size_t offset, DataSink &sink) {
  22546. if (offset == 0) {
  22547. std::string event = "data: authenticated\n\n";
  22548. sink.write(event.data(), event.size());
  22549. }
  22550. return false;
  22551. });
  22552. });
  22553. Client client("localhost", get_port());
  22554. Headers headers = {{"Authorization", "Bearer expired"}};
  22555. sse::SSEClient sse(client, "/auth-retry", headers);
  22556. std::atomic<bool> message_received{false};
  22557. // Refresh token on error
  22558. sse.on_error(
  22559. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22560. sse.on_message([&](const sse::SSEMessage &msg) {
  22561. if (msg.data == "authenticated") { message_received.store(true); }
  22562. });
  22563. sse.set_reconnect_interval(100);
  22564. sse.set_max_reconnect_attempts(3);
  22565. sse.start_async();
  22566. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22567. sse.stop();
  22568. // Should have reconnected after 401 and succeeded with new token
  22569. EXPECT_GE(connection_count.load(), 2);
  22570. EXPECT_TRUE(message_received.load());
  22571. }
  22572. TEST(Issue2318Test, EmptyHostString) {
  22573. {
  22574. httplib::Client cli_empty("", PORT);
  22575. auto res = cli_empty.Get("/");
  22576. ASSERT_FALSE(res);
  22577. EXPECT_EQ(httplib::Error::Connection, res.error());
  22578. }
  22579. {
  22580. httplib::Client cli(" ", PORT);
  22581. auto res = cli.Get("/");
  22582. ASSERT_FALSE(res);
  22583. EXPECT_EQ(httplib::Error::Connection, res.error());
  22584. }
  22585. }
  22586. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22587. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22588. Server svr;
  22589. // Set a small payload limit (1KB)
  22590. svr.set_payload_max_length(1024);
  22591. svr.Post("/test", [&](const Request &req, Response &res) {
  22592. res.set_content("Body size: " + std::to_string(req.body.size()),
  22593. "text/plain");
  22594. });
  22595. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22596. auto se = detail::scope_exit([&] {
  22597. svr.stop();
  22598. listen_thread.join();
  22599. });
  22600. svr.wait_until_ready();
  22601. // Create data that compresses well but exceeds limit when decompressed
  22602. // 8KB of repeated null bytes compresses to a very small size
  22603. std::string original_data(8 * 1024, '\0');
  22604. // Compress the data using gzip
  22605. std::string compressed_data;
  22606. detail::gzip_compressor compressor;
  22607. compressor.compress(original_data.data(), original_data.size(), true,
  22608. [&](const char *data, size_t size) {
  22609. compressed_data.append(data, size);
  22610. return true;
  22611. });
  22612. // Verify compression worked (compressed should be much smaller)
  22613. ASSERT_LT(compressed_data.size(), original_data.size());
  22614. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22615. // Send compressed data with Content-Encoding: gzip
  22616. Client cli(HOST, PORT);
  22617. Headers headers = {{"Content-Encoding", "gzip"}};
  22618. auto res =
  22619. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22620. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22622. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22623. }
  22624. #endif
  22625. // ============================================================================
  22626. // OpenSSL-Specific Tests
  22627. // ============================================================================
  22628. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22629. X509 *readCertificate(const std::string &strFileName) {
  22630. std::ifstream inStream(strFileName);
  22631. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22632. std::istreambuf_iterator<char>());
  22633. if (strCertPEM.empty()) return (nullptr);
  22634. BIO *pbCert = BIO_new(BIO_s_mem());
  22635. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22636. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22637. BIO_free(pbCert);
  22638. return (pCert);
  22639. }
  22640. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22641. std::ifstream inStream(strFileName);
  22642. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22643. std::istreambuf_iterator<char>());
  22644. if (strPrivateKeyPEM.empty()) return (nullptr);
  22645. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22646. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22647. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22648. BIO_free(pbPrivKey);
  22649. return (pPrivateKey);
  22650. }
  22651. TEST(BindServerTest, UpdateCerts) {
  22652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22653. int port = svr.bind_to_any_port("0.0.0.0");
  22654. ASSERT_TRUE(svr.is_valid());
  22655. ASSERT_TRUE(port > 0);
  22656. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22657. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22658. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22659. ASSERT_TRUE(cert != nullptr);
  22660. ASSERT_TRUE(ca_cert != nullptr);
  22661. ASSERT_TRUE(key != nullptr);
  22662. X509_STORE *cert_store = X509_STORE_new();
  22663. X509_STORE_add_cert(cert_store, ca_cert);
  22664. // svr.update_certs(cert, key, cert_store); // deprecated
  22665. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22666. CLIENT_CA_CERT_FILE);
  22667. ASSERT_TRUE(svr.is_valid());
  22668. svr.stop();
  22669. X509_STORE_free(cert_store);
  22670. X509_free(cert);
  22671. X509_free(ca_cert);
  22672. EVP_PKEY_free(key);
  22673. }
  22674. // Test that update_certs() updates client CA list correctly
  22675. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22676. // Start with file-based constructor
  22677. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22678. ASSERT_TRUE(svr.is_valid());
  22679. // Initially no client CA list should be set
  22680. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22681. ASSERT_TRUE(ssl_ctx != nullptr);
  22682. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22683. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22684. // Now update with client CA (PEM string)
  22685. std::string cert_pem, key_pem, ca_pem;
  22686. read_file(SERVER_CERT_FILE, cert_pem);
  22687. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22688. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22689. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22690. ASSERT_TRUE(svr.is_valid());
  22691. // Now client CA list should be set
  22692. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22693. ASSERT_TRUE(ca_list_after != nullptr);
  22694. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22695. }
  22696. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22697. // Test that the file-path SSLServer constructor properly sets the client CA
  22698. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22700. ASSERT_TRUE(svr.is_valid());
  22701. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22702. ASSERT_TRUE(ssl_ctx != nullptr);
  22703. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22704. ASSERT_TRUE(ca_list != nullptr);
  22705. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22706. }
  22707. #endif
  22708. // ============================================================================
  22709. // MbedTLS-Specific Tests
  22710. // ============================================================================
  22711. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22712. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22713. using namespace httplib::tls;
  22714. // Track if callback was invoked
  22715. bool callback_invoked = false;
  22716. // The callback receives void* ctx which is actually MbedTlsContext*
  22717. // We can access the mbedtls_ssl_config via the context
  22718. auto setup_callback = [&callback_invoked](void *ctx) {
  22719. callback_invoked = true;
  22720. // Cast to MbedTlsContext* to access the ssl config
  22721. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22722. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22723. // Use static variables to hold certificate data (simplified for test)
  22724. static mbedtls_x509_crt own_cert;
  22725. static mbedtls_pk_context own_key;
  22726. static mbedtls_x509_crt ca_chain;
  22727. static bool initialized = false;
  22728. if (!initialized) {
  22729. mbedtls_x509_crt_init(&own_cert);
  22730. mbedtls_pk_init(&own_key);
  22731. mbedtls_x509_crt_init(&ca_chain);
  22732. // Load server certificate
  22733. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22734. return false;
  22735. }
  22736. // Load server private key.
  22737. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22738. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22739. #if MBEDTLS_VERSION_MAJOR == 3
  22740. ,
  22741. mbedtls_ctr_drbg_random, nullptr
  22742. #endif
  22743. ) != 0) {
  22744. return false;
  22745. }
  22746. // Load CA chain for client verification
  22747. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22748. return false;
  22749. }
  22750. initialized = true;
  22751. }
  22752. // Configure the SSL config
  22753. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22754. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22755. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22756. // Set minimum TLS version using mbedTLS native API
  22757. #if MBEDTLS_VERSION_MAJOR >= 3
  22758. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22759. #else
  22760. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22761. MBEDTLS_SSL_MINOR_VERSION_3);
  22762. #endif
  22763. return true;
  22764. };
  22765. SSLServer svr(setup_callback);
  22766. ASSERT_TRUE(svr.is_valid());
  22767. ASSERT_TRUE(callback_invoked);
  22768. svr.Get("/test", [&](const Request &req, Response &res) {
  22769. res.set_content("test", "text/plain");
  22770. auto cert = req.peer_cert();
  22771. ASSERT_TRUE(static_cast<bool>(cert));
  22772. auto common_name = cert.subject_cn();
  22773. EXPECT_EQ("Common Name", common_name);
  22774. });
  22775. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22776. auto se = detail::scope_exit([&] {
  22777. svr.stop();
  22778. t.join();
  22779. ASSERT_FALSE(svr.is_running());
  22780. });
  22781. svr.wait_until_ready();
  22782. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22783. cli.enable_server_certificate_verification(false);
  22784. cli.set_connection_timeout(30);
  22785. auto res = cli.Get("/test");
  22786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22787. ASSERT_EQ(StatusCode::OK_200, res->status);
  22788. }
  22789. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22790. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22791. // keep-alive SSL session, which reads through that config in
  22792. // mbedtls_ssl_close_notify.
  22793. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22795. ASSERT_TRUE(svr.is_valid());
  22796. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22797. res.set_content("test", "text/plain");
  22798. });
  22799. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22800. auto se = detail::scope_exit([&] {
  22801. svr.stop();
  22802. t.join();
  22803. ASSERT_FALSE(svr.is_running());
  22804. });
  22805. svr.wait_until_ready();
  22806. {
  22807. SSLClient cli(HOST, PORT);
  22808. cli.enable_server_certificate_verification(false);
  22809. cli.set_keep_alive(true);
  22810. auto res = cli.Get("/test");
  22811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22812. ASSERT_EQ(StatusCode::OK_200, res->status);
  22813. // cli is destructed here with the keep-alive SSL session still open.
  22814. }
  22815. }
  22816. #endif
  22817. // WebSocket Tests
  22818. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22819. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22820. // defining the meaning of these bits has been negotiated.
  22821. auto make_frame = [](uint8_t first_byte) {
  22822. std::string frame;
  22823. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22824. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22825. frame += "Hello";
  22826. return frame;
  22827. };
  22828. // RSV1 set (0x40)
  22829. {
  22830. detail::BufferStream strm;
  22831. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22832. ws::Opcode opcode;
  22833. std::string payload;
  22834. bool fin;
  22835. EXPECT_EQ(
  22836. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22837. ws::impl::FrameRead::Fail);
  22838. }
  22839. // RSV2 set (0x20)
  22840. {
  22841. detail::BufferStream strm;
  22842. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22843. ws::Opcode opcode;
  22844. std::string payload;
  22845. bool fin;
  22846. EXPECT_EQ(
  22847. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22848. ws::impl::FrameRead::Fail);
  22849. }
  22850. // RSV3 set (0x10)
  22851. {
  22852. detail::BufferStream strm;
  22853. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22854. ws::Opcode opcode;
  22855. std::string payload;
  22856. bool fin;
  22857. EXPECT_EQ(
  22858. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22859. ws::impl::FrameRead::Fail);
  22860. }
  22861. // No RSV bits set - should succeed
  22862. {
  22863. detail::BufferStream strm;
  22864. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22865. ws::Opcode opcode;
  22866. std::string payload;
  22867. bool fin;
  22868. EXPECT_EQ(
  22869. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22870. ws::impl::FrameRead::Ok);
  22871. EXPECT_EQ(ws::Opcode::Text, opcode);
  22872. EXPECT_EQ("Hello", payload);
  22873. EXPECT_TRUE(fin);
  22874. }
  22875. }
  22876. TEST(WebSocketTest, ControlFrameValidation) {
  22877. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22878. // payload length <= 125.
  22879. // Ping with FIN=0 - must be rejected
  22880. {
  22881. detail::BufferStream strm;
  22882. std::string frame;
  22883. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22884. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22885. strm.write(frame.data(), frame.size());
  22886. ws::Opcode opcode;
  22887. std::string payload;
  22888. bool fin;
  22889. EXPECT_EQ(
  22890. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22891. ws::impl::FrameRead::Fail);
  22892. }
  22893. // Close with FIN=0 - must be rejected
  22894. {
  22895. detail::BufferStream strm;
  22896. std::string frame;
  22897. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22898. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22899. strm.write(frame.data(), frame.size());
  22900. ws::Opcode opcode;
  22901. std::string payload;
  22902. bool fin;
  22903. EXPECT_EQ(
  22904. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22905. ws::impl::FrameRead::Fail);
  22906. }
  22907. // Ping with payload_len=126 (extended length) - must be rejected
  22908. {
  22909. detail::BufferStream strm;
  22910. std::string frame;
  22911. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22912. frame += static_cast<char>(126); // payload_len=126 (>125)
  22913. frame += static_cast<char>(0x00); // extended length high byte
  22914. frame += static_cast<char>(126); // extended length low byte
  22915. frame += std::string(126, 'x');
  22916. strm.write(frame.data(), frame.size());
  22917. ws::Opcode opcode;
  22918. std::string payload;
  22919. bool fin;
  22920. EXPECT_EQ(
  22921. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22922. ws::impl::FrameRead::Fail);
  22923. }
  22924. // Ping with FIN=1 and payload_len=125 - should succeed
  22925. {
  22926. detail::BufferStream strm;
  22927. std::string frame;
  22928. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22929. frame += static_cast<char>(125); // payload_len=125
  22930. frame += std::string(125, 'x');
  22931. strm.write(frame.data(), frame.size());
  22932. ws::Opcode opcode;
  22933. std::string payload;
  22934. bool fin;
  22935. EXPECT_EQ(
  22936. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22937. ws::impl::FrameRead::Ok);
  22938. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22939. EXPECT_EQ(125u, payload.size());
  22940. EXPECT_TRUE(fin);
  22941. }
  22942. }
  22943. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22944. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22945. // length MUST be 0.
  22946. // MSB set - must be rejected
  22947. {
  22948. detail::BufferStream strm;
  22949. std::string frame;
  22950. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22951. frame += static_cast<char>(127); // 64-bit extended length
  22952. frame += static_cast<char>(0x80); // MSB set (invalid)
  22953. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22954. strm.write(frame.data(), frame.size());
  22955. ws::Opcode opcode;
  22956. std::string payload;
  22957. bool fin;
  22958. EXPECT_EQ(
  22959. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22960. ws::impl::FrameRead::Fail);
  22961. }
  22962. // MSB clear - should pass length parsing (will be rejected by max_len,
  22963. // but that's a different check; use a small length to verify)
  22964. {
  22965. detail::BufferStream strm;
  22966. std::string frame;
  22967. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22968. frame += static_cast<char>(127); // 64-bit extended length
  22969. frame += std::string(7, '\0'); // high bytes = 0
  22970. frame += static_cast<char>(0x03); // length = 3
  22971. frame += "abc";
  22972. strm.write(frame.data(), frame.size());
  22973. ws::Opcode opcode;
  22974. std::string payload;
  22975. bool fin;
  22976. EXPECT_EQ(
  22977. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22978. ws::impl::FrameRead::Ok);
  22979. EXPECT_EQ(ws::Opcode::Text, opcode);
  22980. EXPECT_EQ("abc", payload);
  22981. }
  22982. }
  22983. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22984. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22985. // Valid UTF-8
  22986. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22987. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22988. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22989. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22990. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22991. // Invalid UTF-8
  22992. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22993. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22994. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22995. EXPECT_FALSE(
  22996. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22997. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22998. }
  22999. TEST(WebSocketTest, ConnectAndDisconnect) {
  23000. Server svr;
  23001. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23002. std::string msg;
  23003. while (ws.read(msg)) {}
  23004. });
  23005. auto port = svr.bind_to_any_port(HOST);
  23006. std::thread t([&]() { svr.listen_after_bind(); });
  23007. svr.wait_until_ready();
  23008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23009. auto res = client.connect();
  23010. ASSERT_TRUE(res);
  23011. EXPECT_EQ(Error::Success, res.error());
  23012. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23013. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23014. EXPECT_TRUE(client.is_open());
  23015. client.close();
  23016. EXPECT_FALSE(client.is_open());
  23017. svr.stop();
  23018. t.join();
  23019. }
  23020. TEST(WebSocketTest, ValidURL) {
  23021. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23022. EXPECT_TRUE(ws1.is_valid());
  23023. ws::WebSocketClient ws2("ws://example.com/path");
  23024. EXPECT_TRUE(ws2.is_valid());
  23025. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23026. EXPECT_TRUE(ws3.is_valid());
  23027. #ifdef CPPHTTPLIB_SSL_ENABLED
  23028. ws::WebSocketClient wss1("wss://example.com/path");
  23029. EXPECT_TRUE(wss1.is_valid());
  23030. ws::WebSocketClient wss2("wss://example.com:443/path");
  23031. EXPECT_TRUE(wss2.is_valid());
  23032. #endif
  23033. }
  23034. TEST(WebSocketTest, InvalidURL) {
  23035. // No scheme
  23036. ws::WebSocketClient ws1("localhost:8080/path");
  23037. EXPECT_FALSE(ws1.is_valid());
  23038. // No path
  23039. ws::WebSocketClient ws2("ws://localhost:8080");
  23040. EXPECT_FALSE(ws2.is_valid());
  23041. // Empty string
  23042. ws::WebSocketClient ws3("");
  23043. EXPECT_FALSE(ws3.is_valid());
  23044. // Missing host
  23045. ws::WebSocketClient ws4("ws://:8080/path");
  23046. EXPECT_FALSE(ws4.is_valid());
  23047. // Port number overflow — should not crash
  23048. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23049. EXPECT_FALSE(ws5.is_valid());
  23050. // Port out of range
  23051. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23052. EXPECT_FALSE(ws6.is_valid());
  23053. }
  23054. TEST(WebSocketTest, UnsupportedScheme) {
  23055. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23056. ws::WebSocketClient ws1("http://localhost:8080/path");
  23057. EXPECT_FALSE(ws1.is_valid());
  23058. ws::WebSocketClient ws2("https://localhost:8080/path");
  23059. EXPECT_FALSE(ws2.is_valid());
  23060. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23061. EXPECT_FALSE(ws3.is_valid());
  23062. #else
  23063. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23064. std::invalid_argument);
  23065. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23066. std::invalid_argument);
  23067. #endif
  23068. }
  23069. TEST(WebSocketTest, ConnectWhenInvalid) {
  23070. ws::WebSocketClient ws("not a valid url");
  23071. EXPECT_FALSE(ws.is_valid());
  23072. auto res = ws.connect();
  23073. EXPECT_FALSE(res);
  23074. EXPECT_EQ(Error::Connection, res.error());
  23075. EXPECT_EQ(-1, res.status());
  23076. }
  23077. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23078. // Grab a port that is free, then close it again so nothing listens there
  23079. Server svr;
  23080. auto port = svr.bind_to_any_port(HOST);
  23081. svr.stop();
  23082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23083. auto res = client.connect();
  23084. ASSERT_FALSE(res);
  23085. EXPECT_EQ(Error::Connection, res.error());
  23086. EXPECT_EQ(-1, res.status());
  23087. }
  23088. TEST(WebSocketTest, DefaultPort) {
  23089. ws::WebSocketClient ws1("ws://example.com/path");
  23090. EXPECT_TRUE(ws1.is_valid());
  23091. // ws:// defaults to port 80 (verified by successful parse)
  23092. #ifdef CPPHTTPLIB_SSL_ENABLED
  23093. ws::WebSocketClient ws2("wss://example.com/path");
  23094. EXPECT_TRUE(ws2.is_valid());
  23095. // wss:// defaults to port 443 (verified by successful parse)
  23096. #endif
  23097. }
  23098. TEST(WebSocketTest, IPv6LiteralAddress) {
  23099. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23100. EXPECT_TRUE(ws1.is_valid());
  23101. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23102. EXPECT_TRUE(ws2.is_valid());
  23103. }
  23104. TEST(WebSocketTest, ComplexPath) {
  23105. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23106. EXPECT_TRUE(ws1.is_valid());
  23107. ws::WebSocketClient ws2("ws://localhost:8080/");
  23108. EXPECT_TRUE(ws2.is_valid());
  23109. }
  23110. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23111. Server svr;
  23112. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23113. std::string msg;
  23114. while (ws.read(msg)) {}
  23115. });
  23116. auto port = svr.bind_to_any_port(HOST);
  23117. std::thread t([&]() { svr.listen_after_bind(); });
  23118. svr.wait_until_ready();
  23119. auto another_host = "example.com";
  23120. auto wrong_ip = "192.0.2.1";
  23121. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23122. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23123. ASSERT_TRUE(client.connect());
  23124. EXPECT_TRUE(client.is_open());
  23125. client.close();
  23126. svr.stop();
  23127. t.join();
  23128. }
  23129. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23130. Server svr;
  23131. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23132. std::string msg;
  23133. while (ws.read(msg)) {}
  23134. });
  23135. auto port = svr.bind_to_any_port(HOST);
  23136. std::thread t([&]() { svr.listen_after_bind(); });
  23137. svr.wait_until_ready();
  23138. auto wrong_ip = "192.0.2.1";
  23139. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23140. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23141. client.set_connection_timeout(1);
  23142. client.set_read_timeout(1);
  23143. client.set_write_timeout(1);
  23144. EXPECT_FALSE(client.connect());
  23145. EXPECT_FALSE(client.is_open());
  23146. svr.stop();
  23147. t.join();
  23148. }
  23149. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23150. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23151. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23152. // (RFC 6761) is only a map key and the Host header value.
  23153. auto host = "target.invalid";
  23154. Server svr;
  23155. std::string received_host;
  23156. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23157. received_host = req.get_header_value("Host");
  23158. std::string msg;
  23159. while (ws.read(msg)) {}
  23160. });
  23161. auto port = svr.bind_to_any_port(HOST);
  23162. std::thread t([&]() { svr.listen_after_bind(); });
  23163. // ASSERT_* below returns from the test body, which would leave t joinable
  23164. // and make ~thread call std::terminate.
  23165. auto se = detail::scope_exit([&] {
  23166. svr.stop();
  23167. if (t.joinable()) { t.join(); }
  23168. });
  23169. svr.wait_until_ready();
  23170. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23171. std::to_string(port) + "/ws");
  23172. client.set_hostname_addr_map({{host, HOST}});
  23173. ASSERT_TRUE(client.connect());
  23174. EXPECT_TRUE(client.is_open());
  23175. client.close();
  23176. svr.stop();
  23177. t.join();
  23178. // The mapping only redirects the connection; the identity stays host_.
  23179. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23180. }
  23181. class WebSocketIntegrationTest : public ::testing::Test {
  23182. protected:
  23183. void SetUp() override {
  23184. server_ = httplib::detail::make_unique<Server>();
  23185. setup_server();
  23186. start_server();
  23187. }
  23188. void TearDown() override {
  23189. server_->stop();
  23190. if (server_thread_.joinable()) { server_thread_.join(); }
  23191. }
  23192. void setup_server() {
  23193. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23194. std::string msg;
  23195. ws::ReadResult ret;
  23196. while ((ret = ws.read(msg))) {
  23197. if (ret == ws::Binary) {
  23198. ws.send(msg.data(), msg.size());
  23199. } else {
  23200. ws.send(msg);
  23201. }
  23202. }
  23203. });
  23204. server_->WebSocket("/ws-echo-string",
  23205. [](const Request &, ws::WebSocket &ws) {
  23206. std::string msg;
  23207. while (ws.read(msg)) {
  23208. ws.send("echo: " + msg);
  23209. }
  23210. });
  23211. server_->WebSocket(
  23212. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23213. // Echo back request metadata
  23214. ws.send("path:" + req.path);
  23215. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23216. std::string msg;
  23217. while (ws.read(msg)) {}
  23218. });
  23219. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23220. std::string msg;
  23221. ws.read(msg); // wait for a message
  23222. ws.close();
  23223. });
  23224. server_->WebSocket("/ws-close-status",
  23225. [](const Request &, ws::WebSocket &ws) {
  23226. std::string msg;
  23227. ws.read(msg); // wait for a message
  23228. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23229. });
  23230. server_->WebSocket(
  23231. "/ws-subprotocol",
  23232. [](const Request &, ws::WebSocket &ws) {
  23233. std::string msg;
  23234. while (ws.read(msg)) {
  23235. ws.send(msg);
  23236. }
  23237. },
  23238. [](const std::vector<std::string> &protocols) -> std::string {
  23239. for (const auto &p : protocols) {
  23240. if (p == "graphql-ws") { return p; }
  23241. }
  23242. return "";
  23243. });
  23244. server_->WebSocket(
  23245. "/ws-subprotocol-unoffered",
  23246. [](const Request &, ws::WebSocket &ws) {
  23247. std::string msg;
  23248. while (ws.read(msg)) {
  23249. ws.send(msg);
  23250. }
  23251. },
  23252. [](const std::vector<std::string> &) -> std::string {
  23253. return "admin";
  23254. });
  23255. }
  23256. void start_server() {
  23257. port_ = server_->bind_to_any_port(HOST);
  23258. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23259. server_->wait_until_ready();
  23260. }
  23261. std::unique_ptr<Server> server_;
  23262. std::thread server_thread_;
  23263. int port_ = 0;
  23264. };
  23265. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23266. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23267. "/ws-echo");
  23268. ASSERT_TRUE(client.connect());
  23269. ASSERT_TRUE(client.is_open());
  23270. ASSERT_TRUE(client.send("Hello WebSocket"));
  23271. std::string msg;
  23272. EXPECT_EQ(ws::Text, client.read(msg));
  23273. EXPECT_EQ("Hello WebSocket", msg);
  23274. client.close();
  23275. }
  23276. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23277. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23278. "/ws-echo");
  23279. ASSERT_TRUE(client.connect());
  23280. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23281. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23282. std::string msg;
  23283. EXPECT_EQ(ws::Binary, client.read(msg));
  23284. EXPECT_EQ(binary_data, msg);
  23285. client.close();
  23286. }
  23287. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23288. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23289. "/ws-echo");
  23290. ASSERT_TRUE(client.connect());
  23291. for (int i = 0; i < 10; i++) {
  23292. auto text = "message " + std::to_string(i);
  23293. ASSERT_TRUE(client.send(text));
  23294. std::string msg;
  23295. ASSERT_TRUE(client.read(msg));
  23296. EXPECT_EQ(text, msg);
  23297. }
  23298. client.close();
  23299. }
  23300. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23301. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23302. "/ws-close");
  23303. ASSERT_TRUE(client.connect());
  23304. // Send a message to trigger the server to close
  23305. ASSERT_TRUE(client.send("trigger close"));
  23306. // The server will close, so read should return false
  23307. std::string msg;
  23308. EXPECT_FALSE(client.read(msg));
  23309. EXPECT_FALSE(client.is_open());
  23310. }
  23311. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23312. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23313. "/ws-echo");
  23314. ASSERT_TRUE(client.connect());
  23315. // 128KB message
  23316. std::string large_data(128 * 1024, 'X');
  23317. ASSERT_TRUE(client.send(large_data));
  23318. std::string msg;
  23319. ASSERT_TRUE(client.read(msg));
  23320. EXPECT_EQ(large_data, msg);
  23321. client.close();
  23322. }
  23323. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23324. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23325. "/ws-echo");
  23326. ASSERT_TRUE(client.connect());
  23327. const int num_threads = 4;
  23328. std::vector<std::thread> threads;
  23329. std::atomic<int> send_count{0};
  23330. for (int t = 0; t < num_threads; t++) {
  23331. threads.emplace_back([&client, &send_count, t]() {
  23332. for (int i = 0; i < 5; i++) {
  23333. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23334. if (client.send(text)) { send_count++; }
  23335. }
  23336. });
  23337. }
  23338. for (auto &th : threads) {
  23339. th.join();
  23340. }
  23341. int received = 0;
  23342. std::string msg;
  23343. while (received < send_count.load()) {
  23344. if (!client.read(msg)) { break; }
  23345. received++;
  23346. }
  23347. EXPECT_EQ(send_count.load(), received);
  23348. client.close();
  23349. }
  23350. TEST_F(WebSocketIntegrationTest, ReadString) {
  23351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23352. "/ws-echo-string");
  23353. ASSERT_TRUE(client.connect());
  23354. ASSERT_TRUE(client.send("hello"));
  23355. std::string msg;
  23356. ASSERT_TRUE(client.read(msg));
  23357. EXPECT_EQ("echo: hello", msg);
  23358. ASSERT_TRUE(client.send("world"));
  23359. ASSERT_TRUE(client.read(msg));
  23360. EXPECT_EQ("echo: world", msg);
  23361. client.close();
  23362. }
  23363. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23364. Headers headers = {{"X-Test-Header", "test-value"}};
  23365. ws::WebSocketClient client(
  23366. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23367. ASSERT_TRUE(client.connect());
  23368. std::string msg;
  23369. ASSERT_TRUE(client.read(msg));
  23370. EXPECT_EQ("path:/ws-request-info", msg);
  23371. ASSERT_TRUE(client.read(msg));
  23372. EXPECT_EQ("header:test-value", msg);
  23373. client.close();
  23374. }
  23375. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23377. "/ws-echo");
  23378. client.set_read_timeout(1, 0); // 1 second
  23379. ASSERT_TRUE(client.connect());
  23380. // Don't send anything — server echo handler waits for a message, so read()
  23381. // should time out. The connection survives it: nothing was consumed.
  23382. std::string msg;
  23383. EXPECT_EQ(client.read(msg), ws::Timeout);
  23384. EXPECT_TRUE(client.is_open());
  23385. // And it is still usable afterwards.
  23386. EXPECT_TRUE(client.send("after timeout"));
  23387. EXPECT_EQ(client.read(msg), ws::Text);
  23388. EXPECT_EQ(msg, "after timeout");
  23389. }
  23390. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23391. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23392. "/ws-echo");
  23393. client.set_read_timeout(1, 0);
  23394. ASSERT_TRUE(client.connect());
  23395. ASSERT_TRUE(client.send("first"));
  23396. std::string msg;
  23397. ASSERT_EQ(client.read(msg), ws::Text);
  23398. ASSERT_EQ(msg, "first");
  23399. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23400. // not be used with a read timeout: it would reprocess the previous message.
  23401. EXPECT_EQ(client.read(msg), ws::Timeout);
  23402. EXPECT_EQ(msg, "first");
  23403. }
  23404. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23405. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23406. "/ws-echo");
  23407. ASSERT_TRUE(client.connect());
  23408. // Setting it once the connection is open reaches the live stream, not just
  23409. // the seed for the next connect().
  23410. client.set_read_timeout(1, 0);
  23411. std::string msg;
  23412. EXPECT_EQ(client.read(msg), ws::Timeout);
  23413. EXPECT_TRUE(client.is_open());
  23414. }
  23415. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23416. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23417. "/ws-echo");
  23418. client.set_read_timeout(5, 0);
  23419. ASSERT_TRUE(client.connect());
  23420. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23421. // The server should reject it and close the connection.
  23422. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23423. client.send(oversized);
  23424. // The server's read() should have failed due to payload limit,
  23425. // so our read() should return false (connection closed).
  23426. std::string msg;
  23427. EXPECT_FALSE(client.read(msg));
  23428. }
  23429. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23430. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23431. "/ws-echo");
  23432. client.set_read_timeout(10, 0);
  23433. ASSERT_TRUE(client.connect());
  23434. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23435. // This should succeed.
  23436. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23437. ASSERT_TRUE(client.send(at_limit));
  23438. std::string msg;
  23439. ASSERT_TRUE(client.read(msg));
  23440. EXPECT_EQ(at_limit.size(), msg.size());
  23441. client.close();
  23442. }
  23443. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23444. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23445. "/nonexistent");
  23446. auto res = client.connect();
  23447. EXPECT_FALSE(res);
  23448. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23449. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23450. EXPECT_FALSE(client.is_open());
  23451. }
  23452. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23453. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23454. "/ws-echo");
  23455. ASSERT_TRUE(client.connect());
  23456. ASSERT_TRUE(client.send(""));
  23457. std::string msg;
  23458. EXPECT_EQ(ws::Text, client.read(msg));
  23459. EXPECT_EQ("", msg);
  23460. client.close();
  23461. }
  23462. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23463. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23464. "/ws-echo");
  23465. // First connection
  23466. ASSERT_TRUE(client.connect());
  23467. ASSERT_TRUE(client.send("first"));
  23468. std::string msg;
  23469. ASSERT_TRUE(client.read(msg));
  23470. EXPECT_EQ("first", msg);
  23471. client.close();
  23472. EXPECT_FALSE(client.is_open());
  23473. // Reconnect using the same client object
  23474. ASSERT_TRUE(client.connect());
  23475. ASSERT_TRUE(client.is_open());
  23476. ASSERT_TRUE(client.send("second"));
  23477. ASSERT_TRUE(client.read(msg));
  23478. EXPECT_EQ("second", msg);
  23479. client.close();
  23480. }
  23481. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23482. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23483. "/ws-close-status");
  23484. ASSERT_TRUE(client.connect());
  23485. // Trigger the server to close with GoingAway status
  23486. ASSERT_TRUE(client.send("trigger"));
  23487. // read() should return false after receiving the close frame
  23488. std::string msg;
  23489. EXPECT_FALSE(client.read(msg));
  23490. EXPECT_FALSE(client.is_open());
  23491. }
  23492. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23493. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23494. "/ws-echo");
  23495. ASSERT_TRUE(client.connect());
  23496. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23497. EXPECT_FALSE(client.is_open());
  23498. }
  23499. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23500. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23501. ws::WebSocketClient client(
  23502. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23503. ASSERT_TRUE(client.connect());
  23504. // Server should have selected graphql-ws
  23505. EXPECT_EQ("graphql-ws", client.subprotocol());
  23506. client.close();
  23507. }
  23508. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23509. Headers headers;
  23510. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23511. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23512. ws::WebSocketClient client(
  23513. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23514. ASSERT_TRUE(client.connect());
  23515. // The offer on the second field line counts too, so graphql-ws is selected
  23516. EXPECT_EQ("graphql-ws", client.subprotocol());
  23517. client.close();
  23518. }
  23519. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23520. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23521. ws::WebSocketClient client(
  23522. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23523. ASSERT_TRUE(client.connect());
  23524. // Server should not have selected any subprotocol
  23525. EXPECT_TRUE(client.subprotocol().empty());
  23526. client.close();
  23527. }
  23528. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23529. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23530. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23531. "/ws-subprotocol-unoffered",
  23532. headers);
  23533. ASSERT_TRUE(client.connect());
  23534. EXPECT_TRUE(client.subprotocol().empty());
  23535. client.close();
  23536. }
  23537. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23538. // Connect without requesting any subprotocol
  23539. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23540. "/ws-subprotocol");
  23541. ASSERT_TRUE(client.connect());
  23542. EXPECT_TRUE(client.subprotocol().empty());
  23543. client.close();
  23544. }
  23545. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23546. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23547. "/ws-echo");
  23548. client.set_tcp_nodelay(true);
  23549. client.set_connection_timeout(3, 0);
  23550. bool socket_options_called = false;
  23551. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23552. ASSERT_TRUE(client.connect());
  23553. ASSERT_TRUE(client.is_open());
  23554. EXPECT_TRUE(socket_options_called);
  23555. ASSERT_TRUE(client.send("hello"));
  23556. std::string msg;
  23557. auto result = client.read(msg);
  23558. EXPECT_EQ(result, ws::ReadResult::Text);
  23559. EXPECT_EQ(msg, "hello");
  23560. client.close();
  23561. }
  23562. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23563. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23564. "/ws-echo");
  23565. client.set_connection_timeout(std::chrono::seconds(3));
  23566. client.set_write_timeout(std::chrono::seconds(3));
  23567. // A sub-second remainder exercises the seconds/microseconds split.
  23568. client.set_read_timeout(std::chrono::milliseconds(1500));
  23569. ASSERT_TRUE(client.connect());
  23570. auto start = std::chrono::steady_clock::now();
  23571. std::string msg;
  23572. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23573. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23574. std::chrono::steady_clock::now() - start)
  23575. .count();
  23576. // Above 1s so that dropping the microseconds half of the split fails here.
  23577. // Ignoring the setter altogether would not reach this line at all: a client
  23578. // waits forever by default.
  23579. EXPECT_GE(elapsed, 1400);
  23580. EXPECT_LT(elapsed, 30000);
  23581. }
  23582. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23583. Server svr;
  23584. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23585. if (!req.has_header("Authorization")) {
  23586. res.status = StatusCode::Unauthorized_401;
  23587. res.set_content("Unauthorized", "text/plain");
  23588. return Server::HandlerResponse::Handled;
  23589. }
  23590. return Server::HandlerResponse::Unhandled;
  23591. });
  23592. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23593. std::string msg;
  23594. while (ws.read(msg)) {
  23595. ws.send(msg);
  23596. }
  23597. });
  23598. auto port = svr.bind_to_any_port("localhost");
  23599. std::thread t([&]() { svr.listen_after_bind(); });
  23600. svr.wait_until_ready();
  23601. // Without Authorization header - should be rejected before upgrade
  23602. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23603. EXPECT_FALSE(client1.connect());
  23604. // The rejection is framed like any other HTTP response
  23605. {
  23606. Client cli("localhost", port);
  23607. Headers headers = {{"Upgrade", "websocket"},
  23608. {"Connection", "Upgrade"},
  23609. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23610. {"Sec-WebSocket-Version", "13"}};
  23611. auto res = cli.Get("/ws", headers);
  23612. ASSERT_TRUE(res);
  23613. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23614. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23615. EXPECT_EQ("Unauthorized", res->body);
  23616. }
  23617. // With Authorization header - should succeed
  23618. Headers headers = {{"Authorization", "Bearer token123"}};
  23619. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23620. headers);
  23621. ASSERT_TRUE(client2.connect());
  23622. ASSERT_TRUE(client2.send("hello"));
  23623. std::string msg;
  23624. ASSERT_TRUE(client2.read(msg));
  23625. EXPECT_EQ("hello", msg);
  23626. client2.close();
  23627. svr.stop();
  23628. t.join();
  23629. }
  23630. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23631. Server svr;
  23632. std::atomic<int> pre_routing_calls{0};
  23633. std::atomic<int> pre_request_calls{0};
  23634. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23635. pre_routing_calls++;
  23636. if (req.path == "/handled") {
  23637. res.set_content("handled", "text/plain");
  23638. return Server::HandlerResponse::Handled;
  23639. }
  23640. return Server::HandlerResponse::Unhandled;
  23641. });
  23642. svr.set_pre_request_handler([&](const Request &, Response &) {
  23643. pre_request_calls++;
  23644. return Server::HandlerResponse::Unhandled;
  23645. });
  23646. svr.Get("/http", [](const Request &, Response &res) {
  23647. res.set_content("http", "text/plain");
  23648. });
  23649. svr.WebSocket("/ws",
  23650. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23651. auto port = svr.bind_to_any_port("localhost");
  23652. std::thread t([&]() { svr.listen_after_bind(); });
  23653. auto se = detail::scope_exit([&] {
  23654. svr.stop();
  23655. t.join();
  23656. });
  23657. svr.wait_until_ready();
  23658. Headers upgrade = {{"Upgrade", "websocket"},
  23659. {"Connection", "Upgrade"},
  23660. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23661. {"Sec-WebSocket-Version", "13"}};
  23662. auto get = [&](const char *path) {
  23663. pre_routing_calls = 0;
  23664. return Client("localhost", port).Get(path, upgrade);
  23665. };
  23666. // No WebSocket route, but an HTTP one
  23667. auto res = get("/http");
  23668. ASSERT_TRUE(res);
  23669. EXPECT_EQ(StatusCode::OK_200, res->status);
  23670. EXPECT_EQ("http", res->body);
  23671. EXPECT_EQ(1, pre_routing_calls);
  23672. EXPECT_EQ(1, pre_request_calls);
  23673. // No route at all
  23674. res = get("/none");
  23675. ASSERT_TRUE(res);
  23676. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23677. EXPECT_EQ(1, pre_routing_calls);
  23678. // Answered by the pre-routing handler
  23679. res = get("/handled");
  23680. ASSERT_TRUE(res);
  23681. EXPECT_EQ(StatusCode::OK_200, res->status);
  23682. EXPECT_EQ("handled", res->body);
  23683. EXPECT_EQ(1, pre_routing_calls);
  23684. // A WebSocket route
  23685. pre_routing_calls = 0;
  23686. pre_request_calls = 0;
  23687. {
  23688. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23689. "/ws");
  23690. ASSERT_TRUE(client.connect());
  23691. std::string msg;
  23692. ASSERT_TRUE(client.read(msg));
  23693. EXPECT_EQ("ws", msg);
  23694. client.close();
  23695. }
  23696. EXPECT_EQ(1, pre_routing_calls);
  23697. EXPECT_EQ(1, pre_request_calls);
  23698. }
  23699. // An upgrade request answered by a hook leaves its body unread, so that body
  23700. // must not be served as the next request on the connection.
  23701. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23702. Server svr;
  23703. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23704. if (req.path == "/pre-routing") {
  23705. res.set_content("pre-routing", "text/plain");
  23706. return Server::HandlerResponse::Handled;
  23707. }
  23708. return Server::HandlerResponse::Unhandled;
  23709. });
  23710. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23711. if (req.matched_route == "/pre-request") {
  23712. res.set_content("pre-request", "text/plain");
  23713. return Server::HandlerResponse::Handled;
  23714. }
  23715. return Server::HandlerResponse::Unhandled;
  23716. });
  23717. svr.Get("/smuggled", [](const Request &, Response &res) {
  23718. res.set_content("smuggled", "text/plain");
  23719. });
  23720. svr.WebSocket("/pre-request",
  23721. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23722. auto port = svr.bind_to_any_port(HOST);
  23723. std::thread t([&]() { svr.listen_after_bind(); });
  23724. auto se = detail::scope_exit([&] {
  23725. svr.stop();
  23726. t.join();
  23727. });
  23728. svr.wait_until_ready();
  23729. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23730. for (auto path : {"/pre-routing", "/pre-request"}) {
  23731. std::string req = std::string("GET ") + path +
  23732. " HTTP/1.1\r\n"
  23733. "Host: localhost\r\n"
  23734. "Upgrade: websocket\r\n"
  23735. "Connection: Upgrade\r\n"
  23736. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23737. "Sec-WebSocket-Version: 13\r\n"
  23738. "Content-Length: " +
  23739. std::to_string(body.size()) + "\r\n\r\n" + body;
  23740. std::string res;
  23741. ASSERT_TRUE(send_request(5, req, &res, port));
  23742. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23743. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23744. // Only one response, and the body was not served as a request
  23745. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23746. }
  23747. }
  23748. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23749. Server svr;
  23750. std::atomic<int> pre_request_calls{0};
  23751. std::atomic<bool> route_matched{false};
  23752. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23753. pre_request_calls++;
  23754. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23755. if (req.get_header_value("Authorization") != "Bearer token123") {
  23756. res.status = StatusCode::Unauthorized_401;
  23757. res.set_content("Unauthorized", "text/plain");
  23758. return Server::HandlerResponse::Handled;
  23759. }
  23760. return Server::HandlerResponse::Unhandled;
  23761. });
  23762. std::atomic<bool> handler_called{false};
  23763. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23764. handler_called = true;
  23765. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23766. });
  23767. auto port = svr.bind_to_any_port("localhost");
  23768. std::thread t([&]() { svr.listen_after_bind(); });
  23769. svr.wait_until_ready();
  23770. // Without Authorization header - should be rejected before upgrade
  23771. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23772. "/ws/1");
  23773. EXPECT_FALSE(client1.connect());
  23774. EXPECT_FALSE(handler_called);
  23775. EXPECT_EQ(1, pre_request_calls);
  23776. EXPECT_TRUE(route_matched);
  23777. // The rejection is an ordinary HTTP response, not a protocol switch
  23778. {
  23779. Client cli("localhost", port);
  23780. Headers headers = {{"Upgrade", "websocket"},
  23781. {"Connection", "Upgrade"},
  23782. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23783. {"Sec-WebSocket-Version", "13"}};
  23784. auto res = cli.Get("/ws/1", headers);
  23785. ASSERT_TRUE(res);
  23786. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23787. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23788. EXPECT_EQ("Unauthorized", res->body);
  23789. }
  23790. EXPECT_FALSE(handler_called);
  23791. // With Authorization header - should succeed
  23792. Headers headers = {{"Authorization", "Bearer token123"}};
  23793. ws::WebSocketClient client2(
  23794. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23795. ASSERT_TRUE(client2.connect());
  23796. std::string msg;
  23797. ASSERT_TRUE(client2.read(msg));
  23798. EXPECT_EQ("/ws/:id 2", msg);
  23799. EXPECT_TRUE(handler_called);
  23800. client2.close();
  23801. svr.stop();
  23802. t.join();
  23803. }
  23804. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23805. Server svr;
  23806. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23807. // A read timeout is how a handler gets control back. Without it, a handler
  23808. // parked in read() can never write on the connection it is reading.
  23809. ws.set_read_timeout(std::chrono::milliseconds(100));
  23810. std::string msg;
  23811. while (ws.is_open()) {
  23812. auto r = ws.read(msg);
  23813. if (r == httplib::ws::Timeout) {
  23814. ws.send("tick");
  23815. continue;
  23816. }
  23817. if (r == httplib::ws::Fail) { break; }
  23818. ws.send(msg);
  23819. }
  23820. });
  23821. auto port = svr.bind_to_any_port("localhost");
  23822. std::thread t([&]() { svr.listen_after_bind(); });
  23823. svr.wait_until_ready();
  23824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23825. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23826. ASSERT_TRUE(client.connect());
  23827. // The client sends nothing, so anything it receives came out of the
  23828. // handler's timeout path.
  23829. std::string msg;
  23830. ASSERT_EQ(client.read(msg), ws::Text);
  23831. EXPECT_EQ("tick", msg);
  23832. client.close();
  23833. svr.stop();
  23834. t.join();
  23835. }
  23836. // Stream::read may return fewer bytes than asked for. This is that contract at
  23837. // its worst -- one byte per call -- which is what a frame header straddling a
  23838. // read buffer's boundary looks like to the frame parser.
  23839. class WsByteAtATimeStream : public Stream {
  23840. public:
  23841. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23842. bool is_readable() const override { return true; }
  23843. bool wait_readable() const override { return true; }
  23844. bool wait_writable() const override { return true; }
  23845. ssize_t read(char *ptr, size_t size) override {
  23846. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23847. *ptr = data_[pos_++];
  23848. return 1;
  23849. }
  23850. ssize_t write(const char *, size_t size) override {
  23851. return static_cast<ssize_t>(size);
  23852. }
  23853. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23854. ip = "127.0.0.1";
  23855. port = 0;
  23856. }
  23857. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23858. ip = "127.0.0.1";
  23859. port = 0;
  23860. }
  23861. socket_t socket() const override { return INVALID_SOCKET; }
  23862. time_t duration() const override { return 0; }
  23863. private:
  23864. std::string data_;
  23865. size_t pos_ = 0;
  23866. };
  23867. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23868. // The payload uses the 16-bit extended length, so the header, the length
  23869. // and the mask key are all multi-byte fields here. Each used to be read
  23870. // with a single read() call, which fails as soon as one is split. The
  23871. // payload is also a little over one read chunk, so it is read in two.
  23872. std::string body;
  23873. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23874. body += static_cast<char>(i % 251);
  23875. }
  23876. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23877. std::string frame;
  23878. frame += static_cast<char>(0x81); // FIN + Text
  23879. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23880. frame += static_cast<char>(body.size() >> 8);
  23881. frame += static_cast<char>(body.size() & 0xff);
  23882. for (size_t i = 0; i < 4; i++) {
  23883. frame += static_cast<char>(mask[i]);
  23884. }
  23885. for (size_t i = 0; i < body.size(); i++) {
  23886. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23887. }
  23888. WsByteAtATimeStream strm(frame);
  23889. ws::Opcode opcode;
  23890. std::string payload;
  23891. bool fin = false;
  23892. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23893. /*expect_masked=*/true, body.size()),
  23894. ws::impl::FrameRead::Ok);
  23895. EXPECT_TRUE(fin);
  23896. EXPECT_EQ(opcode, ws::Opcode::Text);
  23897. EXPECT_EQ(payload, body);
  23898. }
  23899. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23900. std::string body(2000, 'x');
  23901. std::string frame;
  23902. frame += static_cast<char>(0x82); // FIN + Binary
  23903. frame += static_cast<char>(126); // 16-bit length follows
  23904. frame += static_cast<char>(body.size() >> 8);
  23905. frame += static_cast<char>(body.size() & 0xff);
  23906. frame += body;
  23907. detail::BufferStream strm;
  23908. strm.write(frame.data(), frame.size());
  23909. ws::Opcode opcode;
  23910. std::string payload;
  23911. bool fin;
  23912. EXPECT_EQ(
  23913. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23914. ws::impl::FrameRead::Ok);
  23915. EXPECT_EQ(body, payload);
  23916. }
  23917. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23918. // The header announces the largest payload allowed, and only 3 bytes of it
  23919. // ever arrive.
  23920. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23921. std::string frame;
  23922. frame += static_cast<char>(0x82); // FIN + Binary
  23923. frame += static_cast<char>(127); // 64-bit length follows
  23924. for (int shift = 56; shift >= 0; shift -= 8) {
  23925. frame += static_cast<char>((len >> shift) & 0xff);
  23926. }
  23927. frame += "abc";
  23928. detail::BufferStream strm;
  23929. strm.write(frame.data(), frame.size());
  23930. ws::Opcode opcode;
  23931. std::string payload;
  23932. bool fin;
  23933. EXPECT_EQ(
  23934. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23935. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23936. ws::impl::FrameRead::Fail);
  23937. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23938. }
  23939. TEST(WebSocketTest, QueryStringInHandshake) {
  23940. Server svr;
  23941. std::mutex mtx;
  23942. std::string received_target;
  23943. std::string received_token;
  23944. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23945. {
  23946. std::lock_guard<std::mutex> lock(mtx);
  23947. received_target = req.target;
  23948. if (req.has_param("token")) {
  23949. received_token = req.get_param_value("token");
  23950. }
  23951. }
  23952. std::string msg;
  23953. while (ws.read(msg)) {
  23954. ws.send(msg);
  23955. }
  23956. });
  23957. auto port = svr.bind_to_any_port("localhost");
  23958. std::thread t([&]() { svr.listen_after_bind(); });
  23959. svr.wait_until_ready();
  23960. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23961. "/ws?token=ABC&session=123");
  23962. ASSERT_TRUE(client.connect());
  23963. // Round-trip ensures the handler has run and captured the request.
  23964. ASSERT_TRUE(client.send("hello"));
  23965. std::string msg;
  23966. ASSERT_TRUE(client.read(msg));
  23967. EXPECT_EQ("hello", msg);
  23968. client.close();
  23969. {
  23970. std::lock_guard<std::mutex> lock(mtx);
  23971. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23972. EXPECT_EQ("ABC", received_token);
  23973. }
  23974. svr.stop();
  23975. t.join();
  23976. }
  23977. // Run a handshake against a throwaway server and hand the request the server
  23978. // received back to the caller, so tests can assert on the headers the client
  23979. // actually put on the wire.
  23980. static void capture_websocket_handshake_request(
  23981. const Headers &client_headers,
  23982. std::function<void(const Request &, int port)> verify) {
  23983. Server svr;
  23984. std::mutex mtx;
  23985. Request received;
  23986. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23987. {
  23988. std::lock_guard<std::mutex> lock(mtx);
  23989. received = req;
  23990. }
  23991. std::string msg;
  23992. while (ws.read(msg)) {
  23993. ws.send(msg);
  23994. }
  23995. });
  23996. auto port = svr.bind_to_any_port("localhost");
  23997. std::thread t([&]() { svr.listen_after_bind(); });
  23998. auto se = detail::scope_exit([&] {
  23999. svr.stop();
  24000. t.join();
  24001. });
  24002. svr.wait_until_ready();
  24003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24004. client_headers);
  24005. ASSERT_TRUE(client.connect());
  24006. ASSERT_TRUE(client.send("hello"));
  24007. std::string msg;
  24008. ASSERT_TRUE(client.read(msg));
  24009. client.close();
  24010. {
  24011. std::lock_guard<std::mutex> lock(mtx);
  24012. verify(received, port);
  24013. }
  24014. }
  24015. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24016. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24017. // Non-default port must be present in the Host header. Default ports
  24018. // (80/443) are omitted; that logic is covered by
  24019. // MakeHostAndPortStringTest.
  24020. EXPECT_EQ("localhost:" + std::to_string(port),
  24021. req.get_header_value("Host"));
  24022. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24023. req.get_header_value("User-Agent"));
  24024. EXPECT_FALSE(req.has_header("Accept"));
  24025. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24026. EXPECT_FALSE(req.has_header("Content-Length"));
  24027. });
  24028. }
  24029. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24030. capture_websocket_handshake_request(
  24031. {{"Host", "example.com"},
  24032. {"User-Agent", "custom-agent"},
  24033. {"X-Custom", "value"}},
  24034. [](const Request &req, int) {
  24035. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24036. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24037. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24038. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24039. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24040. });
  24041. }
  24042. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24043. capture_websocket_handshake_request(
  24044. {{"Upgrade", "bogus"},
  24045. {"Connection", "close"},
  24046. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24047. {"Sec-WebSocket-Version", "8"}},
  24048. [](const Request &req, int) {
  24049. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24050. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24051. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24052. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24053. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24054. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24055. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24056. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24057. req.get_header_value("Sec-WebSocket-Key"));
  24058. });
  24059. }
  24060. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24061. // A header the client refuses to send must abort the handshake before any
  24062. // part of it reaches the wire; a lone request line would otherwise sit in
  24063. // the peer's buffer as a truncated request.
  24064. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24065. ASSERT_NE(INVALID_SOCKET, srv);
  24066. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24067. sockaddr_in addr{};
  24068. addr.sin_family = AF_INET;
  24069. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24070. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24071. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24072. ASSERT_EQ(0, ::listen(srv, 1));
  24073. sockaddr_in bound{};
  24074. socklen_t bound_len = sizeof(bound);
  24075. ASSERT_EQ(
  24076. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24077. auto port = ntohs(bound.sin_port);
  24078. ssize_t received = -1;
  24079. std::thread t([&] {
  24080. // Bound every blocking call so a regression fails the test with a bad
  24081. // value instead of hanging the suite.
  24082. fd_set rfds;
  24083. FD_ZERO(&rfds);
  24084. FD_SET(srv, &rfds);
  24085. timeval tv{5, 0};
  24086. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24087. 0) {
  24088. return;
  24089. }
  24090. sockaddr_in cli_addr{};
  24091. socklen_t cli_len = sizeof(cli_addr);
  24092. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24093. if (cli == INVALID_SOCKET) { return; }
  24094. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24095. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24096. char buf[4096];
  24097. received = ::recv(cli, buf, sizeof(buf), 0);
  24098. });
  24099. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24100. // connect() has already shut the socket down by the time it returns false,
  24101. // so the peer sees EOF without waiting for the client to be destroyed.
  24102. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24103. {{"X-Bad", "a\r\nInjected: 1"}});
  24104. EXPECT_FALSE(client.connect());
  24105. t.join();
  24106. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24107. EXPECT_EQ(0, received);
  24108. }
  24109. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24110. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24111. // contains "upgrade" as a substring is a different token and must not
  24112. // start a WebSocket handshake.
  24113. auto make_request = [](const std::vector<std::string> &connection_values) {
  24114. Request req;
  24115. req.method = "GET";
  24116. req.headers.emplace("Upgrade", "websocket");
  24117. for (const auto &value : connection_values) {
  24118. req.headers.emplace("Connection", value);
  24119. }
  24120. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24121. req.headers.emplace("Sec-WebSocket-Version", "13");
  24122. return req;
  24123. };
  24124. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24125. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24126. EXPECT_TRUE(
  24127. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24128. EXPECT_TRUE(
  24129. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24130. EXPECT_TRUE(
  24131. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24132. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24133. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24134. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24135. EXPECT_FALSE(
  24136. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24137. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24138. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24139. }
  24140. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24141. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24142. // asks recipients to match each protocol-name case-insensitively, and RFC
  24143. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24144. // client naming websocket alongside another protocol, or on a second field
  24145. // line, is offering websocket; a value that merely contains "websocket" as a
  24146. // substring is a different protocol name and is not.
  24147. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24148. Request req;
  24149. req.method = "GET";
  24150. for (const auto &value : upgrade_values) {
  24151. req.headers.emplace("Upgrade", value);
  24152. }
  24153. req.headers.emplace("Connection", "Upgrade");
  24154. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24155. req.headers.emplace("Sec-WebSocket-Version", "13");
  24156. return req;
  24157. };
  24158. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24159. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24160. EXPECT_TRUE(
  24161. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24162. EXPECT_TRUE(
  24163. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24164. EXPECT_TRUE(
  24165. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24166. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24167. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24168. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24169. EXPECT_FALSE(
  24170. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24171. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24172. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24173. }
  24174. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24175. Server svr;
  24176. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24177. auto port = svr.bind_to_any_port("localhost");
  24178. std::thread t([&]() { svr.listen_after_bind(); });
  24179. auto se = detail::scope_exit([&] {
  24180. svr.stop();
  24181. t.join();
  24182. });
  24183. svr.wait_until_ready();
  24184. Headers headers = {{"Upgrade", "websocket"},
  24185. {"Connection", "notupgrade"},
  24186. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24187. {"Sec-WebSocket-Version", "13"}};
  24188. Client cli("localhost", port);
  24189. auto res = cli.Get("/ws", headers);
  24190. // The route exists only as a WebSocket route, so a request that fails the
  24191. // handshake check falls through to ordinary routing.
  24192. ASSERT_TRUE(res);
  24193. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24194. }
  24195. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24196. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24197. // Connection value is the only thing left for the client to reject.
  24198. Server svr;
  24199. svr.Get("/ws", [](const Request &req, Response &res) {
  24200. res.status = StatusCode::SwitchingProtocol_101;
  24201. res.set_header("Upgrade", "websocket");
  24202. res.set_header("Connection", "notupgrade");
  24203. res.set_header("Sec-WebSocket-Accept",
  24204. detail::websocket_accept_key(
  24205. req.get_header_value("Sec-WebSocket-Key")));
  24206. });
  24207. auto port = svr.bind_to_any_port("localhost");
  24208. std::thread t([&]() { svr.listen_after_bind(); });
  24209. auto se = detail::scope_exit([&] {
  24210. svr.stop();
  24211. t.join();
  24212. });
  24213. svr.wait_until_ready();
  24214. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24215. auto res = client.connect();
  24216. EXPECT_FALSE(res);
  24217. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24218. EXPECT_FALSE(client.is_open());
  24219. }
  24220. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24221. Server svr;
  24222. svr.Get("/ws", [](const Request &req, Response &res) {
  24223. res.status = StatusCode::SwitchingProtocol_101;
  24224. res.set_header("Upgrade", "websocket");
  24225. res.set_header("Connection", "Upgrade");
  24226. res.set_header("Sec-WebSocket-Accept",
  24227. detail::websocket_accept_key(
  24228. req.get_header_value("Sec-WebSocket-Key")));
  24229. res.set_header("Sec-WebSocket-Protocol", "admin");
  24230. });
  24231. auto port = svr.bind_to_any_port("localhost");
  24232. std::thread t([&]() { svr.listen_after_bind(); });
  24233. auto se = detail::scope_exit([&] {
  24234. svr.stop();
  24235. t.join();
  24236. });
  24237. svr.wait_until_ready();
  24238. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24239. // Server selects a subprotocol the client never offered
  24240. {
  24241. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24242. ws::WebSocketClient client(url, headers);
  24243. auto res = client.connect();
  24244. EXPECT_FALSE(res);
  24245. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24246. EXPECT_FALSE(client.is_open());
  24247. EXPECT_TRUE(client.subprotocol().empty());
  24248. }
  24249. // Client offered none but the server named one anyway
  24250. {
  24251. ws::WebSocketClient client(url);
  24252. auto res = client.connect();
  24253. EXPECT_FALSE(res);
  24254. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24255. EXPECT_FALSE(client.is_open());
  24256. EXPECT_TRUE(client.subprotocol().empty());
  24257. }
  24258. }
  24259. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24260. // The socket path doubles as the URL host, so it must not contain '/'.
  24261. const char *shard = getenv("GTEST_SHARD_INDEX");
  24262. const std::string sock_path =
  24263. shard ? std::string("httplib-ws-") + shard + ".sock"
  24264. : std::string("httplib-ws.sock");
  24265. std::remove(sock_path.c_str());
  24266. Server svr;
  24267. std::mutex mtx;
  24268. std::string received_host;
  24269. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24270. {
  24271. std::lock_guard<std::mutex> lock(mtx);
  24272. received_host = req.get_header_value("Host");
  24273. }
  24274. std::string msg;
  24275. while (ws.read(msg)) {
  24276. ws.send(msg);
  24277. }
  24278. });
  24279. svr.set_address_family(AF_UNIX);
  24280. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24281. auto se = detail::scope_exit([&] {
  24282. svr.stop();
  24283. t.join();
  24284. std::remove(sock_path.c_str());
  24285. });
  24286. svr.wait_until_ready();
  24287. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24288. client.set_address_family(AF_UNIX);
  24289. ASSERT_TRUE(client.connect());
  24290. ASSERT_TRUE(client.send("hello"));
  24291. std::string msg;
  24292. ASSERT_TRUE(client.read(msg));
  24293. client.close();
  24294. {
  24295. std::lock_guard<std::mutex> lock(mtx);
  24296. // There is no host:port for a Unix socket, so the same "localhost"
  24297. // placeholder the HTTP client uses is expected.
  24298. EXPECT_EQ("localhost", received_host);
  24299. }
  24300. }
  24301. // Two threads must never parse WebSocket frames from the same stream.
  24302. // close() used to read the peer's Close reply with its own frame read, so it
  24303. // raced a reader thread that was in the middle of a payload: the payload loop
  24304. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24305. // so bytes taken by close() were replaced with bytes from further along the
  24306. // stream. The message kept its length and silently changed content.
  24307. //
  24308. // The raw peer below sends a frame header plus part of the payload, waits for
  24309. // the handler to call close(), and only then sends the rest. Whichever thread
  24310. // would win the race for those bytes, the message must arrive intact, because
  24311. // close() must not touch the stream while read() owns it.
  24312. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24313. #ifndef _WIN32
  24314. signal(SIGPIPE, SIG_IGN);
  24315. #endif
  24316. const size_t payload_len = 120; // fits the 7-bit length field
  24317. const size_t prefix_len = 8;
  24318. const int attempts = 8;
  24319. std::string expected(payload_len, '\0');
  24320. for (size_t i = 0; i < payload_len; i++) {
  24321. expected[i] = static_cast<char>('a' + i % 26);
  24322. }
  24323. std::atomic<bool> peer_stalled{false};
  24324. std::atomic<bool> handler_done{false};
  24325. std::mutex received_mutex;
  24326. std::vector<std::string> received;
  24327. // Bound every wait, so a regression fails the test instead of hanging the
  24328. // suite.
  24329. auto wait_for = [](const std::atomic<bool> &flag) {
  24330. for (int i = 0; i < 500 && !flag; i++) {
  24331. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24332. }
  24333. };
  24334. Server svr;
  24335. svr.set_websocket_ping_interval(0);
  24336. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24337. std::thread reader([&]() {
  24338. std::string msg;
  24339. while (ws.read(msg)) {
  24340. std::lock_guard<std::mutex> guard(received_mutex);
  24341. received.push_back(msg);
  24342. }
  24343. });
  24344. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24345. // inside read_websocket_frame() when close() runs.
  24346. wait_for(peer_stalled);
  24347. ws.close();
  24348. reader.join();
  24349. handler_done = true;
  24350. });
  24351. auto port = svr.bind_to_any_port("127.0.0.1");
  24352. std::thread t([&]() { svr.listen_after_bind(); });
  24353. auto se = detail::scope_exit([&] {
  24354. svr.stop();
  24355. t.join();
  24356. });
  24357. svr.wait_until_ready();
  24358. auto send_bytes = [](socket_t s, const std::string &data) {
  24359. #ifdef _WIN32
  24360. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24361. #else
  24362. auto n = ::send(s, data.data(), data.size(), 0);
  24363. #endif
  24364. return n == static_cast<decltype(n)>(data.size());
  24365. };
  24366. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24367. // Every length used here fits the 7-bit length field.
  24368. auto masked_header = [](uint8_t first_byte, size_t len) {
  24369. std::string h;
  24370. h += static_cast<char>(first_byte);
  24371. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24372. h.append(4, '\0'); // mask key
  24373. return h;
  24374. };
  24375. for (int attempt = 0; attempt < attempts; attempt++) {
  24376. peer_stalled = false;
  24377. handler_done = false;
  24378. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24379. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24380. auto se_sock = detail::scope_exit([&] {
  24381. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24382. });
  24383. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24384. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24385. sockaddr_in addr{};
  24386. addr.sin_family = AF_INET;
  24387. addr.sin_port = htons(static_cast<uint16_t>(port));
  24388. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24389. ASSERT_EQ(
  24390. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24391. << "attempt " << attempt;
  24392. ASSERT_TRUE(send_bytes(sock,
  24393. "GET /ws HTTP/1.1\r\n"
  24394. "Host: 127.0.0.1\r\n"
  24395. "Upgrade: websocket\r\n"
  24396. "Connection: Upgrade\r\n"
  24397. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24398. "Sec-WebSocket-Version: 13\r\n"
  24399. "\r\n"))
  24400. << "attempt " << attempt;
  24401. std::string response;
  24402. while (response.find("\r\n\r\n") == std::string::npos) {
  24403. char buf[512];
  24404. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24405. if (n <= 0) { break; }
  24406. response.append(buf, static_cast<size_t>(n));
  24407. }
  24408. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24409. << "attempt " << attempt;
  24410. // Send the header of a Binary message but only the first prefix_len bytes
  24411. // of its payload, leaving the reader thread stalled inside the payload.
  24412. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24413. expected.substr(0, prefix_len)))
  24414. << "attempt " << attempt;
  24415. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24416. peer_stalled = true;
  24417. // Let close() send its Close frame and park in its own read before the
  24418. // rest of the payload arrives, so both threads are waiting for it.
  24419. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24420. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24421. close_frame += static_cast<char>(0x03); // status 1000
  24422. close_frame += static_cast<char>(0xE8);
  24423. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24424. << "attempt " << attempt;
  24425. // Closing the peer releases the reader thread even on the buggy path,
  24426. // where it waits for bytes another thread already consumed.
  24427. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24428. detail::close_socket(sock);
  24429. sock = INVALID_SOCKET;
  24430. wait_for(handler_done);
  24431. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24432. }
  24433. std::lock_guard<std::mutex> guard(received_mutex);
  24434. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24435. << "a message in flight when close() ran was dropped";
  24436. for (size_t i = 0; i < received.size(); i++) {
  24437. EXPECT_EQ(expected, received[i]) << "message " << i;
  24438. }
  24439. }
  24440. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24441. // returning the socket, or INVALID_SOCKET.
  24442. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24443. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24444. if (sock == INVALID_SOCKET) { return sock; }
  24445. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24446. sockaddr_in addr{};
  24447. addr.sin_family = AF_INET;
  24448. addr.sin_port = htons(static_cast<uint16_t>(port));
  24449. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24450. std::string req = "GET " + path +
  24451. " HTTP/1.1\r\n"
  24452. "Host: 127.0.0.1\r\n"
  24453. "Upgrade: websocket\r\n"
  24454. "Connection: Upgrade\r\n"
  24455. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24456. "Sec-WebSocket-Version: 13\r\n"
  24457. "\r\n";
  24458. std::string res;
  24459. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24460. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24461. static_cast<ssize_t>(req.size())) {
  24462. char c;
  24463. while (res.find("\r\n\r\n") == std::string::npos &&
  24464. ::recv(sock, &c, 1, 0) == 1) {
  24465. res += c;
  24466. }
  24467. }
  24468. if (res.find(" 101 ") == std::string::npos) {
  24469. detail::close_socket(sock);
  24470. return INVALID_SOCKET;
  24471. }
  24472. return sock;
  24473. }
  24474. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24475. // The payload must fit the 7-bit length field.
  24476. static std::string masked_frame(uint8_t first_byte,
  24477. const std::string &payload) {
  24478. std::string f;
  24479. f += static_cast<char>(first_byte);
  24480. f += static_cast<char>(0x80 | payload.size());
  24481. f.append(4, '\0');
  24482. return f + payload;
  24483. }
  24484. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24485. std::atomic<bool> done{false};
  24486. std::string received;
  24487. Server svr;
  24488. svr.set_websocket_ping_interval(0);
  24489. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24490. std::string msg;
  24491. if (ws.read(msg) == ws::Binary) { received = msg; }
  24492. done = true;
  24493. });
  24494. auto port = svr.bind_to_any_port("127.0.0.1");
  24495. std::thread t([&]() { svr.listen_after_bind(); });
  24496. auto se = detail::scope_exit([&] {
  24497. svr.stop();
  24498. t.join();
  24499. });
  24500. svr.wait_until_ready();
  24501. auto sock = connect_raw_websocket(port, "/ws");
  24502. ASSERT_NE(INVALID_SOCKET, sock);
  24503. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24504. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24505. masked_frame(0x89, "p") + // FIN + Ping
  24506. masked_frame(0x80, "lo"); // FIN + Continuation
  24507. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24508. for (int i = 0; i < 500 && !done; i++) {
  24509. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24510. }
  24511. ASSERT_TRUE(done);
  24512. EXPECT_EQ("Hello", received);
  24513. // The Ping between the fragments is answered with a Pong.
  24514. char pong[3];
  24515. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24516. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24517. }
  24518. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24519. Server svr;
  24520. svr.set_websocket_ping_interval(-1);
  24521. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24522. std::string msg;
  24523. while (ws.read(msg)) {}
  24524. });
  24525. auto port = svr.bind_to_any_port("127.0.0.1");
  24526. std::thread t([&]() { svr.listen_after_bind(); });
  24527. auto se = detail::scope_exit([&] {
  24528. svr.stop();
  24529. t.join();
  24530. });
  24531. svr.wait_until_ready();
  24532. auto sock = connect_raw_websocket(port, "/ws");
  24533. ASSERT_NE(INVALID_SOCKET, sock);
  24534. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24535. // Nothing comes while the client stays quiet.
  24536. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24537. char c;
  24538. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24539. }
  24540. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24541. // and that has to end a read() already waiting on the peer, on every platform.
  24542. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24543. // The peer sends no pings, and its handler never calls read(), which is
  24544. // where pongs are written.
  24545. std::mutex mutex;
  24546. std::condition_variable cv;
  24547. auto release = false;
  24548. svr.set_websocket_ping_interval(0);
  24549. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24550. std::unique_lock<std::mutex> lock(mutex);
  24551. cv.wait(lock, [&] { return release; });
  24552. });
  24553. auto port = svr.bind_to_any_port(HOST);
  24554. std::thread t([&]() { svr.listen_after_bind(); });
  24555. auto se = detail::scope_exit([&] {
  24556. {
  24557. std::lock_guard<std::mutex> lock(mutex);
  24558. release = true;
  24559. }
  24560. cv.notify_all();
  24561. svr.stop();
  24562. t.join();
  24563. });
  24564. svr.wait_until_ready();
  24565. ws::WebSocketClient client(std::string(scheme) +
  24566. "://localhost:" + std::to_string(port) + "/ws");
  24567. #ifdef CPPHTTPLIB_SSL_ENABLED
  24568. client.enable_server_certificate_verification(false);
  24569. #endif
  24570. // A ping a second, given up on after two go unanswered: about 3s
  24571. client.set_websocket_ping_interval(1);
  24572. client.set_websocket_max_missed_pongs(2);
  24573. // Well past that, so that a read the timeout ends instead stands out
  24574. client.set_read_timeout(10);
  24575. ASSERT_TRUE(client.connect());
  24576. auto start = std::chrono::steady_clock::now();
  24577. std::string msg;
  24578. EXPECT_EQ(ws::Fail, client.read(msg));
  24579. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24580. std::chrono::steady_clock::now() - start)
  24581. .count(),
  24582. 6000);
  24583. EXPECT_FALSE(client.is_open());
  24584. }
  24585. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24586. Server svr;
  24587. check_pong_timeout_ends_read(svr, "ws");
  24588. }
  24589. #ifdef CPPHTTPLIB_SSL_ENABLED
  24590. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24592. ASSERT_TRUE(svr.is_valid());
  24593. check_pong_timeout_ends_read(svr, "wss");
  24594. }
  24595. #endif
  24596. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24597. Server svr;
  24598. svr.set_websocket_ping_interval(0);
  24599. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24600. std::string msg;
  24601. while (ws.read(msg)) {}
  24602. });
  24603. auto port = svr.bind_to_any_port("127.0.0.1");
  24604. std::thread t([&]() { svr.listen_after_bind(); });
  24605. auto se = detail::scope_exit([&] {
  24606. svr.stop();
  24607. t.join();
  24608. });
  24609. svr.wait_until_ready();
  24610. // Each Close payload and the reply it should get: an echo when valid, 1002
  24611. // otherwise.
  24612. std::vector<std::pair<std::string, std::string>> cases = {
  24613. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24614. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24615. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24616. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24617. };
  24618. // Also between the fragments of a message.
  24619. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24620. for (const auto &c : cases) {
  24621. auto sock = connect_raw_websocket(port, "/ws");
  24622. ASSERT_NE(INVALID_SOCKET, sock);
  24623. auto frames = prefix + masked_frame(0x88, c.first);
  24624. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24625. std::string reply;
  24626. char buf[256];
  24627. while (reply.size() < 2 + c.second.size()) {
  24628. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24629. if (n <= 0) { break; }
  24630. reply.append(buf, static_cast<size_t>(n));
  24631. }
  24632. detail::close_socket(sock);
  24633. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24634. c.second,
  24635. reply);
  24636. }
  24637. }
  24638. }
  24639. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24640. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24641. protected:
  24642. void SetUp() override {
  24643. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24644. SERVER_PRIVATE_KEY_FILE);
  24645. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24646. std::string msg;
  24647. ws::ReadResult ret;
  24648. while ((ret = ws.read(msg))) {
  24649. if (ret == ws::Binary) {
  24650. ws.send(msg.data(), msg.size());
  24651. } else {
  24652. ws.send(msg);
  24653. }
  24654. }
  24655. });
  24656. port_ = server_->bind_to_any_port(HOST);
  24657. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24658. server_->wait_until_ready();
  24659. }
  24660. void TearDown() override {
  24661. server_->stop();
  24662. if (server_thread_.joinable()) { server_thread_.join(); }
  24663. }
  24664. std::unique_ptr<SSLServer> server_;
  24665. std::thread server_thread_;
  24666. int port_ = 0;
  24667. };
  24668. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24669. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24670. {
  24671. ws::WebSocketClient client(url);
  24672. client.enable_server_certificate_verification(false);
  24673. auto calls = 0;
  24674. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24675. calls++;
  24676. return false;
  24677. });
  24678. EXPECT_FALSE(client.connect());
  24679. EXPECT_GT(calls, 0);
  24680. }
  24681. {
  24682. ws::WebSocketClient client(url);
  24683. client.enable_server_certificate_verification(false);
  24684. client.set_session_verifier([](tls::session_t) {
  24685. return SSLVerifierResponse::CertificateRejected;
  24686. });
  24687. EXPECT_FALSE(client.connect());
  24688. }
  24689. {
  24690. ws::WebSocketClient client(url);
  24691. client.enable_server_certificate_verification(false);
  24692. client.set_session_verifier([](tls::session_t) {
  24693. return SSLVerifierResponse::CertificateAccepted;
  24694. });
  24695. EXPECT_TRUE(client.connect());
  24696. }
  24697. }
  24698. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24699. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24700. "/ws-echo");
  24701. client.enable_server_certificate_verification(false);
  24702. ASSERT_TRUE(client.connect());
  24703. ASSERT_TRUE(client.is_open());
  24704. ASSERT_TRUE(client.send("Hello WSS"));
  24705. std::string msg;
  24706. EXPECT_EQ(ws::Text, client.read(msg));
  24707. EXPECT_EQ("Hello WSS", msg);
  24708. client.close();
  24709. }
  24710. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24711. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24712. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24713. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24714. // client (without calling close() first) is the only path that runs
  24715. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24716. // bug exactly.
  24717. //
  24718. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24719. // when linked against an instrumented libssl; run under Valgrind to catch it
  24720. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24721. // suite (the freed session otherwise stalls on the close handshake) — this test
  24722. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24723. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24724. {
  24725. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24726. "/ws-echo");
  24727. client.enable_server_certificate_verification(false);
  24728. client.set_read_timeout(2, 0);
  24729. client.set_write_timeout(2, 0);
  24730. ASSERT_TRUE(client.connect());
  24731. ASSERT_TRUE(client.is_open());
  24732. ASSERT_TRUE(client.send("still open"));
  24733. // Intentionally do NOT call client.close(): leaving scope runs
  24734. // shutdown_and_close() with the WebSocket still open, which must send the
  24735. // close frame while the TLS session is still alive.
  24736. }
  24737. }
  24738. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24739. // shutdown_and_close() at the start of connect(), reproducing the same
  24740. // use-after-free within the test body rather than at scope exit. The second
  24741. // connect must succeed and echo, proving the close handshake ran over a live
  24742. // session. See the note above about memory-tool requirements.
  24743. TEST_F(WebSocketSSLIntegrationTest,
  24744. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24745. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24746. "/ws-echo");
  24747. client.enable_server_certificate_verification(false);
  24748. client.set_read_timeout(2, 0);
  24749. client.set_write_timeout(2, 0);
  24750. ASSERT_TRUE(client.connect());
  24751. ASSERT_TRUE(client.is_open());
  24752. ASSERT_TRUE(client.send("still open"));
  24753. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24754. // the still-open connection, which must not touch a freed TLS session.
  24755. ASSERT_TRUE(client.connect());
  24756. ASSERT_TRUE(client.is_open());
  24757. ASSERT_TRUE(client.send("after reconnect"));
  24758. std::string msg;
  24759. EXPECT_EQ(ws::Text, client.read(msg));
  24760. EXPECT_EQ("after reconnect", msg);
  24761. client.close();
  24762. }
  24763. #endif
  24764. #ifdef CPPHTTPLIB_SSL_ENABLED
  24765. class WebSocketSSLCATest : public ::testing::Test {
  24766. protected:
  24767. void SetUp() override {
  24768. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24769. SERVER_PRIVATE_KEY_FILE);
  24770. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24771. std::string msg;
  24772. while (ws.read(msg)) {
  24773. ws.send(msg);
  24774. }
  24775. });
  24776. port_ = server_->bind_to_any_port("127.0.0.1");
  24777. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24778. server_->wait_until_ready();
  24779. }
  24780. void TearDown() override {
  24781. server_->stop();
  24782. if (server_thread_.joinable()) { server_thread_.join(); }
  24783. }
  24784. std::string url() const {
  24785. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24786. }
  24787. std::unique_ptr<SSLServer> server_;
  24788. std::thread server_thread_;
  24789. int port_ = 0;
  24790. };
  24791. // A custom CA loaded as PEM verifies the server with full certificate
  24792. // verification enabled
  24793. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24794. ws::WebSocketClient client(url());
  24795. std::string cert;
  24796. read_file(SERVER_CERT2_FILE, cert);
  24797. client.load_ca_cert_store(cert.c_str(), cert.size());
  24798. ASSERT_TRUE(client.connect());
  24799. ASSERT_TRUE(client.send("hello"));
  24800. std::string msg;
  24801. EXPECT_EQ(ws::Text, client.read(msg));
  24802. EXPECT_EQ("hello", msg);
  24803. client.close();
  24804. }
  24805. // A custom CA that does not cover the server must fail verification (the
  24806. // custom CA is exclusive; system certs are not loaded alongside it)
  24807. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24808. ws::WebSocketClient client(url());
  24809. std::string cert;
  24810. read_file(CLIENT_CA_CERT_FILE, cert);
  24811. client.load_ca_cert_store(cert.c_str(), cert.size());
  24812. auto res = client.connect();
  24813. ASSERT_FALSE(res);
  24814. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24815. EXPECT_EQ(-1, res.status());
  24816. EXPECT_NE(0u, res.ssl_backend_error());
  24817. }
  24818. // The same CA as a file path rather than PEM in memory
  24819. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24820. ws::WebSocketClient client(url());
  24821. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24822. ASSERT_TRUE(client.connect());
  24823. ASSERT_TRUE(client.send("hello"));
  24824. std::string msg;
  24825. EXPECT_EQ(ws::Text, client.read(msg));
  24826. EXPECT_EQ("hello", msg);
  24827. client.close();
  24828. }
  24829. // ...and a CA file that does not cover the server still fails, so it is the
  24830. // path above that decides the outcome
  24831. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24832. ws::WebSocketClient client(url());
  24833. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24834. ASSERT_FALSE(client.connect());
  24835. }
  24836. // Regression test: reconnecting with a native custom CA store used to reuse
  24837. // a store handle the previous TLS context had already freed (use-after-free
  24838. // under the OpenSSL backend). The context now lives as long as the client.
  24839. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24840. ws::WebSocketClient client(url());
  24841. std::string cert;
  24842. read_file(SERVER_CERT2_FILE, cert);
  24843. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24844. ASSERT_TRUE(client.connect());
  24845. client.close();
  24846. ASSERT_TRUE(client.connect());
  24847. ASSERT_TRUE(client.send("again"));
  24848. std::string msg;
  24849. EXPECT_EQ(ws::Text, client.read(msg));
  24850. EXPECT_EQ("again", msg);
  24851. client.close();
  24852. }
  24853. // Regression test: a certificate with a trusted chain but no identity match
  24854. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24855. // verification entirely for IP hosts, so this connection succeeded there.
  24856. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24857. // chain verification while the identity check must still fail.
  24858. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24860. ASSERT_TRUE(svr.is_valid());
  24861. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24862. std::string msg;
  24863. while (ws.read(msg)) {
  24864. ws.send(msg);
  24865. }
  24866. });
  24867. auto port = svr.bind_to_any_port("127.0.0.1");
  24868. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24869. auto se = detail::scope_exit([&] {
  24870. svr.stop();
  24871. t.join();
  24872. });
  24873. svr.wait_until_ready();
  24874. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24875. "/echo");
  24876. std::string cert;
  24877. read_file(SERVER_CERT_FILE, cert);
  24878. client.load_ca_cert_store(cert.c_str(), cert.size());
  24879. ASSERT_FALSE(client.connect());
  24880. }
  24881. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24882. // SNI, so nothing binds the host name to the TLS session. These bind the
  24883. // server to "localhost" instead, the only shape that exercises the SNI and
  24884. // hostname-verification path with certificate verification left enabled.
  24885. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24886. protected:
  24887. void Start(const char *cert_file) {
  24888. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24889. SERVER_PRIVATE_KEY_FILE);
  24890. ASSERT_TRUE(server_->is_valid());
  24891. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24892. std::string msg;
  24893. while (ws.read(msg)) {
  24894. ws.send(msg);
  24895. }
  24896. });
  24897. port_ = server_->bind_to_any_port("localhost");
  24898. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24899. server_->wait_until_ready();
  24900. }
  24901. void TearDown() override {
  24902. if (server_) { server_->stop(); }
  24903. if (server_thread_.joinable()) { server_thread_.join(); }
  24904. }
  24905. std::string url() const {
  24906. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24907. }
  24908. std::unique_ptr<SSLServer> server_;
  24909. std::thread server_thread_;
  24910. int port_ = 0;
  24911. };
  24912. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24913. // out and the connection is usable
  24914. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24915. Start(SERVER_CERT2_FILE);
  24916. ws::WebSocketClient client(url());
  24917. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24918. ASSERT_TRUE(client.connect());
  24919. ASSERT_TRUE(client.send("hello"));
  24920. std::string msg;
  24921. EXPECT_EQ(ws::Text, client.read(msg));
  24922. EXPECT_EQ("hello", msg);
  24923. client.close();
  24924. }
  24925. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24926. // while the identity check must still reject "localhost"
  24927. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24928. Start(SERVER_CERT_FILE);
  24929. ws::WebSocketClient client(url());
  24930. client.set_ca_cert_path(SERVER_CERT_FILE);
  24931. auto res = client.connect();
  24932. ASSERT_FALSE(res);
  24933. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24934. EXPECT_EQ(-1, res.status());
  24935. }
  24936. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24937. // disabled: the chain is still checked, only the identity check is skipped
  24938. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24939. Start(SERVER_CERT_FILE);
  24940. ws::WebSocketClient client(url());
  24941. client.set_ca_cert_path(SERVER_CERT_FILE);
  24942. client.enable_server_hostname_verification(false);
  24943. ASSERT_TRUE(client.connect());
  24944. ASSERT_TRUE(client.send("hello"));
  24945. std::string msg;
  24946. EXPECT_EQ(ws::Text, client.read(msg));
  24947. EXPECT_EQ("hello", msg);
  24948. client.close();
  24949. }
  24950. // A CA that did not sign the server certificate fails the chain, even though
  24951. // the name would match
  24952. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24953. Start(SERVER_CERT2_FILE);
  24954. ws::WebSocketClient client(url());
  24955. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24956. ASSERT_FALSE(client.connect());
  24957. }
  24958. // With verification disabled, neither the chain nor the name is checked
  24959. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24960. Start(SERVER_CERT_FILE);
  24961. ws::WebSocketClient client(url());
  24962. client.enable_server_certificate_verification(false);
  24963. ASSERT_TRUE(client.connect());
  24964. ASSERT_TRUE(client.send("hello"));
  24965. std::string msg;
  24966. EXPECT_EQ(ws::Text, client.read(msg));
  24967. EXPECT_EQ("hello", msg);
  24968. client.close();
  24969. }
  24970. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24971. protected:
  24972. void SetUp() override {
  24973. server_ = httplib::detail::make_unique<SSLServer>(
  24974. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24975. ASSERT_TRUE(server_->is_valid());
  24976. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24977. std::string msg;
  24978. while (ws.read(msg)) {
  24979. ws.send(msg);
  24980. }
  24981. });
  24982. port_ = server_->bind_to_any_port("localhost");
  24983. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24984. server_->wait_until_ready();
  24985. }
  24986. void TearDown() override {
  24987. server_->stop();
  24988. if (server_thread_.joinable()) { server_thread_.join(); }
  24989. }
  24990. std::string url() const {
  24991. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24992. }
  24993. void ConnectWithClientCert(const std::string &client_cert_file,
  24994. const std::string &client_private_key_file,
  24995. const char *private_key_password) {
  24996. std::string cert_pem, key_pem;
  24997. read_file(client_cert_file, cert_pem);
  24998. read_file(client_private_key_file, key_pem);
  24999. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25000. key_pem.c_str(), key_pem.size(),
  25001. private_key_password};
  25002. ConnectWithPem(pem);
  25003. }
  25004. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25005. ws::WebSocketClient client(url(), pem);
  25006. ASSERT_TRUE(client.is_valid());
  25007. client.enable_server_certificate_verification(false);
  25008. ASSERT_TRUE(client.connect());
  25009. ASSERT_TRUE(client.send("hello"));
  25010. std::string msg;
  25011. EXPECT_EQ(ws::Text, client.read(msg));
  25012. EXPECT_EQ("hello", msg);
  25013. client.close();
  25014. }
  25015. std::unique_ptr<SSLServer> server_;
  25016. std::thread server_thread_;
  25017. int port_ = 0;
  25018. };
  25019. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25020. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25021. }
  25022. // Control for the tests above: the fixture's server really does require a
  25023. // client certificate, so it is the PEM the constructor installed that decides
  25024. // the outcome.
  25025. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25026. ws::WebSocketClient client(url());
  25027. ASSERT_TRUE(client.is_valid());
  25028. client.enable_server_certificate_verification(false);
  25029. EXPECT_FALSE(client.connect());
  25030. }
  25031. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25032. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25033. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25034. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25035. }
  25036. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25037. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25038. std::string cert_pem, key_pem;
  25039. read_file(CLIENT_CERT_FILE, cert_pem);
  25040. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25041. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25042. std::vector<char> key(key_pem.begin(), key_pem.end());
  25043. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25044. key.size(), nullptr};
  25045. ConnectWithPem(pem);
  25046. }
  25047. #endif
  25048. #if !defined(_WIN32)
  25049. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25050. auto secret_dir = std::string("./symlink_test_secret");
  25051. auto served_dir = std::string("./symlink_test_served");
  25052. auto secret_file = secret_dir + "/secret.txt";
  25053. auto symlink_path = served_dir + "/escape";
  25054. // Setup: create directories and files
  25055. mkdir(secret_dir.c_str(), 0755);
  25056. mkdir(served_dir.c_str(), 0755);
  25057. {
  25058. std::ofstream ofs(secret_file);
  25059. ofs << "SECRET_DATA";
  25060. }
  25061. // Create symlink using absolute path so it resolves correctly
  25062. #ifdef PATH_MAX
  25063. char abs_secret[PATH_MAX];
  25064. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25065. #else
  25066. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25067. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25068. ASSERT_NE(nullptr, abs_secret);
  25069. #endif
  25070. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25071. auto se = detail::scope_exit([&] {
  25072. unlink(symlink_path.c_str());
  25073. unlink(secret_file.c_str());
  25074. rmdir(served_dir.c_str());
  25075. rmdir(secret_dir.c_str());
  25076. });
  25077. Server svr;
  25078. svr.set_mount_point("/", served_dir);
  25079. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25080. auto se2 = detail::scope_exit([&] {
  25081. svr.stop();
  25082. listen_thread.join();
  25083. });
  25084. svr.wait_until_ready();
  25085. Client cli("localhost", PORT);
  25086. // Symlink pointing outside base dir should be blocked
  25087. auto res = cli.Get("/escape/secret.txt");
  25088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25089. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25090. }
  25091. #endif
  25092. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25093. // "GET /smuggled" request), reads the first response, and only then sends the
  25094. // embedded request as the body. Returns how many times /smuggled ran.
  25095. //
  25096. // The body is sent AFTER receiving the first response (as in the original
  25097. // PoC) so that the stream_line_reader cannot buffer it together with the
  25098. // headers of the first request.
  25099. static int count_smuggled_requests(const std::string &outer_head,
  25100. std::string &first_response) {
  25101. Server svr;
  25102. svr.set_mount_point("/", "./www");
  25103. std::atomic<int> smuggled_count(0);
  25104. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25105. smuggled_count++;
  25106. res.set_content("oops", "text/plain");
  25107. });
  25108. svr.Post("/post", [&](const Request &req, Response &res) {
  25109. res.set_content(req.body, "text/plain");
  25110. });
  25111. auto port = svr.bind_to_any_port("localhost");
  25112. thread t = thread([&] { svr.listen_after_bind(); });
  25113. auto se = detail::scope_exit([&] {
  25114. svr.stop();
  25115. t.join();
  25116. });
  25117. svr.wait_until_ready();
  25118. auto error = Error::Success;
  25119. auto sock = detail::create_client_socket(
  25120. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25121. /*connection_timeout_sec=*/2, 0,
  25122. /*read_timeout_sec=*/2, 0,
  25123. /*write_timeout_sec=*/2, 0, std::string(), error);
  25124. EXPECT_NE(INVALID_SOCKET, sock);
  25125. if (sock == INVALID_SOCKET) { return -1; }
  25126. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25127. // The "smuggled" request will be sent as the body of the outer request
  25128. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25129. "Host: localhost\r\n"
  25130. "Connection: close\r\n"
  25131. "\r\n";
  25132. auto head = outer_head;
  25133. auto len = std::to_string(smuggled.size());
  25134. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25135. pos = head.find("{len}", pos + len.size())) {
  25136. head.replace(pos, 5, len);
  25137. }
  25138. // Step 1: Send only the outer request headers (no body yet)
  25139. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25140. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25141. // Step 2: Read the first response
  25142. char buf[4096];
  25143. for (;;) {
  25144. auto n = recv(sock, buf, sizeof(buf), 0);
  25145. if (n <= 0) break;
  25146. first_response.append(buf, static_cast<size_t>(n));
  25147. // Stop once we have a complete response (headers + body)
  25148. auto hdr_end = first_response.find("\r\n\r\n");
  25149. if (hdr_end != std::string::npos) {
  25150. // Check for Content-Length to know when the body is complete
  25151. auto cl_pos = first_response.find("Content-Length:");
  25152. if (cl_pos != std::string::npos) {
  25153. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25154. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25155. auto cl = std::stoul(
  25156. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25157. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25158. } else {
  25159. break; // No Content-Length, assume headers-only response
  25160. }
  25161. }
  25162. }
  25163. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25164. // vulnerable server the keep-alive loop reads this as a second request. The
  25165. // server may already have closed the connection, so the result is ignored.
  25166. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25167. // Half-close so that a server which drained the body sees EOF and closes,
  25168. // instead of the read below waiting for the read timeout.
  25169. #ifdef _WIN32
  25170. ::shutdown(sock, SD_SEND);
  25171. #else
  25172. ::shutdown(sock, SHUT_WR);
  25173. #endif
  25174. // Step 4: Read until the server closes the connection
  25175. for (;;) {
  25176. auto n = recv(sock, buf, sizeof(buf), 0);
  25177. if (n <= 0) break;
  25178. }
  25179. return smuggled_count.load();
  25180. }
  25181. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25182. // A GET request with Content-Length to a static file handler must have its
  25183. // body drained before the keep-alive connection is reused. Otherwise the
  25184. // unread body bytes are interpreted as the next HTTP request.
  25185. std::string first_response;
  25186. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25187. "Host: localhost\r\n"
  25188. "Content-Length: {len}\r\n"
  25189. "\r\n",
  25190. first_response));
  25191. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25192. }
  25193. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25194. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25195. // be answered with 400 and the connection closed. Treating it as "no body"
  25196. // leaves the body to be parsed as the next request.
  25197. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25198. const char *targets[] = {
  25199. "GET /file", // handler that never reads the body
  25200. "GET /not-found", // no handler matches (404)
  25201. "POST /post", // handler that reads the body
  25202. };
  25203. for (auto target : targets) {
  25204. for (auto value : values) {
  25205. std::string first_response;
  25206. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25207. " HTTP/1.1\r\n"
  25208. "Host: localhost\r\n"
  25209. "Content-Length: " +
  25210. value + "\r\n\r\n",
  25211. first_response))
  25212. << target << " with Content-Length: " << value;
  25213. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25214. << target << " with Content-Length: " << value;
  25215. }
  25216. }
  25217. }
  25218. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25219. // A 400 for an unparseable request line leaves the rest of the message
  25220. // unread, so the connection must be closed rather than reused.
  25221. std::string first_response;
  25222. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25223. "Host: localhost\r\n"
  25224. "Content-Length: {len}\r\n"
  25225. "\r\n",
  25226. first_response));
  25227. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25228. }
  25229. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25230. // Same as above for a header block that fails to parse.
  25231. std::string first_response;
  25232. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25233. "Host: localhost\r\n"
  25234. "Bad Header\r\n"
  25235. "Content-Length: {len}\r\n"
  25236. "\r\n",
  25237. first_response));
  25238. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25239. }
  25240. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25241. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25242. // server must not read another request on that connection, even when the
  25243. // request had no body to drain.
  25244. std::string first_response;
  25245. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25246. "Host: localhost\r\n"
  25247. "\r\n",
  25248. first_response));
  25249. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25250. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25251. }
  25252. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25253. // A content reader that stops early leaves the stream inside the body.
  25254. // Draining the whole Content-Length from there, or reading the body again,
  25255. // reads into the next request, and whatever follows is parsed as a request
  25256. // of its own.
  25257. Server svr;
  25258. std::atomic<int> smuggled_count(0);
  25259. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25260. svr.Post("/upload", [](const Request &req, Response &res,
  25261. const ContentReader &content_reader) {
  25262. // Stop at the last chunk, so the whole body has been read however it
  25263. // arrives.
  25264. auto length = req.get_header_value_u64("Content-Length");
  25265. size_t total = 0;
  25266. auto consumed = content_reader([&](const char *, size_t n) {
  25267. total += n;
  25268. return total < length;
  25269. });
  25270. EXPECT_FALSE(consumed);
  25271. if (req.has_param("retry")) {
  25272. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25273. }
  25274. // Replace the 400 the aborted read set, which would close the connection.
  25275. res.set_redirect("/done");
  25276. });
  25277. auto port = svr.bind_to_any_port(HOST);
  25278. thread t = thread([&] { svr.listen_after_bind(); });
  25279. auto se = detail::scope_exit([&] {
  25280. svr.stop();
  25281. t.join();
  25282. });
  25283. svr.wait_until_ready();
  25284. // A front end sees the second request as a POST whose body is the GET. The
  25285. // first body is as long as the POST's headers, so draining it again reads
  25286. // exactly those and leaves the GET to be parsed next.
  25287. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25288. "Host: localhost\r\n"
  25289. "\r\n";
  25290. std::string second_head = "POST /post HTTP/1.1\r\n"
  25291. "Host: localhost\r\n"
  25292. "Content-Length: " +
  25293. std::to_string(inner.size()) +
  25294. "\r\n"
  25295. "\r\n";
  25296. for (auto target : {"/upload", "/upload?retry"}) {
  25297. smuggled_count = 0;
  25298. std::string request = "POST " + std::string(target) +
  25299. " HTTP/1.1\r\n"
  25300. "Host: localhost\r\n"
  25301. "Content-Length: " +
  25302. std::to_string(second_head.size()) +
  25303. "\r\n"
  25304. "\r\n" +
  25305. std::string(second_head.size(), 'A') + second_head +
  25306. inner;
  25307. std::string response;
  25308. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25309. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25310. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25311. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25312. EXPECT_EQ(0, smuggled_count.load()) << target;
  25313. }
  25314. }
  25315. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25316. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25317. // must be rejected with 400 Bad Request.
  25318. Server svr;
  25319. svr.Post("/test", [&](const Request &, Response &res) {
  25320. res.set_content("ok", "text/plain");
  25321. });
  25322. thread t = thread([&] { svr.listen(HOST, PORT); });
  25323. auto se = detail::scope_exit([&] {
  25324. svr.stop();
  25325. t.join();
  25326. ASSERT_FALSE(svr.is_running());
  25327. });
  25328. svr.wait_until_ready();
  25329. // Exact "chunked"
  25330. {
  25331. auto req = "POST /test HTTP/1.1\r\n"
  25332. "Host: localhost\r\n"
  25333. "Content-Length: 5\r\n"
  25334. "Transfer-Encoding: chunked\r\n"
  25335. "Connection: close\r\n"
  25336. "\r\n"
  25337. "hello";
  25338. std::string response;
  25339. ASSERT_TRUE(send_request(1, req, &response));
  25340. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25341. response.substr(0, response.find("\r\n")));
  25342. }
  25343. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25344. {
  25345. auto req = "POST /test HTTP/1.1\r\n"
  25346. "Host: localhost\r\n"
  25347. "Content-Length: 5\r\n"
  25348. "Transfer-Encoding: gzip, chunked\r\n"
  25349. "Connection: close\r\n"
  25350. "\r\n"
  25351. "hello";
  25352. std::string response;
  25353. ASSERT_TRUE(send_request(1, req, &response));
  25354. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25355. response.substr(0, response.find("\r\n")));
  25356. }
  25357. }
  25358. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25359. Server svr;
  25360. svr.Post("/test", [&](const Request &, Response &res) {
  25361. res.set_content("ok", "text/plain");
  25362. });
  25363. thread t = thread([&] { svr.listen(HOST, PORT); });
  25364. auto se = detail::scope_exit([&] {
  25365. svr.stop();
  25366. t.join();
  25367. ASSERT_FALSE(svr.is_running());
  25368. });
  25369. svr.wait_until_ready();
  25370. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25371. // length cannot be determined, so the server must answer 400 and close
  25372. // rather than treat the request as bodyless and leave the body in the
  25373. // socket for the next request to pick up.
  25374. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25375. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25376. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25377. std::string response;
  25378. ASSERT_TRUE(send_request(1, req, &response));
  25379. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25380. response.substr(0, response.find("\r\n")))
  25381. << transfer_encoding;
  25382. }
  25383. // RFC 9110 5.3: the codings may also be split across several
  25384. // Transfer-Encoding lines, which combine in the order they were received.
  25385. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25386. // just like the single-line "chunked, gzip" above.
  25387. {
  25388. auto req = "POST /test HTTP/1.1\r\n"
  25389. "Host: localhost\r\n"
  25390. "Transfer-Encoding: chunked\r\n"
  25391. "Transfer-Encoding: gzip\r\n"
  25392. "\r\n"
  25393. "0\r\n\r\n";
  25394. std::string response;
  25395. ASSERT_TRUE(send_request(1, req, &response));
  25396. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25397. response.substr(0, response.find("\r\n")));
  25398. }
  25399. // A sequence ending in chunked stays valid.
  25400. auto req = "POST /test HTTP/1.1\r\n"
  25401. "Host: localhost\r\n"
  25402. "Transfer-Encoding: gzip, chunked\r\n"
  25403. "Connection: close\r\n"
  25404. "\r\n"
  25405. "0\r\n\r\n";
  25406. std::string response;
  25407. ASSERT_TRUE(send_request(1, req, &response));
  25408. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  25409. // ...including when it is spread over several lines.
  25410. auto split_req = "POST /test HTTP/1.1\r\n"
  25411. "Host: localhost\r\n"
  25412. "Transfer-Encoding: gzip\r\n"
  25413. "Transfer-Encoding: chunked\r\n"
  25414. "Connection: close\r\n"
  25415. "\r\n"
  25416. "0\r\n\r\n";
  25417. std::string split_response;
  25418. ASSERT_TRUE(send_request(1, split_req, &split_response));
  25419. EXPECT_EQ("HTTP/1.1 200 OK",
  25420. split_response.substr(0, split_response.find("\r\n")));
  25421. }
  25422. // Regression for issue #2450: a DELETE without Content-Length on a
  25423. // keep-alive connection must not let the post-response drain consume the
  25424. // next request's bytes.
  25425. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25426. Server svr;
  25427. std::atomic<int> delete_count(0);
  25428. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25429. delete_count++;
  25430. res.status = StatusCode::NoContent_204;
  25431. });
  25432. auto port = svr.bind_to_any_port(HOST);
  25433. thread t = thread([&] { svr.listen_after_bind(); });
  25434. auto se = detail::scope_exit([&] {
  25435. svr.stop();
  25436. t.join();
  25437. });
  25438. svr.wait_until_ready();
  25439. auto error = Error::Success;
  25440. auto sock = detail::create_client_socket(
  25441. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25442. /*connection_timeout_sec=*/2, 0,
  25443. /*read_timeout_sec=*/2, 0,
  25444. /*write_timeout_sec=*/2, 0, std::string(), error);
  25445. ASSERT_NE(INVALID_SOCKET, sock);
  25446. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25447. auto send_request_and_read_response = [&](const std::string &req,
  25448. std::string &out) -> bool {
  25449. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25450. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25451. char buf[4096];
  25452. for (;;) {
  25453. auto n = recv(sock, buf, sizeof(buf), 0);
  25454. if (n <= 0) { return !out.empty(); }
  25455. out.append(buf, static_cast<size_t>(n));
  25456. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25457. }
  25458. };
  25459. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25460. "Host: localhost\r\n"
  25461. "\r\n";
  25462. std::string resp1;
  25463. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25464. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25465. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25466. "Host: localhost\r\n"
  25467. "Connection: close\r\n"
  25468. "\r\n";
  25469. std::string resp2;
  25470. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25471. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25472. EXPECT_EQ(2, delete_count.load());
  25473. }
  25474. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25475. Server svr;
  25476. svr.Post("/ingest", [&](const Request &, Response &res,
  25477. const ContentReader &content_reader) {
  25478. auto consumed = content_reader([](const char *, size_t) { return false; });
  25479. EXPECT_FALSE(consumed);
  25480. res.status = StatusCode::Conflict_409;
  25481. res.set_header("Connection", "close");
  25482. });
  25483. auto port = svr.bind_to_any_port(HOST);
  25484. thread t = thread([&] { svr.listen_after_bind(); });
  25485. auto se = detail::scope_exit([&] {
  25486. svr.stop();
  25487. t.join();
  25488. });
  25489. svr.wait_until_ready();
  25490. auto error = Error::Success;
  25491. auto sock = detail::create_client_socket(
  25492. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25493. /*connection_timeout_sec=*/2, 0,
  25494. /*read_timeout_sec=*/1, 0,
  25495. /*write_timeout_sec=*/2, 0, std::string(), error);
  25496. ASSERT_NE(INVALID_SOCKET, sock);
  25497. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25498. std::string request = "POST /ingest HTTP/1.1\r\n"
  25499. "Host: localhost\r\n"
  25500. "Transfer-Encoding: chunked\r\n"
  25501. "\r\n"
  25502. "4\r\n"
  25503. "data\r\n";
  25504. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25505. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25506. std::string response;
  25507. ssize_t received = 0;
  25508. do {
  25509. char buf[4096];
  25510. received = recv(sock, buf, sizeof(buf), 0);
  25511. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25512. } while (received > 0);
  25513. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25514. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25515. EXPECT_EQ(0, received);
  25516. }
  25517. namespace no_proxy_test {
  25518. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25519. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25520. // calling listen().
  25521. class ScopedServer {
  25522. public:
  25523. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25524. ~ScopedServer() {
  25525. svr_.stop();
  25526. if (th_.joinable()) { th_.join(); }
  25527. }
  25528. Server &svr() { return svr_; }
  25529. int port() const { return port_; }
  25530. void listen() {
  25531. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25532. svr_.wait_until_ready();
  25533. }
  25534. private:
  25535. Server svr_;
  25536. std::thread th_;
  25537. int port_ = 0;
  25538. };
  25539. class ProxyAndTargetServers {
  25540. public:
  25541. ProxyAndTargetServers() {
  25542. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25543. proxy_hits_++;
  25544. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25545. res.set_content("via-proxy", "text/plain");
  25546. });
  25547. target_.Get(".*", [this](const Request &req, Response &res) {
  25548. target_hits_++;
  25549. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25550. res.set_content("direct", "text/plain");
  25551. });
  25552. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25553. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25554. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25555. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25556. proxy_mock_.wait_until_ready();
  25557. target_.wait_until_ready();
  25558. }
  25559. ~ProxyAndTargetServers() {
  25560. proxy_mock_.stop();
  25561. target_.stop();
  25562. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25563. if (target_thread_.joinable()) { target_thread_.join(); }
  25564. }
  25565. Server &proxy_mock() { return proxy_mock_; }
  25566. Server &target() { return target_; }
  25567. int proxy_port() const { return proxy_port_; }
  25568. int target_port() const { return target_port_; }
  25569. int proxy_hits() const { return proxy_hits_.load(); }
  25570. int target_hits() const { return target_hits_.load(); }
  25571. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25572. void reset_counters() {
  25573. proxy_hits_ = 0;
  25574. target_hits_ = 0;
  25575. last_had_proxy_authz_ = false;
  25576. }
  25577. private:
  25578. Server proxy_mock_;
  25579. Server target_;
  25580. std::thread proxy_thread_;
  25581. std::thread target_thread_;
  25582. int proxy_port_ = 0;
  25583. int target_port_ = 0;
  25584. std::atomic<int> proxy_hits_{0};
  25585. std::atomic<int> target_hits_{0};
  25586. std::atomic<bool> last_had_proxy_authz_{false};
  25587. };
  25588. inline std::unique_ptr<Client> make_client(const std::string &host,
  25589. ProxyAndTargetServers &s) {
  25590. auto cli = detail::make_unique<Client>(host, s.target_port());
  25591. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25592. cli->set_proxy("127.0.0.1", s.proxy_port());
  25593. return cli;
  25594. }
  25595. } // namespace no_proxy_test
  25596. using no_proxy_test::make_client;
  25597. using no_proxy_test::ProxyAndTargetServers;
  25598. // A stream request carries the credentials a buffered request does
  25599. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25600. no_proxy_test::ScopedServer origin;
  25601. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25602. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25603. });
  25604. origin.listen();
  25605. Client cli("127.0.0.1", origin.port());
  25606. cli.set_basic_auth("user", "pass");
  25607. auto handle = cli.open_stream("GET", "/x");
  25608. ASSERT_TRUE(handle.is_valid());
  25609. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25610. Client bearer("127.0.0.1", origin.port());
  25611. bearer.set_bearer_token_auth("tok");
  25612. auto handle2 = bearer.open_stream("GET", "/x");
  25613. ASSERT_TRUE(handle2.is_valid());
  25614. EXPECT_EQ("Bearer tok", read_all(handle2));
  25615. }
  25616. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25617. // takes its own credentials, as for a buffered request
  25618. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25619. std::string target, authz, proxy_authz;
  25620. no_proxy_test::ScopedServer proxy;
  25621. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25622. target = req.target;
  25623. authz = req.get_header_value("Authorization");
  25624. proxy_authz = req.get_header_value("Proxy-Authorization");
  25625. res.set_content("ok", "text/plain");
  25626. });
  25627. proxy.listen();
  25628. Client cli("origin.example", 8080);
  25629. cli.set_proxy("127.0.0.1", proxy.port());
  25630. cli.set_proxy_basic_auth("puser", "ppass");
  25631. cli.set_basic_auth("user", "pass");
  25632. auto handle = cli.open_stream("GET", "/x");
  25633. ASSERT_TRUE(handle.is_valid());
  25634. EXPECT_EQ("ok", read_all(handle));
  25635. EXPECT_EQ("http://origin.example:8080/x", target);
  25636. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25637. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25638. }
  25639. TEST(NoProxyTest, ExactHostnameBypasses) {
  25640. ProxyAndTargetServers s;
  25641. auto cli = make_client("example.com", s);
  25642. cli->set_no_proxy({"example.com"});
  25643. auto res = cli->Get("/");
  25644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25645. EXPECT_EQ(0, s.proxy_hits());
  25646. EXPECT_EQ(1, s.target_hits());
  25647. }
  25648. TEST(NoProxyTest, SubdomainBypasses) {
  25649. ProxyAndTargetServers s;
  25650. auto cli = make_client("foo.example.com", s);
  25651. cli->set_no_proxy({"example.com"});
  25652. auto res = cli->Get("/");
  25653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25654. EXPECT_EQ(0, s.proxy_hits());
  25655. EXPECT_EQ(1, s.target_hits());
  25656. }
  25657. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25658. // Regression guard: "evilexample.com" must not be considered a subdomain
  25659. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25660. // check would let traffic bypass the proxy and leak credentials direct
  25661. // to the attacker host.
  25662. ProxyAndTargetServers s;
  25663. auto cli = make_client("evilexample.com", s);
  25664. cli->set_no_proxy({"example.com"});
  25665. auto res = cli->Get("/");
  25666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25667. EXPECT_GE(s.proxy_hits(), 1);
  25668. EXPECT_EQ(0, s.target_hits());
  25669. }
  25670. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25671. ProxyAndTargetServers s;
  25672. auto cli = make_client("example.com.evil.com", s);
  25673. cli->set_no_proxy({"example.com"});
  25674. auto res = cli->Get("/");
  25675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25676. EXPECT_GE(s.proxy_hits(), 1);
  25677. EXPECT_EQ(0, s.target_hits());
  25678. }
  25679. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25680. ProxyAndTargetServers s;
  25681. auto cli = make_client("example.com", s);
  25682. cli->set_no_proxy({".example.com"});
  25683. auto res = cli->Get("/");
  25684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25685. EXPECT_EQ(0, s.proxy_hits());
  25686. EXPECT_EQ(1, s.target_hits());
  25687. }
  25688. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25689. ProxyAndTargetServers s;
  25690. auto cli = make_client("Example.COM", s);
  25691. cli->set_no_proxy({"EXAMPLE.com"});
  25692. auto res = cli->Get("/");
  25693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25694. EXPECT_EQ(0, s.proxy_hits());
  25695. EXPECT_EQ(1, s.target_hits());
  25696. }
  25697. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25698. ProxyAndTargetServers s;
  25699. auto cli = make_client("example.com.", s);
  25700. cli->set_no_proxy({"example.com"});
  25701. auto res = cli->Get("/");
  25702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25703. EXPECT_EQ(0, s.proxy_hits());
  25704. EXPECT_EQ(1, s.target_hits());
  25705. }
  25706. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25707. // Trailing dots must be normalized on BOTH sides — host and entry.
  25708. // An implementation that only strips the host-side trailing dot would
  25709. // fail to match host "example.com" against entry "example.com." because
  25710. // a literal substring search would compare 11 chars against 12.
  25711. ProxyAndTargetServers s;
  25712. auto cli = make_client("example.com", s);
  25713. cli->set_no_proxy({"example.com."});
  25714. auto res = cli->Get("/");
  25715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25716. EXPECT_EQ(0, s.proxy_hits());
  25717. EXPECT_EQ(1, s.target_hits());
  25718. }
  25719. TEST(NoProxyTest, WildcardBypassesEverything) {
  25720. ProxyAndTargetServers s;
  25721. auto cli = make_client("anything.invalid.test", s);
  25722. cli->set_no_proxy({"*"});
  25723. auto res = cli->Get("/");
  25724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25725. EXPECT_EQ(0, s.proxy_hits());
  25726. EXPECT_EQ(1, s.target_hits());
  25727. }
  25728. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25729. ProxyAndTargetServers s;
  25730. Client cli("127.0.0.1", s.target_port());
  25731. cli.set_proxy("127.0.0.1", s.proxy_port());
  25732. cli.set_no_proxy({"127.0.0.1"});
  25733. auto res = cli.Get("/");
  25734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25735. EXPECT_EQ(0, s.proxy_hits());
  25736. EXPECT_EQ(1, s.target_hits());
  25737. }
  25738. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25739. ProxyAndTargetServers s;
  25740. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25741. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25742. cli.set_proxy("127.0.0.1", s.proxy_port());
  25743. cli.set_no_proxy({"::1"});
  25744. auto res = cli.Get("/");
  25745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25746. EXPECT_EQ(0, s.proxy_hits());
  25747. EXPECT_EQ(1, s.target_hits());
  25748. }
  25749. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25750. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25751. // must still be recognized as IPv6 for CIDR matching. Implementations
  25752. // that detect IPv6 only when the host begins with '[' would parse the
  25753. // host as a hostname and miss the match.
  25754. ProxyAndTargetServers s;
  25755. Client cli("fe80::1", s.target_port());
  25756. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25757. cli.set_proxy("127.0.0.1", s.proxy_port());
  25758. cli.set_no_proxy({"fe80::/10"});
  25759. auto res = cli.Get("/");
  25760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25761. EXPECT_EQ(0, s.proxy_hits());
  25762. EXPECT_EQ(1, s.target_hits());
  25763. }
  25764. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25765. ProxyAndTargetServers s;
  25766. Client cli("::1", s.target_port());
  25767. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25768. cli.set_proxy("127.0.0.1", s.proxy_port());
  25769. cli.set_no_proxy({"[::1]"});
  25770. auto res = cli.Get("/");
  25771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25772. EXPECT_EQ(0, s.proxy_hits());
  25773. EXPECT_EQ(1, s.target_hits());
  25774. }
  25775. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25776. ProxyAndTargetServers s;
  25777. Client cli("fe80::1", s.target_port());
  25778. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25779. cli.set_proxy("127.0.0.1", s.proxy_port());
  25780. cli.set_no_proxy({"[fe80::]/10"});
  25781. auto res = cli.Get("/");
  25782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25783. EXPECT_EQ(0, s.proxy_hits());
  25784. EXPECT_EQ(1, s.target_hits());
  25785. }
  25786. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25787. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25788. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25789. // tricks via address-family conversion.
  25790. ProxyAndTargetServers s;
  25791. Client cli("::ffff:127.0.0.1", s.target_port());
  25792. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25793. cli.set_proxy("127.0.0.1", s.proxy_port());
  25794. cli.set_no_proxy({"127.0.0.1"});
  25795. auto res = cli.Get("/");
  25796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25797. EXPECT_GE(s.proxy_hits(), 1);
  25798. EXPECT_EQ(0, s.target_hits());
  25799. }
  25800. TEST(NoProxyTest, IPv4CidrMatch) {
  25801. ProxyAndTargetServers s;
  25802. Client cli("127.0.0.1", s.target_port());
  25803. cli.set_proxy("127.0.0.1", s.proxy_port());
  25804. cli.set_no_proxy({"127.0.0.0/8"});
  25805. auto res = cli.Get("/");
  25806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25807. EXPECT_EQ(0, s.proxy_hits());
  25808. EXPECT_EQ(1, s.target_hits());
  25809. }
  25810. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25811. ProxyAndTargetServers s;
  25812. Client cli("127.0.0.1", s.target_port());
  25813. cli.set_proxy("127.0.0.1", s.proxy_port());
  25814. cli.set_no_proxy({"10.0.0.0/8"});
  25815. auto res = cli.Get("/");
  25816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25817. EXPECT_GE(s.proxy_hits(), 1);
  25818. EXPECT_EQ(0, s.target_hits());
  25819. }
  25820. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25821. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25822. // IPv4 target matches.
  25823. ProxyAndTargetServers s;
  25824. Client cli("127.0.0.1", s.target_port());
  25825. cli.set_proxy("127.0.0.1", s.proxy_port());
  25826. cli.set_no_proxy({"0.0.0.0/0"});
  25827. auto res = cli.Get("/");
  25828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25829. EXPECT_EQ(0, s.proxy_hits());
  25830. EXPECT_EQ(1, s.target_hits());
  25831. }
  25832. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25833. ProxyAndTargetServers s;
  25834. Client cli("127.0.0.1", s.target_port());
  25835. cli.set_proxy("127.0.0.1", s.proxy_port());
  25836. cli.set_no_proxy({"127.0.0.1"});
  25837. auto res = cli.Get("/");
  25838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25839. EXPECT_EQ(0, s.proxy_hits());
  25840. EXPECT_EQ(1, s.target_hits());
  25841. }
  25842. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25843. ProxyAndTargetServers s;
  25844. Client cli("127.0.0.1", s.target_port());
  25845. cli.set_proxy("127.0.0.1", s.proxy_port());
  25846. cli.set_no_proxy({"127.0.0.0/33"});
  25847. auto res = cli.Get("/");
  25848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25849. EXPECT_GE(s.proxy_hits(), 1);
  25850. EXPECT_EQ(0, s.target_hits());
  25851. }
  25852. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25853. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25854. ProxyAndTargetServers s;
  25855. Client cli("127.0.0.1", s.target_port());
  25856. cli.set_proxy("127.0.0.1", s.proxy_port());
  25857. cli.set_no_proxy({"127.0.0.1/"});
  25858. auto res = cli.Get("/");
  25859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25860. EXPECT_GE(s.proxy_hits(), 1);
  25861. EXPECT_EQ(0, s.target_hits());
  25862. }
  25863. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25864. ProxyAndTargetServers s;
  25865. auto cli = make_client("internal.corp", s);
  25866. cli->set_proxy_basic_auth("u", "p");
  25867. cli->set_no_proxy({"internal.corp"});
  25868. auto res = cli->Get("/");
  25869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25870. EXPECT_EQ(1, s.target_hits());
  25871. EXPECT_EQ(0, s.proxy_hits());
  25872. EXPECT_FALSE(s.last_had_proxy_authz())
  25873. << "Proxy-Authorization must not be sent direct to the target";
  25874. }
  25875. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25876. ProxyAndTargetServers s;
  25877. auto cli = make_client("public.example", s);
  25878. cli->set_proxy_basic_auth("u", "p");
  25879. cli->set_no_proxy({"internal.corp"}); // does not match
  25880. auto res = cli->Get("/");
  25881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25882. EXPECT_GE(s.proxy_hits(), 1);
  25883. EXPECT_TRUE(s.last_had_proxy_authz());
  25884. }
  25885. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25886. std::atomic<int> hits{0};
  25887. std::atomic<int> hits_with_authz{0};
  25888. no_proxy_test::ScopedServer proxy_mock;
  25889. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25890. hits++;
  25891. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25892. if (req.target.find("/redir") != std::string::npos) {
  25893. res.set_redirect("http://other.example/landed");
  25894. } else {
  25895. res.set_content("via-proxy", "text/plain");
  25896. }
  25897. });
  25898. proxy_mock.listen();
  25899. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25900. hits = 0;
  25901. hits_with_authz = 0;
  25902. Client cli("public.example", 80);
  25903. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25904. cli.set_proxy_basic_auth(c.first, c.second);
  25905. cli.set_follow_location(true);
  25906. // The redirect to another host goes through the proxy as well
  25907. auto res = cli.Get("/redir");
  25908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25909. EXPECT_EQ(2, hits.load());
  25910. EXPECT_EQ(2, hits_with_authz.load());
  25911. }
  25912. }
  25913. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25914. ProxyAndTargetServers s;
  25915. auto cli = make_client("anything.test", s);
  25916. auto res = cli->Get("/");
  25917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25918. EXPECT_GE(s.proxy_hits(), 1);
  25919. EXPECT_EQ(0, s.target_hits());
  25920. }
  25921. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25922. ProxyAndTargetServers s;
  25923. auto cli = make_client("example.com", s);
  25924. cli->set_no_proxy({"example.com:8080"});
  25925. auto res = cli->Get("/");
  25926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25927. EXPECT_GE(s.proxy_hits(), 1);
  25928. EXPECT_EQ(0, s.target_hits());
  25929. }
  25930. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25931. ProxyAndTargetServers s;
  25932. auto cli = make_client("anything.test", s);
  25933. cli->set_no_proxy({"", " ", "\t"});
  25934. auto res = cli->Get("/");
  25935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25936. EXPECT_GE(s.proxy_hits(), 1);
  25937. EXPECT_EQ(0, s.target_hits());
  25938. }
  25939. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25940. // An entry with leading/trailing whitespace must still match — env-style
  25941. // values are commonly pasted with stray spaces and an implementation
  25942. // that feeds the raw token directly to inet_pton would fail to match
  25943. // valid CIDRs because of the spaces.
  25944. ProxyAndTargetServers s;
  25945. Client cli("127.0.0.1", s.target_port());
  25946. cli.set_proxy("127.0.0.1", s.proxy_port());
  25947. cli.set_no_proxy({" 127.0.0.0/8 "});
  25948. auto res = cli.Get("/");
  25949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25950. EXPECT_EQ(0, s.proxy_hits());
  25951. EXPECT_EQ(1, s.target_hits());
  25952. }
  25953. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25954. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25955. // go direct and must NOT carry Proxy-Authorization.
  25956. std::atomic<int> proxy_hits{0};
  25957. std::atomic<int> target_hits{0};
  25958. std::atomic<bool> target_saw_authz{false};
  25959. no_proxy_test::ScopedServer proxy_mock, target;
  25960. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25961. proxy_hits++;
  25962. res.status = 302;
  25963. res.set_header("Location", "http://127.0.0.1:" +
  25964. std::to_string(target.port()) + "/landed");
  25965. });
  25966. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25967. target_hits++;
  25968. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25969. res.set_content("direct", "text/plain");
  25970. });
  25971. proxy_mock.listen();
  25972. target.listen();
  25973. Client cli("public.example", target.port());
  25974. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25975. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25976. cli.set_proxy_basic_auth("u", "p");
  25977. cli.set_no_proxy({"127.0.0.1"});
  25978. cli.set_follow_location(true);
  25979. auto res = cli.Get("/redir");
  25980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25981. EXPECT_GE(proxy_hits.load(), 1);
  25982. EXPECT_GE(target_hits.load(), 1);
  25983. EXPECT_FALSE(target_saw_authz.load());
  25984. }
  25985. #ifdef CPPHTTPLIB_SSL_ENABLED
  25986. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25987. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25988. // proxy creds would be sent to the (possibly hostile) origin.
  25989. std::atomic<int> target_hits{0};
  25990. std::atomic<bool> target_saw_proxy_authz{false};
  25991. no_proxy_test::ScopedServer target;
  25992. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25993. target_hits++;
  25994. if (req.has_header("Proxy-Authorization")) {
  25995. target_saw_proxy_authz = true;
  25996. }
  25997. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25998. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25999. "nonce=\"abc\", algorithm=MD5");
  26000. });
  26001. target.listen();
  26002. // The proxy address is set to the target's port: the bypass MUST kick in;
  26003. // if it doesn't, the test still routes "via proxy" to the same server and
  26004. // the Proxy-Authorization assertion below catches the leak.
  26005. Client cli("evil.example", target.port());
  26006. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26007. cli.set_proxy("127.0.0.1", target.port());
  26008. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26009. cli.set_no_proxy({"evil.example"});
  26010. auto res = cli.Get("/x");
  26011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26012. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26013. EXPECT_EQ(1, target_hits.load());
  26014. EXPECT_FALSE(target_saw_proxy_authz.load());
  26015. }
  26016. #endif
  26017. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26018. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26019. std::atomic<int> proxy_hits{0};
  26020. std::atomic<int> bypass_hits{0};
  26021. std::atomic<bool> proxy_saw_c_url{false};
  26022. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26023. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26024. proxy_hits++;
  26025. if (req.path.find("/start") != std::string::npos) {
  26026. res.status = 302;
  26027. res.set_header("Location", "http://127.0.0.1:" +
  26028. std::to_string(bypass_server.port()) +
  26029. "/middle");
  26030. return;
  26031. }
  26032. if (req.path.find("/end") != std::string::npos) {
  26033. proxy_saw_c_url = true;
  26034. res.set_content("c-via-proxy", "text/plain");
  26035. return;
  26036. }
  26037. res.set_content("unexpected", "text/plain");
  26038. });
  26039. // public.example's "advertised" port is arbitrary (the request never lands
  26040. // there — it goes through the proxy), but use a dynamic value to stay
  26041. // friendly with sharded parallel runs.
  26042. int public_port = bypass_server.port();
  26043. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26044. bypass_hits++;
  26045. res.status = 302;
  26046. res.set_header("Location", "http://public.example:" +
  26047. std::to_string(public_port) + "/end");
  26048. });
  26049. proxy_mock.listen();
  26050. bypass_server.listen();
  26051. Client cli("public.example", public_port);
  26052. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26053. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26054. cli.set_no_proxy({"127.0.0.1"});
  26055. cli.set_follow_location(true);
  26056. auto res = cli.Get("/start");
  26057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26058. EXPECT_EQ(StatusCode::OK_200, res->status);
  26059. EXPECT_EQ("c-via-proxy", res->body);
  26060. EXPECT_GE(proxy_hits.load(), 2);
  26061. EXPECT_GE(bypass_hits.load(), 1);
  26062. EXPECT_TRUE(proxy_saw_c_url.load());
  26063. }
  26064. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26065. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26066. // request reconnects to the correct endpoint.
  26067. std::atomic<int> proxy_hits{0};
  26068. std::atomic<int> target_hits{0};
  26069. no_proxy_test::ScopedServer proxy_mock, target;
  26070. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26071. proxy_hits++;
  26072. res.set_content("via-proxy", "text/plain");
  26073. });
  26074. target.svr().Get(".*", [&](const Request &, Response &res) {
  26075. target_hits++;
  26076. res.set_content("direct", "text/plain");
  26077. });
  26078. proxy_mock.listen();
  26079. target.listen();
  26080. Client cli("public.example", target.port());
  26081. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26082. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26083. cli.set_keep_alive(true);
  26084. auto res1 = cli.Get("/a");
  26085. ASSERT_TRUE(res1);
  26086. EXPECT_EQ("via-proxy", res1->body);
  26087. EXPECT_EQ(1, proxy_hits.load());
  26088. EXPECT_EQ(0, target_hits.load());
  26089. cli.set_no_proxy({"public.example"});
  26090. auto res2 = cli.Get("/b");
  26091. ASSERT_TRUE(res2);
  26092. EXPECT_EQ("direct", res2->body);
  26093. EXPECT_EQ(1, proxy_hits.load());
  26094. EXPECT_EQ(1, target_hits.load());
  26095. }
  26096. // Forward declarations (see the base64_encode note).
  26097. namespace httplib {
  26098. namespace detail {
  26099. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26100. int shutdown_socket(socket_t sock) noexcept;
  26101. } // namespace detail
  26102. } // namespace httplib
  26103. namespace proxy_tunnel_test {
  26104. const char *const kTunnelEstablished =
  26105. "HTTP/1.1 200 Connection established\r\n\r\n";
  26106. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26107. using ConnectReply = std::function<std::string(const std::string &head)>;
  26108. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26109. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26110. class ScopedConnectProxy {
  26111. public:
  26112. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26113. : forward_port_(forward_port), reply_(std::move(reply)) {
  26114. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26115. if (listen_sock_ == INVALID_SOCKET) { return; }
  26116. auto a = loopback(0);
  26117. auto addr = reinterpret_cast<sockaddr *>(&a);
  26118. socklen_t alen = sizeof(a);
  26119. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26120. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26121. ::listen(listen_sock_, 4) != 0) {
  26122. return;
  26123. }
  26124. port_ = ntohs(a.sin_port);
  26125. th_ = std::thread([this] { run(); });
  26126. }
  26127. ~ScopedConnectProxy() {
  26128. if (th_.joinable()) {
  26129. stop_ = true;
  26130. auto wake = connect_to(port_);
  26131. th_.join();
  26132. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26133. }
  26134. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26135. }
  26136. int port() const { return port_; }
  26137. int connect_hits() const { return connect_hits_.load(); }
  26138. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26139. std::string connect_request() const {
  26140. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26141. return connect_request_;
  26142. }
  26143. private:
  26144. static sockaddr_in loopback(int port) {
  26145. sockaddr_in a{};
  26146. a.sin_family = AF_INET;
  26147. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26148. a.sin_port = htons(static_cast<unsigned short>(port));
  26149. return a;
  26150. }
  26151. static socket_t connect_to(int port) {
  26152. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26153. if (sock == INVALID_SOCKET) { return sock; }
  26154. auto a = loopback(port);
  26155. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26156. detail::close_socket(sock);
  26157. return INVALID_SOCKET;
  26158. }
  26159. return sock;
  26160. }
  26161. static bool send_all(socket_t sock, const char *data, size_t size) {
  26162. while (size > 0) {
  26163. auto n = detail::send_socket(sock, data, size, 0);
  26164. if (n <= 0) { return false; }
  26165. data += n;
  26166. size -= static_cast<size_t>(n);
  26167. }
  26168. return true;
  26169. }
  26170. void run() {
  26171. for (;;) {
  26172. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26173. if (stop_) {
  26174. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26175. return;
  26176. }
  26177. if (client == INVALID_SOCKET) { continue; }
  26178. serve(client);
  26179. detail::close_socket(client);
  26180. }
  26181. }
  26182. void serve(socket_t client) {
  26183. std::string head;
  26184. char buf[2048];
  26185. while (head.find("\r\n\r\n") == std::string::npos) {
  26186. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26187. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26188. if (n <= 0) { return; }
  26189. head.append(buf, static_cast<size_t>(n));
  26190. }
  26191. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26192. connect_hits_++;
  26193. {
  26194. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26195. connect_request_ = head;
  26196. }
  26197. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26198. if (!send_all(client, res.data(), res.size()) ||
  26199. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26200. return;
  26201. }
  26202. auto origin = connect_to(forward_port_);
  26203. if (origin == INVALID_SOCKET) { return; }
  26204. // When either side stops, shut both down so the other pump returns too.
  26205. auto pump = [&](socket_t from, socket_t to) {
  26206. char b[8192];
  26207. for (;;) {
  26208. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26209. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26210. }
  26211. detail::shutdown_socket(client);
  26212. detail::shutdown_socket(origin);
  26213. };
  26214. std::thread up([&] { pump(client, origin); });
  26215. pump(origin, client);
  26216. up.join();
  26217. detail::close_socket(origin);
  26218. }
  26219. int forward_port_;
  26220. ConnectReply reply_;
  26221. socket_t listen_sock_ = INVALID_SOCKET;
  26222. int port_ = 0;
  26223. std::thread th_;
  26224. std::atomic<bool> stop_{false};
  26225. std::atomic<int> connect_hits_{0};
  26226. mutable std::mutex connect_request_mutex_;
  26227. std::string connect_request_;
  26228. };
  26229. } // namespace proxy_tunnel_test
  26230. #ifdef CPPHTTPLIB_SSL_ENABLED
  26231. namespace proxy_tunnel_test {
  26232. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26233. class ScopedSSLServer {
  26234. public:
  26235. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26236. port_ = svr_.bind_to_any_port("127.0.0.1");
  26237. }
  26238. ~ScopedSSLServer() {
  26239. svr_.stop();
  26240. if (th_.joinable()) { th_.join(); }
  26241. }
  26242. SSLServer &svr() { return svr_; }
  26243. int port() const { return port_; }
  26244. void listen() {
  26245. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26246. svr_.wait_until_ready();
  26247. }
  26248. private:
  26249. SSLServer svr_;
  26250. std::thread th_;
  26251. int port_ = 0;
  26252. };
  26253. // Sends one request through the CONNECT proxy to the TLS origin with a
  26254. // credential configured for each hop, and checks that each credential reaches
  26255. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26256. // origin's (every header in origin_headers) on the tunnelled request.
  26257. void CredentialsStayWithTheirHop(
  26258. const std::function<void(SSLClient &)> &set_credentials,
  26259. const std::string &scheme,
  26260. const std::vector<std::string> &origin_headers = {"Authorization"},
  26261. bool stream = false) {
  26262. std::atomic<int> origin_hits{0};
  26263. std::atomic<bool> origin_saw_proxy_authz{false};
  26264. std::atomic<bool> origin_saw_headers{false};
  26265. ScopedSSLServer origin;
  26266. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26267. origin_hits++;
  26268. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26269. origin_saw_headers =
  26270. std::all_of(origin_headers.begin(), origin_headers.end(),
  26271. [&](const std::string &h) { return req.has_header(h); });
  26272. res.set_content("ok", "text/plain");
  26273. });
  26274. origin.listen();
  26275. ScopedConnectProxy proxy(origin.port());
  26276. ASSERT_NE(0, proxy.port());
  26277. // Pinned to 127.0.0.1 for the same reason as the test below.
  26278. SSLClient cli("127.0.0.1", origin.port());
  26279. cli.enable_server_certificate_verification(false);
  26280. cli.set_proxy("127.0.0.1", proxy.port());
  26281. set_credentials(cli);
  26282. if (stream) {
  26283. auto handle = cli.open_stream("GET", "/x");
  26284. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26285. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26286. } else {
  26287. auto res = cli.Get("/x");
  26288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26289. EXPECT_EQ(StatusCode::OK_200, res->status);
  26290. }
  26291. EXPECT_EQ(1, origin_hits.load());
  26292. EXPECT_EQ(1, proxy.connect_hits());
  26293. EXPECT_TRUE(origin_saw_headers.load());
  26294. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26295. << "Proxy-Authorization must not be sent inside the tunnel";
  26296. auto connect_req = proxy.connect_request();
  26297. EXPECT_NE(std::string::npos,
  26298. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26299. for (const auto &h : origin_headers) {
  26300. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26301. << h << " must not be sent to the proxy on CONNECT";
  26302. }
  26303. }
  26304. } // namespace proxy_tunnel_test
  26305. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26306. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26307. [](SSLClient &cli) {
  26308. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26309. cli.set_basic_auth("origin-user", "origin-pass");
  26310. },
  26311. "Basic");
  26312. }
  26313. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26314. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26315. [](SSLClient &cli) {
  26316. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26317. cli.set_basic_auth("origin-user", "origin-pass");
  26318. },
  26319. "Basic", {"Authorization"}, true);
  26320. }
  26321. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26322. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26323. [](SSLClient &cli) {
  26324. cli.set_proxy_bearer_token_auth("proxy-token");
  26325. cli.set_bearer_token_auth("origin-token");
  26326. },
  26327. "Bearer");
  26328. }
  26329. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26330. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26331. [](SSLClient &cli) {
  26332. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26333. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26334. {"Cookie", "sid=origin-session"},
  26335. {"X-Api-Key", "origin-key"}});
  26336. },
  26337. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26338. }
  26339. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26340. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26341. // retry; otherwise proxy creds would be sent to the origin.
  26342. std::atomic<int> origin_hits{0};
  26343. std::atomic<bool> origin_saw_proxy_authz{false};
  26344. proxy_tunnel_test::ScopedSSLServer origin;
  26345. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26346. origin_hits++;
  26347. if (req.has_header("Proxy-Authorization")) {
  26348. origin_saw_proxy_authz = true;
  26349. }
  26350. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26351. res.set_header("Proxy-Authenticate",
  26352. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26353. "algorithm=MD5");
  26354. });
  26355. origin.listen();
  26356. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26357. ASSERT_NE(0, proxy.port());
  26358. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26359. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26360. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26361. // and answer with its own status, making this test flaky.
  26362. SSLClient cli("127.0.0.1", origin.port());
  26363. cli.enable_server_certificate_verification(false);
  26364. cli.set_proxy("127.0.0.1", proxy.port());
  26365. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26366. auto res = cli.Get("/x");
  26367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26368. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26369. EXPECT_EQ(1, origin_hits.load());
  26370. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26371. EXPECT_EQ(1, proxy.connect_hits());
  26372. }
  26373. #endif
  26374. namespace proxy_tunnel_test {
  26375. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26376. // anything else gets a 407 with `challenge`.
  26377. ConnectReply require_proxy_auth(const std::string &expected,
  26378. const std::string &challenge) {
  26379. return [=](const std::string &head) -> std::string {
  26380. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26381. std::string::npos) {
  26382. return kTunnelEstablished;
  26383. }
  26384. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26385. "Proxy-Authenticate: " +
  26386. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26387. };
  26388. }
  26389. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26390. // request, then echoes.
  26391. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26392. ws.send(
  26393. "authorization:" + req.get_header_value("Authorization") +
  26394. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26395. std::string msg;
  26396. while (ws.read(msg)) {
  26397. ws.send(msg);
  26398. }
  26399. }
  26400. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26401. class ScopedWebSocketOrigin {
  26402. public:
  26403. ScopedWebSocketOrigin() {
  26404. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26405. server_.listen();
  26406. }
  26407. int port() const { return server_.port(); }
  26408. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26409. std::string url() const {
  26410. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26411. }
  26412. private:
  26413. no_proxy_test::ScopedServer server_;
  26414. };
  26415. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26416. // passed as a constructor header, and checks that each reaches only its hop.
  26417. void WebSocketCredentialsStayWithTheirHop(
  26418. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26419. const std::string &proxy_authz, const std::string &origin_authz) {
  26420. ScopedWebSocketOrigin origin;
  26421. ScopedConnectProxy proxy(
  26422. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26423. ASSERT_NE(0, proxy.port());
  26424. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26425. client.set_proxy("127.0.0.1", proxy.port());
  26426. set_proxy_credentials(client);
  26427. auto res = client.connect();
  26428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26429. std::string msg;
  26430. ASSERT_TRUE(client.read(msg));
  26431. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26432. client.close();
  26433. EXPECT_EQ(1, proxy.connect_hits());
  26434. EXPECT_EQ(std::string::npos,
  26435. proxy.connect_request().find("\r\nAuthorization: "))
  26436. << "origin credentials must not be sent to the proxy";
  26437. }
  26438. } // namespace proxy_tunnel_test
  26439. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26440. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26441. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26442. ASSERT_NE(0, proxy.port());
  26443. ws::WebSocketClient client(origin.url());
  26444. client.set_proxy("127.0.0.1", proxy.port());
  26445. auto res = client.connect();
  26446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26447. std::string msg;
  26448. ASSERT_TRUE(client.read(msg));
  26449. ASSERT_TRUE(client.send("hello"));
  26450. ASSERT_TRUE(client.read(msg));
  26451. EXPECT_EQ("hello", msg);
  26452. client.close();
  26453. EXPECT_EQ(1, proxy.connect_hits());
  26454. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26455. auto connect_req = proxy.connect_request();
  26456. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26457. EXPECT_NE(std::string::npos,
  26458. connect_req.find("\r\nHost: " + target + "\r\n"));
  26459. }
  26460. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26461. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26462. [](ws::WebSocketClient &cli) {
  26463. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26464. },
  26465. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26466. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26467. }
  26468. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26469. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26470. [](ws::WebSocketClient &cli) {
  26471. cli.set_proxy_bearer_token_auth("proxy-token");
  26472. },
  26473. "Bearer proxy-token", "Bearer origin-token");
  26474. }
  26475. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26476. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26477. proxy_tunnel_test::ScopedConnectProxy proxy(
  26478. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26479. "Basic " + detail::base64_encode("proxy-user:"),
  26480. "Basic realm=\"proxy\""));
  26481. ASSERT_NE(0, proxy.port());
  26482. ws::WebSocketClient client(origin.url());
  26483. client.set_proxy("127.0.0.1", proxy.port());
  26484. client.set_proxy_basic_auth("proxy-user", "");
  26485. auto res = client.connect();
  26486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26487. client.close();
  26488. EXPECT_EQ(1, proxy.connect_hits());
  26489. }
  26490. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26491. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26492. proxy_tunnel_test::ScopedConnectProxy proxy(
  26493. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26494. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26495. ASSERT_NE(0, proxy.port());
  26496. ws::WebSocketClient client(origin.url());
  26497. client.set_proxy("127.0.0.1", proxy.port());
  26498. auto res = client.connect();
  26499. EXPECT_FALSE(res);
  26500. EXPECT_EQ(Error::ProxyConnection, res.error());
  26501. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26502. EXPECT_EQ("Basic realm=\"proxy\"",
  26503. res.get_header_value("Proxy-Authenticate"));
  26504. EXPECT_FALSE(client.is_open());
  26505. }
  26506. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26507. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26508. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26509. ASSERT_NE(0, proxy.port());
  26510. ws::WebSocketClient client(origin.url());
  26511. client.set_proxy("127.0.0.1", proxy.port());
  26512. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26513. client.set_no_proxy({"127.0.0.1"});
  26514. auto res = client.connect();
  26515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26516. std::string msg;
  26517. ASSERT_TRUE(client.read(msg));
  26518. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26519. << "proxy credentials must not reach a bypassed origin";
  26520. client.close();
  26521. EXPECT_EQ(0, proxy.connect_hits());
  26522. }
  26523. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26524. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26525. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26526. ASSERT_NE(0, proxy.port());
  26527. ws::WebSocketClient client(origin.url());
  26528. client.set_proxy("127.0.0.1", proxy.port());
  26529. ASSERT_TRUE(client.connect());
  26530. ASSERT_TRUE(client.connect());
  26531. client.close();
  26532. EXPECT_EQ(2, proxy.connect_hits());
  26533. }
  26534. #ifdef CPPHTTPLIB_SSL_ENABLED
  26535. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26536. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26537. proxy_tunnel_test::ScopedConnectProxy proxy(
  26538. origin.port(), [](const std::string &head) -> std::string {
  26539. if (head.find(
  26540. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26541. std::string::npos) {
  26542. return proxy_tunnel_test::kTunnelEstablished;
  26543. }
  26544. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26545. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26546. "nonce=\"abc\", algorithm=MD5\r\n"
  26547. "Content-Length: 0\r\n\r\n";
  26548. });
  26549. ASSERT_NE(0, proxy.port());
  26550. ws::WebSocketClient client(origin.url());
  26551. client.set_proxy("127.0.0.1", proxy.port());
  26552. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26553. auto res = client.connect();
  26554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26555. std::string msg;
  26556. ASSERT_TRUE(client.read(msg));
  26557. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26558. client.close();
  26559. EXPECT_EQ(2, proxy.connect_hits());
  26560. }
  26561. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26562. proxy_tunnel_test::ScopedSSLServer origin;
  26563. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26564. origin.listen();
  26565. proxy_tunnel_test::ScopedConnectProxy proxy(
  26566. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26567. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26568. ASSERT_NE(0, proxy.port());
  26569. ws::WebSocketClient client(
  26570. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26571. client.enable_server_certificate_verification(false);
  26572. client.set_proxy("127.0.0.1", proxy.port());
  26573. client.set_proxy_bearer_token_auth("proxy-token");
  26574. auto res = client.connect();
  26575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26576. std::string msg;
  26577. ASSERT_TRUE(client.read(msg));
  26578. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26579. << "Proxy-Authorization must not be sent inside the tunnel";
  26580. client.close();
  26581. EXPECT_EQ(1, proxy.connect_hits());
  26582. }
  26583. #endif