test.cc 559 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206
  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 <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(DivideTest, DivideStringTests) {
  666. auto divide = [](const std::string &str, char d) {
  667. std::string lhs;
  668. std::string rhs;
  669. detail::divide(str, d,
  670. [&](const char *lhs_data, std::size_t lhs_size,
  671. const char *rhs_data, std::size_t rhs_size) {
  672. lhs.assign(lhs_data, lhs_size);
  673. rhs.assign(rhs_data, rhs_size);
  674. });
  675. return std::make_pair(std::move(lhs), std::move(rhs));
  676. };
  677. {
  678. const auto res = divide("", '=');
  679. EXPECT_EQ(res.first, "");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "");
  686. }
  687. {
  688. const auto res = divide(" ", '=');
  689. EXPECT_EQ(res.first, " ");
  690. EXPECT_EQ(res.second, "");
  691. }
  692. {
  693. const auto res = divide("a", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "");
  696. }
  697. {
  698. const auto res = divide("a=", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "");
  701. }
  702. {
  703. const auto res = divide("=b", '=');
  704. EXPECT_EQ(res.first, "");
  705. EXPECT_EQ(res.second, "b");
  706. }
  707. {
  708. const auto res = divide("a=b", '=');
  709. EXPECT_EQ(res.first, "a");
  710. EXPECT_EQ(res.second, "b");
  711. }
  712. {
  713. const auto res = divide("a=b=", '=');
  714. EXPECT_EQ(res.first, "a");
  715. EXPECT_EQ(res.second, "b=");
  716. }
  717. {
  718. const auto res = divide("a=b=c", '=');
  719. EXPECT_EQ(res.first, "a");
  720. EXPECT_EQ(res.second, "b=c");
  721. }
  722. }
  723. TEST(SplitTest, ParseQueryString) {
  724. string s = "key1=val1&key2=val2&key3=val3";
  725. Params dic;
  726. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  727. [&](const char *b, const char *e) {
  728. string key, val;
  729. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  730. if (key.empty()) {
  731. key.assign(b2, e2);
  732. } else {
  733. val.assign(b2, e2);
  734. }
  735. });
  736. dic.emplace(key, val);
  737. });
  738. EXPECT_EQ("val1", dic.find("key1")->second);
  739. EXPECT_EQ("val2", dic.find("key2")->second);
  740. EXPECT_EQ("val3", dic.find("key3")->second);
  741. }
  742. TEST(SplitTest, ParseInvalidQueryTests) {
  743. {
  744. string s = " ";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. {
  750. string s = " = =";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. }
  756. TEST(ParseQueryTest, ParseQueryString) {
  757. {
  758. std::string s = "key1=val1&key2=val2&key3=val3";
  759. Params dic;
  760. detail::parse_query_text(s, dic);
  761. EXPECT_EQ("val1", dic.find("key1")->second);
  762. EXPECT_EQ("val2", dic.find("key2")->second);
  763. EXPECT_EQ("val3", dic.find("key3")->second);
  764. }
  765. {
  766. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  767. Params dic;
  768. detail::parse_query_text(s, dic);
  769. EXPECT_EQ("", dic.find("key1")->second);
  770. EXPECT_EQ("val1", dic.find("key2")->second);
  771. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  772. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  773. }
  774. }
  775. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  776. Params dic;
  777. EXPECT_EQ(detail::params_to_query_str(dic), "");
  778. dic.emplace("key1", "val1");
  779. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  780. dic.emplace("key2", "val2");
  781. dic.emplace("key3", "val3");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  783. }
  784. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  785. string content_type = "multipart/form-data; boundary=something";
  786. string boundary;
  787. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(boundary, "something");
  790. }
  791. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  792. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  793. string boundary;
  794. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  795. EXPECT_TRUE(ret);
  796. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  797. }
  798. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  799. string content_type =
  800. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  801. string boundary;
  802. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  803. EXPECT_TRUE(ret);
  804. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  805. }
  806. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  807. string content_type =
  808. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  809. string boundary;
  810. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  811. EXPECT_TRUE(ret);
  812. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  813. }
  814. TEST(GetHeaderValueTest, DefaultValue) {
  815. Headers headers = {{"Dummy", "Dummy"}};
  816. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  817. EXPECT_STREQ("text/plain", val);
  818. }
  819. TEST(GetHeaderValueTest, DefaultValueInt) {
  820. Headers headers = {{"Dummy", "Dummy"}};
  821. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  822. EXPECT_EQ(100ull, val);
  823. }
  824. TEST(GetHeaderValueTest, RegularValue) {
  825. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  826. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  827. EXPECT_STREQ("text/html", val);
  828. }
  829. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  830. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  832. EXPECT_STREQ("text/html", val);
  833. }
  834. TEST(GetHeaderValueTest, SetContent) {
  835. Response res;
  836. res.set_content("html", "text/html");
  837. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  838. res.set_content("text", "text/plain");
  839. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  840. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  841. }
  842. TEST(GetHeaderValueTest, RegularValueInt) {
  843. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  845. EXPECT_EQ(100ull, val);
  846. }
  847. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  848. Headers headers = {{"Content-Length", "x"}};
  849. auto is_invalid_value = false;
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  851. is_invalid_value);
  852. EXPECT_EQ(0ull, val);
  853. EXPECT_TRUE(is_invalid_value);
  854. }
  855. TEST(GetHeaderValueTest, Range) {
  856. {
  857. Headers headers = {make_range_header({{1, -1}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=-1", val);
  865. }
  866. {
  867. Headers headers = {make_range_header({{1, 10}})};
  868. auto val = detail::get_header_value(headers, "Range", 0, 0);
  869. EXPECT_STREQ("bytes=1-10", val);
  870. }
  871. {
  872. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  873. auto val = detail::get_header_value(headers, "Range", 0, 0);
  874. EXPECT_STREQ("bytes=1-10, 100-", val);
  875. }
  876. {
  877. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  878. auto val = detail::get_header_value(headers, "Range", 0, 0);
  879. EXPECT_STREQ("bytes=1-10, 100-200", val);
  880. }
  881. {
  882. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  883. auto val = detail::get_header_value(headers, "Range", 0, 0);
  884. EXPECT_STREQ("bytes=0-0, -1", val);
  885. }
  886. }
  887. TEST(ParseHeaderValueTest, Range) {
  888. {
  889. Ranges ranges;
  890. auto ret = detail::parse_range_header("bytes=1-", ranges);
  891. EXPECT_TRUE(ret);
  892. EXPECT_EQ(1u, ranges.size());
  893. EXPECT_EQ(1u, ranges[0].first);
  894. EXPECT_EQ(-1, ranges[0].second);
  895. }
  896. {
  897. Ranges ranges;
  898. auto ret = detail::parse_range_header("bytes=-1", ranges);
  899. EXPECT_TRUE(ret);
  900. EXPECT_EQ(1u, ranges.size());
  901. EXPECT_EQ(-1, ranges[0].first);
  902. EXPECT_EQ(1u, ranges[0].second);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(1u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. }
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  915. EXPECT_FALSE(ret);
  916. }
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(2u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(-1, ranges[1].second);
  926. }
  927. {
  928. Ranges ranges;
  929. auto ret =
  930. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(3u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. EXPECT_EQ(100u, ranges[1].first);
  936. EXPECT_EQ(200u, ranges[1].second);
  937. EXPECT_EQ(300u, ranges[2].first);
  938. EXPECT_EQ(400u, ranges[2].second);
  939. }
  940. {
  941. Ranges ranges;
  942. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  955. EXPECT_TRUE(ranges.empty());
  956. }
  957. }
  958. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  966. #else
  967. EXPECT_TRUE(ret == detail::EncodingType::None);
  968. #endif
  969. }
  970. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  971. Request req;
  972. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  973. Response res;
  974. res.set_header("Content-Type", "text/plain");
  975. auto ret = detail::encoding_type(req, res);
  976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  978. #elif CPPHTTPLIB_ZLIB_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  980. #elif CPPHTTPLIB_ZSTD_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  982. #else
  983. EXPECT_TRUE(ret == detail::EncodingType::None);
  984. #endif
  985. }
  986. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  987. Request req;
  988. req.set_header("Accept-Encoding",
  989. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  995. #elif CPPHTTPLIB_ZLIB_SUPPORT
  996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  997. #elif CPPHTTPLIB_ZSTD_SUPPORT
  998. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  999. #else
  1000. EXPECT_TRUE(ret == detail::EncodingType::None);
  1001. #endif
  1002. }
  1003. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1004. // All supported encodings rejected with q=0 should return None
  1005. Request req;
  1006. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1007. Response res;
  1008. res.set_header("Content-Type", "text/plain");
  1009. auto ret = detail::encoding_type(req, res);
  1010. EXPECT_TRUE(ret == detail::EncodingType::None);
  1011. }
  1012. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1013. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1014. Request req;
  1015. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1016. Response res;
  1017. res.set_header("Content-Type", "text/plain");
  1018. auto ret = detail::encoding_type(req, res);
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. }
  1021. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1022. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1023. Request req;
  1024. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1025. Response res;
  1026. res.set_header("Content-Type", "text/plain");
  1027. auto ret = detail::encoding_type(req, res);
  1028. EXPECT_TRUE(ret == detail::EncodingType::None);
  1029. }
  1030. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1031. // RFC 7231: Accept-Encoding values are case-insensitive
  1032. Request req;
  1033. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1034. Response res;
  1035. res.set_header("Content-Type", "text/plain");
  1036. auto ret = detail::encoding_type(req, res);
  1037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1043. #else
  1044. EXPECT_TRUE(ret == detail::EncodingType::None);
  1045. #endif
  1046. }
  1047. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1048. // q value should determine priority, not hardcoded order
  1049. Request req;
  1050. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1051. Response res;
  1052. res.set_header("Content-Type", "text/plain");
  1053. auto ret = detail::encoding_type(req, res);
  1054. // gzip has highest q=1.0, so it should be selected even though
  1055. // br and zstd are also supported
  1056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1060. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1062. #else
  1063. EXPECT_TRUE(ret == detail::EncodingType::None);
  1064. #endif
  1065. }
  1066. TEST(BufferStreamTest, read) {
  1067. detail::BufferStream strm1;
  1068. Stream &strm = strm1;
  1069. EXPECT_EQ(5, strm.write("hello"));
  1070. char buf[512];
  1071. EXPECT_EQ(2, strm.read(buf, 2));
  1072. EXPECT_EQ('h', buf[0]);
  1073. EXPECT_EQ('e', buf[1]);
  1074. EXPECT_EQ(2, strm.read(buf, 2));
  1075. EXPECT_EQ('l', buf[0]);
  1076. EXPECT_EQ('l', buf[1]);
  1077. EXPECT_EQ(1, strm.read(buf, 1));
  1078. EXPECT_EQ('o', buf[0]);
  1079. EXPECT_EQ(0, strm.read(buf, 1));
  1080. }
  1081. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1082. auto host = "www.httpwatch.com";
  1083. auto ip = hosted_at(host);
  1084. EXPECT_EQ("23.96.13.243", ip);
  1085. std::vector<std::string> addrs;
  1086. hosted_at(host, addrs);
  1087. EXPECT_EQ(1u, addrs.size());
  1088. }
  1089. #if 0 // It depends on each test environment...
  1090. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1091. auto host = "www.youtube.com";
  1092. std::vector<std::string> addrs;
  1093. hosted_at(host, addrs);
  1094. EXPECT_EQ(20u, addrs.size());
  1095. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1096. EXPECT_TRUE(it != addrs.end());
  1097. }
  1098. #endif
  1099. class ChunkedEncodingTest : public ::testing::Test {
  1100. protected:
  1101. ChunkedEncodingTest()
  1102. : cli_(HOST, PORT)
  1103. #ifdef CPPHTTPLIB_SSL_ENABLED
  1104. ,
  1105. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1106. #endif
  1107. {
  1108. cli_.set_connection_timeout(2);
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. cli_.enable_server_certificate_verification(false);
  1111. #endif
  1112. }
  1113. virtual void SetUp() {
  1114. read_file("./image.jpg", image_data_);
  1115. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. svr_.Get(
  1119. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1120. res.set_chunked_content_provider(
  1121. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1122. size_t remaining = image_data_.size() - offset;
  1123. if (remaining == 0) {
  1124. sink.done();
  1125. } else {
  1126. constexpr size_t CHUNK_SIZE = 1024;
  1127. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1128. sink.write(&image_data_[offset], send_size);
  1129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1130. }
  1131. return true;
  1132. });
  1133. });
  1134. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1135. svr_.wait_until_ready();
  1136. }
  1137. virtual void TearDown() {
  1138. svr_.stop();
  1139. if (!request_threads_.empty()) {
  1140. std::this_thread::sleep_for(std::chrono::seconds(1));
  1141. for (auto &t : request_threads_) {
  1142. t.join();
  1143. }
  1144. }
  1145. t_.join();
  1146. }
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. SSLClient cli_;
  1149. SSLServer svr_;
  1150. #else
  1151. Client cli_;
  1152. Server svr_;
  1153. #endif
  1154. thread t_;
  1155. std::vector<thread> request_threads_;
  1156. std::string image_data_;
  1157. };
  1158. TEST_F(ChunkedEncodingTest, NormalGet) {
  1159. auto res = cli_.Get("/chunked");
  1160. ASSERT_TRUE(res);
  1161. std::string out;
  1162. read_file("./image.jpg", out);
  1163. EXPECT_EQ(StatusCode::OK_200, res->status);
  1164. EXPECT_EQ(out, res->body);
  1165. }
  1166. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1167. std::string body;
  1168. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1169. body.append(data, data_length);
  1170. return true;
  1171. });
  1172. ASSERT_TRUE(res);
  1173. std::string out;
  1174. read_file("./image.jpg", out);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. EXPECT_EQ(out, body);
  1177. }
  1178. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1179. std::string body;
  1180. auto res = cli_.Get(
  1181. "/chunked",
  1182. [&](const Response &response) {
  1183. EXPECT_EQ(StatusCode::OK_200, response.status);
  1184. return true;
  1185. },
  1186. [&](const char *data, size_t data_length) {
  1187. body.append(data, data_length);
  1188. return true;
  1189. });
  1190. ASSERT_TRUE(res);
  1191. std::string out;
  1192. read_file("./image.jpg", out);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. EXPECT_EQ(out, body);
  1195. }
  1196. TEST(RangeTest, FromHTTPBin_Online) {
  1197. auto host = "httpbingo.org";
  1198. auto path = std::string{"/range/32"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(5);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_TRUE(res);
  1210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. }
  1213. {
  1214. Headers headers = {make_range_header({{1, -1}})};
  1215. auto res = cli.Get(path, headers);
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1219. }
  1220. {
  1221. Headers headers = {make_range_header({{1, 10}})};
  1222. auto res = cli.Get(path, headers);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("bcdefghijk", res->body);
  1225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1226. }
  1227. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1228. // entire resource, while the original httpbin returned 200. Both are
  1229. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1230. {
  1231. Headers headers = {make_range_header({{0, 31}})};
  1232. auto res = cli.Get(path, headers);
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1235. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1236. res->status == StatusCode::PartialContent_206);
  1237. }
  1238. {
  1239. Headers headers = {make_range_header({{0, -1}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1243. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1244. res->status == StatusCode::PartialContent_206);
  1245. }
  1246. // go-httpbin returns 206 with clamped range for over-range requests,
  1247. // while the original httpbin returned 416. Both behaviors are observed
  1248. // in real servers, so we only verify the request succeeds.
  1249. {
  1250. Headers headers = {make_range_header({{0, 32}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. }
  1254. }
  1255. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1256. auto host = "unresolvableaddress.local";
  1257. auto path = std::string{"/"};
  1258. #ifdef CPPHTTPLIB_SSL_ENABLED
  1259. auto port = 443;
  1260. SSLClient cli(host, port);
  1261. #else
  1262. auto port = 80;
  1263. Client cli(host, port);
  1264. #endif
  1265. cli.set_connection_timeout(1);
  1266. {
  1267. auto res = cli.Get(path);
  1268. ASSERT_FALSE(res);
  1269. }
  1270. std::this_thread::sleep_for(std::chrono::seconds(8));
  1271. }
  1272. #if defined(__linux__) && defined(__GLIBC__) && \
  1273. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1274. // Forward declaration: in split builds split.py strips `inline` and moves the
  1275. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1276. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1277. // against the symbol in both header-only and split builds.
  1278. namespace httplib {
  1279. namespace detail {
  1280. int getaddrinfo_with_timeout(const char *node, const char *service,
  1281. const struct addrinfo *hints,
  1282. struct addrinfo **res, time_t timeout_sec);
  1283. } // namespace detail
  1284. } // namespace httplib
  1285. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1286. //
  1287. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1288. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1289. // gai_suspend() call hits the connection timeout the function calls
  1290. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1291. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1292. // still alive and still references the now-destroyed stack frame.
  1293. //
  1294. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1295. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1296. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1297. // and runs them in a container.
  1298. namespace {
  1299. bool should_run_issue_2431_tests() {
  1300. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1301. return v && *v && std::string(v) != "0";
  1302. }
  1303. std::string unique_unresolvable_host(int n) {
  1304. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1305. // glibc still asks the configured nameserver — which is exactly the path
  1306. // we want to exercise. A unique label per call avoids the resolver cache.
  1307. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1308. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1309. std::to_string(n) + ".invalid";
  1310. }
  1311. } // namespace
  1312. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1313. if (!should_run_issue_2431_tests()) {
  1314. GTEST_SKIP()
  1315. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1316. }
  1317. for (int i = 0; i < 8; ++i) {
  1318. struct addrinfo hints;
  1319. memset(&hints, 0, sizeof(hints));
  1320. hints.ai_family = AF_UNSPEC;
  1321. hints.ai_socktype = SOCK_STREAM;
  1322. auto host = unique_unresolvable_host(i);
  1323. struct addrinfo *result = nullptr;
  1324. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1325. &result, /*timeout_sec=*/1);
  1326. if (rc == 0 && result) { freeaddrinfo(result); }
  1327. }
  1328. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1329. // stack region they still believe holds their gaicb.
  1330. std::this_thread::sleep_for(std::chrono::seconds(3));
  1331. }
  1332. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1333. if (!should_run_issue_2431_tests()) {
  1334. GTEST_SKIP()
  1335. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1336. }
  1337. std::atomic<bool> stop{false};
  1338. std::vector<std::thread> threads;
  1339. for (int t = 0; t < 8; ++t) {
  1340. threads.emplace_back([t, &stop] {
  1341. int i = 0;
  1342. while (!stop.load(std::memory_order_relaxed)) {
  1343. struct addrinfo hints;
  1344. memset(&hints, 0, sizeof(hints));
  1345. hints.ai_family = AF_UNSPEC;
  1346. hints.ai_socktype = SOCK_STREAM;
  1347. auto host = unique_unresolvable_host(t * 100000 + i++);
  1348. struct addrinfo *result = nullptr;
  1349. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1350. &result, /*timeout_sec=*/1);
  1351. if (rc == 0 && result) { freeaddrinfo(result); }
  1352. }
  1353. });
  1354. }
  1355. std::this_thread::sleep_for(std::chrono::seconds(8));
  1356. stop.store(true, std::memory_order_relaxed);
  1357. for (auto &th : threads) {
  1358. th.join();
  1359. }
  1360. std::this_thread::sleep_for(std::chrono::seconds(3));
  1361. }
  1362. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1363. if (!should_run_issue_2431_tests()) {
  1364. GTEST_SKIP()
  1365. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1366. }
  1367. std::atomic<bool> stop{false};
  1368. std::vector<std::thread> threads;
  1369. for (int t = 0; t < 8; ++t) {
  1370. threads.emplace_back([t, &stop] {
  1371. int i = 0;
  1372. while (!stop.load(std::memory_order_relaxed)) {
  1373. auto host = unique_unresolvable_host(t * 100000 + i++);
  1374. Client cli(host, 80);
  1375. cli.set_connection_timeout(1, 0);
  1376. cli.set_read_timeout(1, 0);
  1377. cli.set_write_timeout(1, 0);
  1378. (void)cli.Get("/");
  1379. }
  1380. });
  1381. }
  1382. std::this_thread::sleep_for(std::chrono::seconds(8));
  1383. stop.store(true, std::memory_order_relaxed);
  1384. for (auto &th : threads) {
  1385. th.join();
  1386. }
  1387. std::this_thread::sleep_for(std::chrono::seconds(3));
  1388. }
  1389. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1390. TEST(ConnectionErrorTest, InvalidHost) {
  1391. auto host = "-abcde.com";
  1392. #ifdef CPPHTTPLIB_SSL_ENABLED
  1393. auto port = 443;
  1394. SSLClient cli(host, port);
  1395. #else
  1396. auto port = 80;
  1397. Client cli(host, port);
  1398. #endif
  1399. cli.set_connection_timeout(std::chrono::seconds(2));
  1400. auto res = cli.Get("/");
  1401. ASSERT_TRUE(!res);
  1402. EXPECT_EQ(Error::Connection, res.error());
  1403. }
  1404. TEST(ConnectionErrorTest, InvalidHost2) {
  1405. auto host = "httpcan.org/";
  1406. #ifdef CPPHTTPLIB_SSL_ENABLED
  1407. SSLClient cli(host);
  1408. #else
  1409. Client cli(host);
  1410. #endif
  1411. cli.set_connection_timeout(std::chrono::seconds(2));
  1412. auto res = cli.Get("/");
  1413. ASSERT_TRUE(!res);
  1414. EXPECT_EQ(Error::Connection, res.error());
  1415. }
  1416. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1417. auto host = "httpcan.org/";
  1418. #ifdef CPPHTTPLIB_SSL_ENABLED
  1419. SSLClient cli(host);
  1420. #else
  1421. Client cli(host);
  1422. #endif
  1423. cli.set_connection_timeout(std::chrono::seconds(2));
  1424. auto res = cli.Get("/");
  1425. ASSERT_TRUE(!res);
  1426. stringstream s;
  1427. s << "error code: " << res.error();
  1428. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1429. }
  1430. TEST(ConnectionErrorTest, InvalidPort) {
  1431. auto host = "localhost";
  1432. auto port = 44380;
  1433. #ifdef CPPHTTPLIB_SSL_ENABLED
  1434. SSLClient cli(host, port);
  1435. #else
  1436. Client cli(host, port);
  1437. #endif
  1438. cli.set_connection_timeout(std::chrono::seconds(2));
  1439. auto res = cli.Get("/");
  1440. ASSERT_TRUE(!res);
  1441. EXPECT_TRUE(Error::Connection == res.error() ||
  1442. Error::ConnectionTimeout == res.error());
  1443. }
  1444. TEST(ConnectionErrorTest, Timeout_Online) {
  1445. auto host = "google.com";
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 44380;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 8080;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(std::chrono::seconds(2));
  1454. // only probe one address type so that the error reason
  1455. // correlates to the timed-out IPv4, not the unsupported
  1456. // IPv6 connection attempt
  1457. cli.set_address_family(AF_INET);
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1461. }
  1462. TEST(CancelTest, NoCancel_Online) {
  1463. auto host = "httpbingo.org";
  1464. auto path = std::string{"/range/32"};
  1465. #ifdef CPPHTTPLIB_SSL_ENABLED
  1466. auto port = 443;
  1467. SSLClient cli(host, port);
  1468. #else
  1469. auto port = 80;
  1470. Client cli(host, port);
  1471. #endif
  1472. cli.set_connection_timeout(std::chrono::seconds(5));
  1473. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1479. // Use /bytes with a large payload so that the DownloadProgress callback
  1480. // (which only fires for Content-Length responses) is invoked before the
  1481. // entire body is received, giving cancellation a chance to fire.
  1482. auto host = "httpbingo.org";
  1483. auto path = std::string{"/bytes/524288"};
  1484. #ifdef CPPHTTPLIB_SSL_ENABLED
  1485. auto port = 443;
  1486. SSLClient cli(host, port);
  1487. #else
  1488. auto port = 80;
  1489. Client cli(host, port);
  1490. #endif
  1491. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. ASSERT_TRUE(!res);
  1494. EXPECT_EQ(Error::Canceled, res.error());
  1495. }
  1496. TEST(CancelTest, WithCancelLargePayload_Online) {
  1497. auto host = "httpbingo.org";
  1498. auto path = std::string{"/bytes/524288"};
  1499. #ifdef CPPHTTPLIB_SSL_ENABLED
  1500. auto port = 443;
  1501. SSLClient cli(host, port);
  1502. #else
  1503. auto port = 80;
  1504. Client cli(host, port);
  1505. #endif
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. uint32_t count = 0;
  1508. auto res =
  1509. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelPost) {
  1514. Server svr;
  1515. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1535. Server svr;
  1536. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadPost) {
  1555. Server svr;
  1556. svr.set_payload_max_length(200 * 1024 * 1024);
  1557. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content(LARGE_DATA, "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_payload_max_length(200 * 1024 * 1024);
  1569. cli.set_connection_timeout(std::chrono::seconds(5));
  1570. auto res =
  1571. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1572. "application/json", [](uint64_t, uint64_t) { return false; });
  1573. ASSERT_TRUE(!res);
  1574. EXPECT_EQ(Error::Canceled, res.error());
  1575. }
  1576. TEST(CancelTest, NoCancelPut) {
  1577. Server svr;
  1578. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content("Hello World!", "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_connection_timeout(std::chrono::seconds(5));
  1590. auto res =
  1591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1592. "application/json", [](uint64_t, uint64_t) { return true; });
  1593. ASSERT_TRUE(res);
  1594. EXPECT_EQ("Hello World!", res->body);
  1595. EXPECT_EQ(StatusCode::OK_200, res->status);
  1596. }
  1597. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1598. Server svr;
  1599. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1600. res.set_content("Hello World!", "text/plain");
  1601. });
  1602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. thread.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. Client cli(HOST, PORT);
  1610. cli.set_connection_timeout(std::chrono::seconds(5));
  1611. auto res =
  1612. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1613. "application/json", [](uint64_t, uint64_t) { return false; });
  1614. ASSERT_TRUE(!res);
  1615. EXPECT_EQ(Error::Canceled, res.error());
  1616. }
  1617. TEST(CancelTest, WithCancelLargePayloadPut) {
  1618. Server svr;
  1619. svr.set_payload_max_length(200 * 1024 * 1024);
  1620. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1621. res.set_content(LARGE_DATA, "text/plain");
  1622. });
  1623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1624. auto se = detail::scope_exit([&] {
  1625. svr.stop();
  1626. thread.join();
  1627. ASSERT_FALSE(svr.is_running());
  1628. });
  1629. svr.wait_until_ready();
  1630. Client cli(HOST, PORT);
  1631. cli.set_payload_max_length(200 * 1024 * 1024);
  1632. cli.set_connection_timeout(std::chrono::seconds(5));
  1633. auto res =
  1634. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1635. "application/json", [](uint64_t, uint64_t) { return false; });
  1636. ASSERT_TRUE(!res);
  1637. EXPECT_EQ(Error::Canceled, res.error());
  1638. }
  1639. TEST(CancelTest, NoCancelPatch) {
  1640. Server svr;
  1641. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1642. res.set_content("Hello World!", "text/plain");
  1643. });
  1644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1645. auto se = detail::scope_exit([&] {
  1646. svr.stop();
  1647. thread.join();
  1648. ASSERT_FALSE(svr.is_running());
  1649. });
  1650. svr.wait_until_ready();
  1651. Client cli(HOST, PORT);
  1652. cli.set_connection_timeout(std::chrono::seconds(5));
  1653. auto res =
  1654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1655. "application/json", [](uint64_t, uint64_t) { return true; });
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ("Hello World!", res->body);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1661. Server svr;
  1662. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1663. res.set_content("Hello World!", "text/plain");
  1664. });
  1665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1666. auto se = detail::scope_exit([&] {
  1667. svr.stop();
  1668. thread.join();
  1669. ASSERT_FALSE(svr.is_running());
  1670. });
  1671. svr.wait_until_ready();
  1672. Client cli(HOST, PORT);
  1673. cli.set_connection_timeout(std::chrono::seconds(5));
  1674. auto res =
  1675. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1676. "application/json", [](uint64_t, uint64_t) { return false; });
  1677. ASSERT_TRUE(!res);
  1678. EXPECT_EQ(Error::Canceled, res.error());
  1679. }
  1680. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1681. Server svr;
  1682. svr.set_payload_max_length(200 * 1024 * 1024);
  1683. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1684. res.set_content(LARGE_DATA, "text/plain");
  1685. });
  1686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. thread.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. Client cli(HOST, PORT);
  1694. cli.set_payload_max_length(200 * 1024 * 1024);
  1695. cli.set_connection_timeout(std::chrono::seconds(5));
  1696. auto res =
  1697. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1698. "application/json", [](uint64_t, uint64_t) { return false; });
  1699. ASSERT_TRUE(!res);
  1700. EXPECT_EQ(Error::Canceled, res.error());
  1701. }
  1702. TEST(CancelTest, NoCancelDelete) {
  1703. Server svr;
  1704. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1705. res.set_content("Hello World!", "text/plain");
  1706. });
  1707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1708. auto se = detail::scope_exit([&] {
  1709. svr.stop();
  1710. thread.join();
  1711. ASSERT_FALSE(svr.is_running());
  1712. });
  1713. svr.wait_until_ready();
  1714. Client cli(HOST, PORT);
  1715. cli.set_connection_timeout(std::chrono::seconds(5));
  1716. auto res =
  1717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1718. "application/json", [](uint64_t, uint64_t) { return true; });
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ("Hello World!", res->body);
  1721. EXPECT_EQ(StatusCode::OK_200, res->status);
  1722. }
  1723. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1724. Server svr;
  1725. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1726. res.set_content("Hello World!", "text/plain");
  1727. });
  1728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1729. auto se = detail::scope_exit([&] {
  1730. svr.stop();
  1731. thread.join();
  1732. ASSERT_FALSE(svr.is_running());
  1733. });
  1734. svr.wait_until_ready();
  1735. Client cli(HOST, PORT);
  1736. cli.set_connection_timeout(std::chrono::seconds(5));
  1737. auto res =
  1738. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1739. "application/json", [](uint64_t, uint64_t) { return false; });
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1744. Server svr;
  1745. svr.set_payload_max_length(200 * 1024 * 1024);
  1746. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content(LARGE_DATA, "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. Client cli(HOST, PORT);
  1757. cli.set_payload_max_length(200 * 1024 * 1024);
  1758. cli.set_connection_timeout(std::chrono::seconds(5));
  1759. auto res =
  1760. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1761. "application/json", [](uint64_t, uint64_t) { return false; });
  1762. ASSERT_TRUE(!res);
  1763. EXPECT_EQ(Error::Canceled, res.error());
  1764. }
  1765. static std::string remove_whitespace(const std::string &input) {
  1766. std::string output;
  1767. output.reserve(input.size());
  1768. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1769. [](unsigned char c) { return !std::isspace(c); });
  1770. return output;
  1771. }
  1772. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1773. auto host = "httpbingo.org";
  1774. auto path = std::string{"/basic-auth/hello/world"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. {
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1786. }
  1787. {
  1788. auto res =
  1789. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1790. ASSERT_TRUE(res);
  1791. auto body = remove_whitespace(res->body);
  1792. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1793. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. {
  1797. cli.set_basic_auth("hello", "world");
  1798. auto res = cli.Get(path);
  1799. ASSERT_TRUE(res);
  1800. auto body = remove_whitespace(res->body);
  1801. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1802. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1803. EXPECT_EQ(StatusCode::OK_200, res->status);
  1804. }
  1805. {
  1806. cli.set_basic_auth("hello", "bad");
  1807. auto res = cli.Get(path);
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1810. }
  1811. {
  1812. cli.set_basic_auth("bad", "world");
  1813. auto res = cli.Get(path);
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1816. }
  1817. }
  1818. #ifdef CPPHTTPLIB_SSL_ENABLED
  1819. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1820. auto host = "httpbingo.org";
  1821. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1822. auto paths = std::vector<std::string>{
  1823. "/digest-auth/auth/hello/world/MD5",
  1824. "/digest-auth/auth/hello/world/SHA-256",
  1825. };
  1826. auto port = 443;
  1827. SSLClient cli(host, port);
  1828. {
  1829. auto res = cli.Get(unauth_path);
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1832. }
  1833. {
  1834. cli.set_digest_auth("hello", "world");
  1835. for (const auto &path : paths) {
  1836. auto res = cli.Get(path.c_str());
  1837. ASSERT_TRUE(res);
  1838. auto body = remove_whitespace(res->body);
  1839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. cli.set_digest_auth("hello", "bad");
  1844. for (const auto &path : paths) {
  1845. auto res = cli.Get(path.c_str());
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1848. }
  1849. }
  1850. }
  1851. #endif
  1852. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1853. auto host = "google.com";
  1854. auto another_host = "example.com";
  1855. auto wrong_ip = "0.0.0.0";
  1856. #ifdef CPPHTTPLIB_SSL_ENABLED
  1857. SSLClient cli(host);
  1858. #else
  1859. Client cli(host);
  1860. #endif
  1861. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1862. auto res = cli.Get("/");
  1863. ASSERT_TRUE(res);
  1864. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1865. }
  1866. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1867. auto host = "google.com";
  1868. auto wrong_ip = "0.0.0.0";
  1869. #ifdef CPPHTTPLIB_SSL_ENABLED
  1870. SSLClient cli(host);
  1871. #else
  1872. Client cli(host);
  1873. #endif
  1874. cli.set_hostname_addr_map({{host, wrong_ip}});
  1875. auto res = cli.Get("/");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::Connection, res.error());
  1878. }
  1879. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1880. auto host = "httpbingo.org";
  1881. auto path = std::string{"/absolute-redirect/3"};
  1882. #ifdef CPPHTTPLIB_SSL_ENABLED
  1883. SSLClient cli(host);
  1884. #else
  1885. Client cli(host);
  1886. #endif
  1887. cli.set_follow_location(true);
  1888. auto res = cli.Get(path);
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::OK_200, res->status);
  1891. }
  1892. TEST(RedirectTest, Redirect_Online) {
  1893. auto host = "httpbingo.org";
  1894. auto path = std::string{"/redirect/3"};
  1895. #ifdef CPPHTTPLIB_SSL_ENABLED
  1896. SSLClient cli(host);
  1897. #else
  1898. Client cli(host);
  1899. #endif
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get(path);
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. }
  1905. TEST(RelativeRedirectTest, Redirect_Online) {
  1906. auto host = "httpbingo.org";
  1907. auto path = std::string{"/relative-redirect/3"};
  1908. #ifdef CPPHTTPLIB_SSL_ENABLED
  1909. SSLClient cli(host);
  1910. #else
  1911. Client cli(host);
  1912. #endif
  1913. cli.set_follow_location(true);
  1914. auto res = cli.Get(path);
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::OK_200, res->status);
  1917. }
  1918. TEST(TooManyRedirectTest, Redirect_Online) {
  1919. auto host = "httpbingo.org";
  1920. auto path = std::string{"/redirect/21"};
  1921. #ifdef CPPHTTPLIB_SSL_ENABLED
  1922. SSLClient cli(host);
  1923. #else
  1924. Client cli(host);
  1925. #endif
  1926. cli.set_follow_location(true);
  1927. auto res = cli.Get(path);
  1928. ASSERT_TRUE(!res);
  1929. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1930. }
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. TEST(YahooRedirectTest, Redirect_Online) {
  1933. Client cli("yahoo.com");
  1934. auto res = cli.Get("/");
  1935. ASSERT_TRUE(res);
  1936. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1937. cli.set_follow_location(true);
  1938. res = cli.Get("/");
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(StatusCode::OK_200, res->status);
  1941. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1942. }
  1943. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1944. #define REDIR_HOST "httpbingo.org"
  1945. #define REDIR_PATH "/redirect-to"
  1946. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1947. SSLClient cli(REDIR_HOST);
  1948. cli.set_follow_location(true);
  1949. auto res =
  1950. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. }
  1954. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1955. SSLClient cli(REDIR_HOST);
  1956. cli.set_follow_location(true);
  1957. Params params;
  1958. params.emplace("url", "http://example.com");
  1959. params.emplace("status_code", "302");
  1960. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. }
  1964. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1965. SSLClient cli(REDIR_HOST);
  1966. cli.set_follow_location(true);
  1967. Params params;
  1968. params.emplace("url", "http://example.com");
  1969. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. }
  1973. TEST(UrlWithSpace, Redirect_Online) {
  1974. SSLClient cli("edge.forgecdn.net");
  1975. cli.set_follow_location(true);
  1976. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(StatusCode::OK_200, res->status);
  1979. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1980. }
  1981. #endif
  1982. #if !defined(_WIN32) && !defined(_WIN64)
  1983. TEST(ReceiveSignals, Signal) {
  1984. auto setupSignalHandlers = []() {
  1985. struct sigaction act;
  1986. sigemptyset(&act.sa_mask);
  1987. act.sa_flags = SA_SIGINFO;
  1988. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1989. switch (sig) {
  1990. case SIGINT:
  1991. default: break;
  1992. }
  1993. };
  1994. ::sigaction(SIGINT, &act, nullptr);
  1995. };
  1996. Server svr;
  1997. int port = 0;
  1998. auto thread = std::thread([&]() {
  1999. setupSignalHandlers();
  2000. port = svr.bind_to_any_port(HOST);
  2001. svr.listen_after_bind();
  2002. });
  2003. auto se = detail::scope_exit([&] {
  2004. svr.stop();
  2005. thread.join();
  2006. ASSERT_FALSE(svr.is_running());
  2007. });
  2008. svr.wait_until_ready();
  2009. ASSERT_TRUE(svr.is_running());
  2010. pthread_kill(thread.native_handle(), SIGINT);
  2011. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2012. ASSERT_TRUE(svr.is_running());
  2013. }
  2014. #endif
  2015. TEST(RedirectToDifferentPort, Redirect) {
  2016. Server svr1;
  2017. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. int svr1_port = 0;
  2021. auto thread1 = std::thread([&]() {
  2022. svr1_port = svr1.bind_to_any_port(HOST);
  2023. svr1.listen_after_bind();
  2024. });
  2025. Server svr2;
  2026. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2027. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2028. });
  2029. int svr2_port = 0;
  2030. auto thread2 = std::thread([&]() {
  2031. svr2_port = svr2.bind_to_any_port(HOST);
  2032. svr2.listen_after_bind();
  2033. });
  2034. auto se = detail::scope_exit([&] {
  2035. svr2.stop();
  2036. thread2.join();
  2037. svr1.stop();
  2038. thread1.join();
  2039. ASSERT_FALSE(svr2.is_running());
  2040. ASSERT_FALSE(svr1.is_running());
  2041. });
  2042. svr1.wait_until_ready();
  2043. svr2.wait_until_ready();
  2044. Client cli("localhost", svr2_port);
  2045. cli.set_follow_location(true);
  2046. auto res = cli.Get("/2");
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::OK_200, res->status);
  2049. EXPECT_EQ("Hello World!", res->body);
  2050. }
  2051. static void
  2052. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2053. Server svr1;
  2054. std::string captured_authorization;
  2055. svr1.Get("/target", [&](const Request &req, Response &res) {
  2056. captured_authorization = req.get_header_value("Authorization");
  2057. res.set_content("OK", "text/plain");
  2058. });
  2059. int svr1_port = 0;
  2060. auto thread1 = std::thread([&]() {
  2061. svr1_port = svr1.bind_to_any_port(HOST);
  2062. svr1.listen_after_bind();
  2063. });
  2064. Server svr2;
  2065. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2066. res.set_redirect(
  2067. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2068. });
  2069. int svr2_port = 0;
  2070. auto thread2 = std::thread([&]() {
  2071. svr2_port = svr2.bind_to_any_port(HOST);
  2072. svr2.listen_after_bind();
  2073. });
  2074. auto se = detail::scope_exit([&] {
  2075. svr2.stop();
  2076. thread2.join();
  2077. svr1.stop();
  2078. thread1.join();
  2079. ASSERT_FALSE(svr2.is_running());
  2080. ASSERT_FALSE(svr1.is_running());
  2081. });
  2082. svr1.wait_until_ready();
  2083. svr2.wait_until_ready();
  2084. Client cli("localhost", svr2_port);
  2085. cli.set_follow_location(true);
  2086. set_auth(cli);
  2087. auto res = cli.Get("/redir");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2091. EXPECT_TRUE(captured_authorization.empty());
  2092. }
  2093. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2094. TestDoNotForwardCredentialsOnRedirect(
  2095. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2096. }
  2097. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2098. TestDoNotForwardCredentialsOnRedirect(
  2099. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2100. }
  2101. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2102. Server svr;
  2103. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2104. // Port number that overflows int — should not crash
  2105. res.set_redirect("http://localhost:99999999999999999999/target");
  2106. });
  2107. auto port = svr.bind_to_any_port(HOST);
  2108. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2109. auto se = detail::scope_exit([&] {
  2110. svr.stop();
  2111. thread.join();
  2112. ASSERT_FALSE(svr.is_running());
  2113. });
  2114. svr.wait_until_ready();
  2115. Client cli(HOST, port);
  2116. cli.set_follow_location(true);
  2117. auto res = cli.Get("/redir");
  2118. // Should fail gracefully, not crash (no valid response due to bad port)
  2119. EXPECT_FALSE(res);
  2120. }
  2121. TEST(RedirectFromPageWithContent, Redirect) {
  2122. Server svr;
  2123. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2124. res.set_content("___", "text/plain");
  2125. res.set_redirect("/2");
  2126. });
  2127. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2128. res.set_content("Hello World!", "text/plain");
  2129. });
  2130. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2131. auto se = detail::scope_exit([&] {
  2132. svr.stop();
  2133. th.join();
  2134. ASSERT_FALSE(svr.is_running());
  2135. });
  2136. svr.wait_until_ready();
  2137. {
  2138. Client cli("localhost", PORT);
  2139. cli.set_follow_location(true);
  2140. std::string body;
  2141. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2142. body.append(data, data_length);
  2143. return true;
  2144. });
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. EXPECT_EQ("Hello World!", body);
  2148. }
  2149. {
  2150. Client cli("localhost", PORT);
  2151. std::string body;
  2152. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2153. body.append(data, data_length);
  2154. return true;
  2155. });
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(StatusCode::Found_302, res->status);
  2158. EXPECT_EQ("___", body);
  2159. }
  2160. }
  2161. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2162. Server svr;
  2163. auto port_str = std::to_string(PORT);
  2164. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2165. auto expected_host = "[::1]:" + port_str;
  2166. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2167. res.set_content("___", "text/plain");
  2168. // res.set_redirect("/2");
  2169. res.set_redirect(redirect_url);
  2170. });
  2171. svr.Get("/2", [&](const Request &req, Response &res) {
  2172. auto host_header = req.headers.find("Host");
  2173. ASSERT_TRUE(host_header != req.headers.end());
  2174. EXPECT_EQ(expected_host, host_header->second);
  2175. res.set_content("Hello World!", "text/plain");
  2176. });
  2177. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. th.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2184. // actually starts anything, so the condition !svr.is_running() will
  2185. // always remain true, and the loop never stops.
  2186. // This basically counts how many milliseconds have passed since the
  2187. // call to svr.listen(), and if after 5 seconds nothing started yet
  2188. // aborts the test.
  2189. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2191. ASSERT_LT(milliseconds, 5000U);
  2192. }
  2193. {
  2194. Client cli("::1", PORT);
  2195. cli.set_follow_location(true);
  2196. std::string body;
  2197. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2198. body.append(data, data_length);
  2199. return true;
  2200. });
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::OK_200, res->status);
  2203. EXPECT_EQ("Hello World!", body);
  2204. }
  2205. {
  2206. Client cli("::1", PORT);
  2207. std::string body;
  2208. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2209. body.append(data, data_length);
  2210. return true;
  2211. });
  2212. ASSERT_TRUE(res);
  2213. EXPECT_EQ(StatusCode::Found_302, res->status);
  2214. EXPECT_EQ("___", body);
  2215. }
  2216. }
  2217. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2218. Server svr;
  2219. svr.Get("/foo", [](const Request &req, Response &res) {
  2220. auto a = req.params.find("a");
  2221. if (a != req.params.end()) {
  2222. res.set_content((*a).second, "text/plain");
  2223. res.status = StatusCode::OK_200;
  2224. } else {
  2225. res.status = StatusCode::BadRequest_400;
  2226. }
  2227. });
  2228. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. thread.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. {
  2236. Client cli(HOST, PORT);
  2237. cli.set_path_encode(false);
  2238. auto res = cli.Get("/foo?a=explicitly+encoded");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. // This expects it back with a space, as the `+` won't have been
  2242. // url-encoded, and server-side the params get decoded turning `+`
  2243. // into spaces.
  2244. EXPECT_EQ("explicitly encoded", res->body);
  2245. }
  2246. }
  2247. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2248. Server svr;
  2249. svr.Get("/", [](const Request &req, Response &) {
  2250. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. {
  2260. Client cli(HOST, PORT);
  2261. cli.set_path_encode(false);
  2262. auto res = cli.Get("/?something=%0A");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::OK_200, res->status);
  2265. }
  2266. }
  2267. TEST(BindServerTest, BindDualStack) {
  2268. Server svr;
  2269. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2270. res.set_content("Hello World!", "text/plain");
  2271. });
  2272. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2273. auto se = detail::scope_exit([&] {
  2274. svr.stop();
  2275. thread.join();
  2276. ASSERT_FALSE(svr.is_running());
  2277. });
  2278. svr.wait_until_ready();
  2279. {
  2280. Client cli("127.0.0.1", PORT);
  2281. auto res = cli.Get("/1");
  2282. ASSERT_TRUE(res);
  2283. EXPECT_EQ(StatusCode::OK_200, res->status);
  2284. EXPECT_EQ("Hello World!", res->body);
  2285. }
  2286. {
  2287. Client cli("::1", PORT);
  2288. auto res = cli.Get("/1");
  2289. ASSERT_TRUE(res);
  2290. EXPECT_EQ(StatusCode::OK_200, res->status);
  2291. EXPECT_EQ("Hello World!", res->body);
  2292. }
  2293. }
  2294. TEST(BindServerTest, BindAndListenSeparately) {
  2295. Server svr;
  2296. int port = svr.bind_to_any_port("0.0.0.0");
  2297. ASSERT_TRUE(svr.is_valid());
  2298. ASSERT_TRUE(port > 0);
  2299. svr.stop();
  2300. }
  2301. #ifdef CPPHTTPLIB_SSL_ENABLED
  2302. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2304. CLIENT_CA_CERT_DIR);
  2305. int port = svr.bind_to_any_port("0.0.0.0");
  2306. ASSERT_TRUE(svr.is_valid());
  2307. ASSERT_TRUE(port > 0);
  2308. svr.stop();
  2309. }
  2310. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2311. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2312. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2313. int port = svr.bind_to_any_port("0.0.0.0");
  2314. ASSERT_TRUE(svr.is_valid());
  2315. ASSERT_TRUE(port > 0);
  2316. svr.stop();
  2317. }
  2318. TEST(BindServerTest, UpdateCertsPem) {
  2319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2320. int port = svr.bind_to_any_port("0.0.0.0");
  2321. ASSERT_TRUE(svr.is_valid());
  2322. ASSERT_TRUE(port > 0);
  2323. // Read PEM files
  2324. std::string cert_pem, key_pem, ca_pem;
  2325. read_file(SERVER_CERT_FILE, cert_pem);
  2326. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2327. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2328. // Update server certificates using PEM API
  2329. ASSERT_TRUE(
  2330. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2331. ASSERT_TRUE(svr.is_valid());
  2332. svr.stop();
  2333. }
  2334. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2335. // Start server with client CA (enables client auth)
  2336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2337. ASSERT_TRUE(svr.is_valid());
  2338. bool handler_called = false;
  2339. svr.Get("/test", [&](const Request &req, Response &res) {
  2340. handler_called = true;
  2341. // Verify client certificate is present
  2342. auto cert = req.peer_cert();
  2343. EXPECT_TRUE(static_cast<bool>(cert));
  2344. res.set_content("ok", "text/plain");
  2345. });
  2346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. t.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. // Read PEM files
  2354. std::string cert_pem, key_pem, ca_pem;
  2355. read_file(SERVER_CERT_FILE, cert_pem);
  2356. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2357. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2358. // Update server certificates and client CA using PEM API while server running
  2359. ASSERT_TRUE(
  2360. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2361. // Connect with client certificate
  2362. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2363. cli.enable_server_certificate_verification(false);
  2364. cli.set_connection_timeout(30);
  2365. auto res = cli.Get("/test");
  2366. ASSERT_TRUE(res);
  2367. ASSERT_EQ(StatusCode::OK_200, res->status);
  2368. ASSERT_TRUE(handler_called);
  2369. EXPECT_EQ("ok", res->body);
  2370. }
  2371. #endif
  2372. TEST(ErrorHandlerTest, ContentLength) {
  2373. Server svr;
  2374. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2375. res.status = StatusCode::OK_200;
  2376. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2377. "text/html"); // <= Content-Length still 13
  2378. });
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.set_content("Hello World!\n", "text/plain");
  2381. res.status = 524;
  2382. });
  2383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2384. auto se = detail::scope_exit([&] {
  2385. svr.stop();
  2386. thread.join();
  2387. ASSERT_FALSE(svr.is_running());
  2388. });
  2389. svr.wait_until_ready();
  2390. {
  2391. Client cli(HOST, PORT);
  2392. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2393. ASSERT_TRUE(res);
  2394. EXPECT_EQ(StatusCode::OK_200, res->status);
  2395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2398. }
  2399. }
  2400. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2401. TEST(ExceptionTest, WithoutExceptionHandler) {
  2402. Server svr;
  2403. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2404. throw std::runtime_error("exception...");
  2405. });
  2406. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2407. throw std::runtime_error("exception\r\n...");
  2408. });
  2409. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2410. auto se = detail::scope_exit([&] {
  2411. svr.stop();
  2412. listen_thread.join();
  2413. ASSERT_FALSE(svr.is_running());
  2414. });
  2415. svr.wait_until_ready();
  2416. Client cli("localhost", PORT);
  2417. {
  2418. auto res = cli.Get("/exception");
  2419. ASSERT_TRUE(res);
  2420. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2421. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2422. }
  2423. {
  2424. auto res = cli.Get("/unknown");
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2427. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2428. }
  2429. }
  2430. TEST(ExceptionTest, WithExceptionHandler) {
  2431. Server svr;
  2432. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2433. std::exception_ptr ep) {
  2434. EXPECT_FALSE(ep == nullptr);
  2435. try {
  2436. std::rethrow_exception(ep);
  2437. } catch (std::exception &e) {
  2438. EXPECT_EQ("abc", std::string(e.what()));
  2439. } catch (...) {}
  2440. res.status = StatusCode::InternalServerError_500;
  2441. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2442. "text/html"); // <= Content-Length still 13 at this point
  2443. });
  2444. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2445. res.set_content("Hello World!\n", "text/plain");
  2446. throw std::runtime_error("abc");
  2447. });
  2448. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2449. auto se = detail::scope_exit([&] {
  2450. svr.stop();
  2451. thread.join();
  2452. ASSERT_FALSE(svr.is_running());
  2453. });
  2454. svr.wait_until_ready();
  2455. for (size_t i = 0; i < 10; i++) {
  2456. Client cli(HOST, PORT);
  2457. for (size_t j = 0; j < 100; j++) {
  2458. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2461. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2462. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2463. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2464. }
  2465. cli.set_keep_alive(true);
  2466. for (size_t j = 0; j < 100; j++) {
  2467. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2470. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2471. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2473. }
  2474. }
  2475. }
  2476. TEST(ExceptionTest, AndErrorHandler) {
  2477. Server svr;
  2478. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2479. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2480. });
  2481. svr.set_exception_handler(
  2482. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2483. EXPECT_FALSE(ep == nullptr);
  2484. try {
  2485. std::rethrow_exception(ep);
  2486. } catch (std::exception &e) {
  2487. res.set_content(e.what(), "text/html");
  2488. } catch (...) {}
  2489. res.status = StatusCode::InternalServerError_500;
  2490. });
  2491. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2492. throw std::runtime_error("EXCEPTION");
  2493. });
  2494. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2495. res.set_content("ERROR", "text/html");
  2496. res.status = StatusCode::InternalServerError_500;
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, PORT);
  2506. {
  2507. auto res = cli.Get("/exception");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2510. EXPECT_EQ("EXCEPTION", res->body);
  2511. }
  2512. {
  2513. auto res = cli.Get("/error");
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2516. EXPECT_EQ("ERROR", res->body);
  2517. }
  2518. {
  2519. auto res = cli.Get("/invalid");
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2522. EXPECT_EQ("NOT_FOUND", res->body);
  2523. }
  2524. }
  2525. #endif
  2526. TEST(NoContentTest, ContentLength) {
  2527. Server svr;
  2528. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2529. res.status = StatusCode::NoContent_204;
  2530. });
  2531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. thread.join();
  2535. ASSERT_FALSE(svr.is_running());
  2536. });
  2537. svr.wait_until_ready();
  2538. {
  2539. Client cli(HOST, PORT);
  2540. auto res = cli.Get("/hi");
  2541. ASSERT_TRUE(res);
  2542. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2543. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2544. }
  2545. }
  2546. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2549. ASSERT_TRUE(svr.is_valid());
  2550. #else
  2551. Server svr;
  2552. #endif
  2553. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2554. if (req.path == "/routing_handler") {
  2555. res.set_header("PRE_ROUTING", "on");
  2556. res.set_content("Routing Handler", "text/plain");
  2557. return httplib::Server::HandlerResponse::Handled;
  2558. }
  2559. return httplib::Server::HandlerResponse::Unhandled;
  2560. });
  2561. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2562. res.set_content("Error", "text/html");
  2563. });
  2564. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2565. if (req.path == "/routing_handler") {
  2566. res.set_header("POST_ROUTING", "on");
  2567. }
  2568. });
  2569. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2570. res.set_content("Hello World!\n", "text/plain");
  2571. });
  2572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. svr.wait_until_ready();
  2579. {
  2580. #ifdef CPPHTTPLIB_SSL_ENABLED
  2581. SSLClient cli(HOST, PORT);
  2582. cli.enable_server_certificate_verification(false);
  2583. #else
  2584. Client cli(HOST, PORT);
  2585. #endif
  2586. auto res = cli.Get("/routing_handler");
  2587. ASSERT_TRUE(res);
  2588. EXPECT_EQ(StatusCode::OK_200, res->status);
  2589. EXPECT_EQ("Routing Handler", res->body);
  2590. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2591. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2592. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2593. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2594. }
  2595. {
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. SSLClient cli(HOST, PORT);
  2598. cli.enable_server_certificate_verification(false);
  2599. #else
  2600. Client cli(HOST, PORT);
  2601. #endif
  2602. auto res = cli.Get("/hi");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(StatusCode::OK_200, res->status);
  2605. EXPECT_EQ("Hello World!\n", res->body);
  2606. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2607. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2608. }
  2609. {
  2610. #ifdef CPPHTTPLIB_SSL_ENABLED
  2611. SSLClient cli(HOST, PORT);
  2612. cli.enable_server_certificate_verification(false);
  2613. #else
  2614. Client cli(HOST, PORT);
  2615. #endif
  2616. auto res = cli.Get("/aaa");
  2617. ASSERT_TRUE(res);
  2618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2619. EXPECT_EQ("Error", res->body);
  2620. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2621. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2622. }
  2623. }
  2624. TEST(RequestHandlerTest, PreRequestHandler) {
  2625. auto route_path = "/user/:user";
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request &, Response &res) {
  2628. res.set_content("hi", "text/plain");
  2629. });
  2630. svr.Get(route_path, [](const Request &req, Response &res) {
  2631. res.set_content(req.path_params.at("user"), "text/plain");
  2632. });
  2633. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2634. if (req.matched_route == route_path) {
  2635. auto user = req.path_params.at("user");
  2636. if (user != "john") {
  2637. res.status = StatusCode::Forbidden_403;
  2638. res.set_content("error", "text/html");
  2639. return Server::HandlerResponse::Handled;
  2640. }
  2641. }
  2642. return Server::HandlerResponse::Unhandled;
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. {
  2653. auto res = cli.Get("/hi");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("hi", res->body);
  2657. }
  2658. {
  2659. auto res = cli.Get("/user/john");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. EXPECT_EQ("john", res->body);
  2663. }
  2664. {
  2665. auto res = cli.Get("/user/invalid-user");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2668. EXPECT_EQ("error", res->body);
  2669. }
  2670. }
  2671. TEST(UserDataTest, BasicOperations) {
  2672. httplib::UserData ud;
  2673. // Initially empty
  2674. EXPECT_FALSE(ud.has("key"));
  2675. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2676. // set and get
  2677. ud.set("key", 42);
  2678. EXPECT_TRUE(ud.has("key"));
  2679. auto *p = ud.get<int>("key");
  2680. ASSERT_NE(nullptr, p);
  2681. EXPECT_EQ(42, *p);
  2682. // Type mismatch → nullptr
  2683. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2684. // Overwrite with different type
  2685. ud.set("key", std::string("hello"));
  2686. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2687. auto *s = ud.get<std::string>("key");
  2688. ASSERT_NE(nullptr, s);
  2689. EXPECT_EQ("hello", *s);
  2690. // erase
  2691. ud.erase("key");
  2692. EXPECT_FALSE(ud.has("key"));
  2693. // clear
  2694. ud.set("a", 1);
  2695. ud.set("b", 2);
  2696. ud.clear();
  2697. EXPECT_FALSE(ud.has("a"));
  2698. EXPECT_FALSE(ud.has("b"));
  2699. }
  2700. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2701. struct AuthCtx {
  2702. std::string user_id;
  2703. };
  2704. Server svr;
  2705. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2706. res.user_data.set("auth", AuthCtx{"alice"});
  2707. return Server::HandlerResponse::Unhandled;
  2708. });
  2709. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2710. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2711. ASSERT_NE(nullptr, ctx);
  2712. res.set_content("Hello " + ctx->user_id, "text/plain");
  2713. });
  2714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2715. auto se = detail::scope_exit([&] {
  2716. svr.stop();
  2717. thread.join();
  2718. ASSERT_FALSE(svr.is_running());
  2719. });
  2720. svr.wait_until_ready();
  2721. Client cli(HOST, PORT);
  2722. auto res = cli.Get("/me");
  2723. ASSERT_TRUE(res);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. EXPECT_EQ("Hello alice", res->body);
  2726. }
  2727. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2728. struct RoleCtx {
  2729. std::string role;
  2730. };
  2731. Server svr;
  2732. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2733. res.user_data.set("role", RoleCtx{"admin"});
  2734. return Server::HandlerResponse::Unhandled;
  2735. });
  2736. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2737. auto *ctx = res.user_data.get<RoleCtx>("role");
  2738. ASSERT_NE(nullptr, ctx);
  2739. res.set_content(ctx->role, "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. auto res = cli.Get("/role");
  2750. ASSERT_TRUE(res);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. EXPECT_EQ("admin", res->body);
  2753. }
  2754. TEST(InvalidFormatTest, StatusCode) {
  2755. Server svr;
  2756. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2757. res.set_content("Hello World!\n", "text/plain");
  2758. res.status = 9999; // Status should be a three-digit code...
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. {
  2768. Client cli(HOST, PORT);
  2769. auto res = cli.Get("/hi");
  2770. ASSERT_FALSE(res);
  2771. }
  2772. }
  2773. TEST(URLFragmentTest, WithFragment) {
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2776. EXPECT_TRUE(req.target == "/hi");
  2777. });
  2778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2779. auto se = detail::scope_exit([&] {
  2780. svr.stop();
  2781. thread.join();
  2782. ASSERT_FALSE(svr.is_running());
  2783. });
  2784. svr.wait_until_ready();
  2785. {
  2786. Client cli(HOST, PORT);
  2787. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2788. EXPECT_TRUE(res);
  2789. EXPECT_EQ(StatusCode::OK_200, res->status);
  2790. res = cli.Get("/hi%23key1=val1=key2=val2");
  2791. EXPECT_TRUE(res);
  2792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2793. }
  2794. }
  2795. TEST(HeaderWriter, SetHeaderWriter) {
  2796. Server svr;
  2797. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2798. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2799. return detail::write_headers(strm, hdrs);
  2800. });
  2801. svr.Get("/hi", [](const Request &req, Response &res) {
  2802. auto it = req.headers.find("CustomClientHeader");
  2803. EXPECT_TRUE(it != req.headers.end());
  2804. EXPECT_EQ(it->second, "CustomClientValue");
  2805. res.set_content("Hello World!\n", "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. {
  2815. Client cli(HOST, PORT);
  2816. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2817. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2818. return detail::write_headers(strm, hdrs);
  2819. });
  2820. auto res = cli.Get("/hi");
  2821. EXPECT_TRUE(res);
  2822. EXPECT_EQ(StatusCode::OK_200, res->status);
  2823. auto it = res->headers.find("CustomServerHeader");
  2824. EXPECT_TRUE(it != res->headers.end());
  2825. EXPECT_EQ(it->second, "CustomServerValue");
  2826. }
  2827. }
  2828. class ServerTest : public ::testing::Test {
  2829. protected:
  2830. ServerTest()
  2831. : cli_(HOST, PORT)
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. ,
  2834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2835. #endif
  2836. {
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. cli_.enable_server_certificate_verification(false);
  2839. #endif
  2840. // Allow LARGE_DATA (100MB) responses
  2841. cli_.set_payload_max_length(200 * 1024 * 1024);
  2842. }
  2843. virtual void SetUp() {
  2844. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2845. svr_.set_payload_max_length(200 * 1024 * 1024);
  2846. svr_.set_mount_point("/", "./www");
  2847. svr_.set_mount_point("/mount", "./www2");
  2848. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2849. svr_.Get("/hi",
  2850. [&](const Request & /*req*/, Response &res) {
  2851. res.set_content("Hello World!", "text/plain");
  2852. })
  2853. .Get("/file_content",
  2854. [&](const Request & /*req*/, Response &res) {
  2855. res.set_file_content("./www/dir/test.html");
  2856. })
  2857. .Get("/file_content_with_content_type",
  2858. [&](const Request & /*req*/, Response &res) {
  2859. res.set_file_content("./www/file", "text/plain");
  2860. })
  2861. .Get("/invalid_file_content",
  2862. [&](const Request & /*req*/, Response &res) {
  2863. res.set_file_content("./www/dir/invalid_file_path");
  2864. })
  2865. .Get("/http_response_splitting",
  2866. [&](const Request & /*req*/, Response &res) {
  2867. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2868. EXPECT_EQ(0U, res.headers.size());
  2869. EXPECT_FALSE(res.has_header("a"));
  2870. res.set_header("a", "1\nSet-Cookie: a=1");
  2871. EXPECT_EQ(0U, res.headers.size());
  2872. EXPECT_FALSE(res.has_header("a"));
  2873. res.set_header("a", "1\rSet-Cookie: a=1");
  2874. EXPECT_EQ(0U, res.headers.size());
  2875. EXPECT_FALSE(res.has_header("a"));
  2876. res.set_header("a\r\nb", "0");
  2877. EXPECT_EQ(0U, res.headers.size());
  2878. EXPECT_FALSE(res.has_header("a"));
  2879. res.set_header("a\rb", "0");
  2880. EXPECT_EQ(0U, res.headers.size());
  2881. EXPECT_FALSE(res.has_header("a"));
  2882. res.set_header("a\nb", "0");
  2883. EXPECT_EQ(0U, res.headers.size());
  2884. EXPECT_FALSE(res.has_header("a"));
  2885. res.set_redirect("1\r\nSet-Cookie: a=1");
  2886. EXPECT_EQ(0U, res.headers.size());
  2887. EXPECT_FALSE(res.has_header("Location"));
  2888. })
  2889. .Get("/slow",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. std::this_thread::sleep_for(std::chrono::seconds(4));
  2892. res.set_content("slow", "text/plain");
  2893. })
  2894. #if 0
  2895. .Post("/slowpost",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. std::this_thread::sleep_for(std::chrono::seconds(2));
  2898. res.set_content("slow", "text/plain");
  2899. })
  2900. #endif
  2901. .Get("/remote_addr",
  2902. [&](const Request &req, Response &res) {
  2903. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2904. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2905. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2906. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2907. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2908. #endif
  2909. res.set_content(req.remote_addr, "text/plain");
  2910. })
  2911. .Get("/local_addr",
  2912. [&](const Request &req, Response &res) {
  2913. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2914. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2915. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2916. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2917. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2918. #endif
  2919. auto local_addr = req.local_addr;
  2920. auto local_port = std::to_string(req.local_port);
  2921. res.set_content(local_addr.append(":").append(local_port),
  2922. "text/plain");
  2923. })
  2924. .Get("/endwith%",
  2925. [&](const Request & /*req*/, Response &res) {
  2926. res.set_content("Hello World!", "text/plain");
  2927. })
  2928. .Get("/a\\+\\+b",
  2929. [&](const Request &req, Response &res) {
  2930. ASSERT_TRUE(req.has_param("a +b"));
  2931. auto val = req.get_param_value("a +b");
  2932. res.set_content(val, "text/plain");
  2933. })
  2934. .Get("/", [&](const Request & /*req*/,
  2935. Response &res) { res.set_redirect("/hi"); })
  2936. .Post("/1",
  2937. [](const Request & /*req*/, Response &res) {
  2938. res.set_redirect("/2", StatusCode::SeeOther_303);
  2939. })
  2940. .Get("/2",
  2941. [](const Request & /*req*/, Response &res) {
  2942. res.set_content("redirected.", "text/plain");
  2943. res.status = StatusCode::OK_200;
  2944. })
  2945. .Post("/person",
  2946. [&](const Request &req, Response &res) {
  2947. if (req.has_param("name") && req.has_param("note")) {
  2948. persons_[req.get_param_value("name")] =
  2949. req.get_param_value("note");
  2950. } else {
  2951. res.status = StatusCode::BadRequest_400;
  2952. }
  2953. })
  2954. .Put("/person",
  2955. [&](const Request &req, Response &res) {
  2956. if (req.has_param("name") && req.has_param("note")) {
  2957. persons_[req.get_param_value("name")] =
  2958. req.get_param_value("note");
  2959. } else {
  2960. res.status = StatusCode::BadRequest_400;
  2961. }
  2962. })
  2963. .Get("/person/(.*)",
  2964. [&](const Request &req, Response &res) {
  2965. string name = req.matches[1];
  2966. if (persons_.find(name) != persons_.end()) {
  2967. auto note = persons_[name];
  2968. res.set_content(note, "text/plain");
  2969. } else {
  2970. res.status = StatusCode::NotFound_404;
  2971. }
  2972. })
  2973. .Delete("/person",
  2974. [&](const Request &req, Response &res) {
  2975. if (req.has_param("name")) {
  2976. string name = req.get_param_value("name");
  2977. if (persons_.find(name) != persons_.end()) {
  2978. persons_.erase(name);
  2979. res.set_content("DELETED", "text/plain");
  2980. } else {
  2981. res.status = StatusCode::NotFound_404;
  2982. }
  2983. } else {
  2984. res.status = StatusCode::BadRequest_400;
  2985. }
  2986. })
  2987. .Post("/x-www-form-urlencoded-json",
  2988. [&](const Request &req, Response &res) {
  2989. auto json = req.get_param_value("json");
  2990. ASSERT_EQ(JSON_DATA, json);
  2991. res.set_content(json, "appliation/json");
  2992. res.status = StatusCode::OK_200;
  2993. })
  2994. .Get("/streamed-chunked",
  2995. [&](const Request & /*req*/, Response &res) {
  2996. res.set_chunked_content_provider(
  2997. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2998. sink.os << "123";
  2999. sink.os << "456";
  3000. sink.os << "789";
  3001. sink.done();
  3002. return true;
  3003. });
  3004. })
  3005. .Get("/streamed-chunked-with-prohibited-trailer",
  3006. [&](const Request & /*req*/, Response &res) {
  3007. auto i = new int(0);
  3008. // Declare both a prohibited trailer (Content-Length) and an
  3009. // allowed one
  3010. res.set_header("Trailer", "Content-Length, X-Allowed");
  3011. res.set_chunked_content_provider(
  3012. "text/plain",
  3013. [i](size_t /*offset*/, DataSink &sink) {
  3014. switch (*i) {
  3015. case 0: sink.os << "123"; break;
  3016. case 1: sink.os << "456"; break;
  3017. case 2: sink.os << "789"; break;
  3018. case 3: {
  3019. sink.done_with_trailer(
  3020. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3021. } break;
  3022. }
  3023. (*i)++;
  3024. return true;
  3025. },
  3026. [i](bool success) {
  3027. EXPECT_TRUE(success);
  3028. delete i;
  3029. });
  3030. })
  3031. .Get("/streamed-chunked2",
  3032. [&](const Request & /*req*/, Response &res) {
  3033. auto i = new int(0);
  3034. res.set_chunked_content_provider(
  3035. "text/plain",
  3036. [i](size_t /*offset*/, DataSink &sink) {
  3037. switch (*i) {
  3038. case 0: sink.os << "123"; break;
  3039. case 1: sink.os << "456"; break;
  3040. case 2: sink.os << "789"; break;
  3041. case 3: sink.done(); break;
  3042. }
  3043. (*i)++;
  3044. return true;
  3045. },
  3046. [i](bool success) {
  3047. EXPECT_TRUE(success);
  3048. delete i;
  3049. });
  3050. })
  3051. .Get("/streamed-chunked-with-trailer",
  3052. [&](const Request & /*req*/, Response &res) {
  3053. auto i = new int(0);
  3054. res.set_header("Trailer", "Dummy1, Dummy2");
  3055. res.set_chunked_content_provider(
  3056. "text/plain",
  3057. [i](size_t /*offset*/, DataSink &sink) {
  3058. switch (*i) {
  3059. case 0: sink.os << "123"; break;
  3060. case 1: sink.os << "456"; break;
  3061. case 2: sink.os << "789"; break;
  3062. case 3: {
  3063. sink.done_with_trailer(
  3064. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3065. } break;
  3066. }
  3067. (*i)++;
  3068. return true;
  3069. },
  3070. [i](bool success) {
  3071. EXPECT_TRUE(success);
  3072. delete i;
  3073. });
  3074. })
  3075. .Get("/streamed",
  3076. [&](const Request & /*req*/, Response &res) {
  3077. res.set_content_provider(
  3078. 6, "text/plain",
  3079. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3080. sink.os << (offset < 3 ? "a" : "b");
  3081. return true;
  3082. });
  3083. })
  3084. .Get("/streamed-with-range",
  3085. [&](const Request &req, Response &res) {
  3086. auto data = new std::string("abcdefg");
  3087. res.set_content_provider(
  3088. data->size(), "text/plain",
  3089. [data](size_t offset, size_t length, DataSink &sink) {
  3090. size_t DATA_CHUNK_SIZE = 4;
  3091. const auto &d = *data;
  3092. auto out_len =
  3093. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3094. auto ret =
  3095. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3096. EXPECT_TRUE(ret);
  3097. return true;
  3098. },
  3099. [data, &req](bool success) {
  3100. EXPECT_EQ(success, !req.has_param("error"));
  3101. delete data;
  3102. });
  3103. })
  3104. .Get("/streamed-cancel",
  3105. [&](const Request & /*req*/, Response &res) {
  3106. res.set_content_provider(
  3107. size_t(-1), "text/plain",
  3108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3109. sink.os << "data_chunk";
  3110. return true;
  3111. });
  3112. })
  3113. .Get("/regex-with-delimiter",
  3114. [&](const Request &req, Response & /*res*/) {
  3115. ASSERT_TRUE(req.has_param("key"));
  3116. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3117. })
  3118. .Get("/with-range",
  3119. [&](const Request & /*req*/, Response &res) {
  3120. res.set_content("abcdefg", "text/plain");
  3121. })
  3122. .Get("/test-start-time",
  3123. [&](const Request &req, Response & /*res*/) {
  3124. EXPECT_NE(req.start_time_,
  3125. std::chrono::steady_clock::time_point::min());
  3126. })
  3127. .Get("/with-range-customized-response",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.status = StatusCode::BadRequest_400;
  3130. res.set_content(JSON_DATA, "application/json");
  3131. })
  3132. .Post("/chunked",
  3133. [&](const Request &req, Response & /*res*/) {
  3134. EXPECT_EQ(req.body, "dechunked post body");
  3135. })
  3136. .Post("/large-chunked",
  3137. [&](const Request &req, Response & /*res*/) {
  3138. std::string expected(6 * 30 * 1024u, 'a');
  3139. EXPECT_EQ(req.body, expected);
  3140. })
  3141. .Post("/multipart",
  3142. [&](const Request &req, Response & /*res*/) {
  3143. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3144. req.form.get_field_count("text2") +
  3145. req.form.get_field_count("file3") +
  3146. req.form.get_field_count("file4"));
  3147. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3148. req.form.get_file_count("file2"));
  3149. ASSERT_TRUE(!req.form.has_file("???"));
  3150. ASSERT_TRUE(!req.form.has_field("???"));
  3151. ASSERT_TRUE(req.body.empty());
  3152. {
  3153. const auto &text = req.form.get_field("text1");
  3154. EXPECT_EQ("text default", text);
  3155. }
  3156. {
  3157. const auto &text = req.form.get_field("text2");
  3158. EXPECT_EQ("aωb", text);
  3159. }
  3160. {
  3161. const auto &file = req.form.get_file("file1");
  3162. EXPECT_EQ("hello.txt", file.filename);
  3163. EXPECT_EQ("text/plain", file.content_type);
  3164. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3165. }
  3166. {
  3167. const auto &file = req.form.get_file("file2");
  3168. EXPECT_EQ("world.json", file.filename);
  3169. EXPECT_EQ("application/json", file.content_type);
  3170. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3171. }
  3172. {
  3173. const auto &text = req.form.get_field("file3");
  3174. EXPECT_EQ(0u, text.size());
  3175. }
  3176. {
  3177. const auto &text = req.form.get_field("file4");
  3178. EXPECT_EQ(0u, text.size());
  3179. }
  3180. })
  3181. .Post("/multipart/multi_file_values",
  3182. [&](const Request &req, Response & /*res*/) {
  3183. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3184. req.form.get_field_count("multi_text1"));
  3185. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3186. ASSERT_TRUE(!req.form.has_file("???"));
  3187. ASSERT_TRUE(!req.form.has_field("???"));
  3188. ASSERT_TRUE(req.body.empty());
  3189. {
  3190. const auto &text = req.form.get_field("text");
  3191. EXPECT_EQ("default text", text);
  3192. }
  3193. {
  3194. const auto &text1_values = req.form.get_fields("multi_text1");
  3195. EXPECT_EQ(2u, text1_values.size());
  3196. EXPECT_EQ("aaaaa", text1_values[0]);
  3197. EXPECT_EQ("bbbbb", text1_values[1]);
  3198. }
  3199. {
  3200. const auto &file1_values = req.form.get_files("multi_file1");
  3201. EXPECT_EQ(2u, file1_values.size());
  3202. auto file1 = file1_values[0];
  3203. EXPECT_EQ(file1.filename, "hello.txt");
  3204. EXPECT_EQ(file1.content_type, "text/plain");
  3205. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3206. auto file2 = file1_values[1];
  3207. EXPECT_EQ(file2.filename, "world.json");
  3208. EXPECT_EQ(file2.content_type, "application/json");
  3209. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3210. }
  3211. })
  3212. .Post("/empty",
  3213. [&](const Request &req, Response &res) {
  3214. EXPECT_EQ(req.body, "");
  3215. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3216. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3217. res.set_content("empty", "text/plain");
  3218. })
  3219. .Post("/empty-no-content-type",
  3220. [&](const Request &req, Response &res) {
  3221. EXPECT_EQ(req.body, "");
  3222. EXPECT_FALSE(req.has_header("Content-Type"));
  3223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3224. res.set_content("empty-no-content-type", "text/plain");
  3225. })
  3226. .Post("/path-only",
  3227. [&](const Request &req, Response &res) {
  3228. EXPECT_EQ(req.body, "");
  3229. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3230. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3231. res.set_content("path-only", "text/plain");
  3232. })
  3233. .Post("/path-headers-only",
  3234. [&](const Request &req, Response &res) {
  3235. EXPECT_EQ(req.body, "");
  3236. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3237. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3238. EXPECT_EQ("world", req.get_header_value("hello"));
  3239. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3240. res.set_content("path-headers-only", "text/plain");
  3241. })
  3242. .Post("/post-large",
  3243. [&](const Request &req, Response &res) {
  3244. EXPECT_EQ(req.body, LARGE_DATA);
  3245. res.set_content(req.body, "text/plain");
  3246. })
  3247. .Post("/post-loopback",
  3248. [&](const Request &, Response &res,
  3249. ContentReader const &content_reader) {
  3250. std::string body;
  3251. content_reader([&](const char *data, size_t data_length) {
  3252. body.append(data, data_length);
  3253. return true;
  3254. });
  3255. res.set_content(body, "text/plain");
  3256. })
  3257. .Put("/put-loopback",
  3258. [&](const Request &, Response &res,
  3259. ContentReader const &content_reader) {
  3260. std::string body;
  3261. content_reader([&](const char *data, size_t data_length) {
  3262. body.append(data, data_length);
  3263. return true;
  3264. });
  3265. res.set_content(body, "text/plain");
  3266. })
  3267. .Patch("/patch-loopback",
  3268. [&](const Request &, Response &res,
  3269. ContentReader const &content_reader) {
  3270. std::string body;
  3271. content_reader([&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. res.set_content(body, "text/plain");
  3276. })
  3277. .Put("/empty-no-content-type",
  3278. [&](const Request &req, Response &res) {
  3279. EXPECT_EQ(req.body, "");
  3280. EXPECT_FALSE(req.has_header("Content-Type"));
  3281. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3282. res.set_content("empty-no-content-type", "text/plain");
  3283. })
  3284. .Put("/put",
  3285. [&](const Request &req, Response &res) {
  3286. EXPECT_EQ(req.body, "PUT");
  3287. res.set_content(req.body, "text/plain");
  3288. })
  3289. .Put("/put-large",
  3290. [&](const Request &req, Response &res) {
  3291. EXPECT_EQ(req.body, LARGE_DATA);
  3292. res.set_content(req.body, "text/plain");
  3293. })
  3294. .Patch("/patch",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(req.body, "PATCH");
  3297. res.set_content(req.body, "text/plain");
  3298. })
  3299. .Delete("/delete",
  3300. [&](const Request & /*req*/, Response &res) {
  3301. res.set_content("DELETE", "text/plain");
  3302. })
  3303. .Delete("/delete-body",
  3304. [&](const Request &req, Response &res) {
  3305. EXPECT_EQ(req.body, "content");
  3306. res.set_content(req.body, "text/plain");
  3307. })
  3308. .Options(R"(\*)",
  3309. [&](const Request & /*req*/, Response &res) {
  3310. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3311. })
  3312. .Get("/request-target",
  3313. [&](const Request &req, Response & /*res*/) {
  3314. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3315. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3316. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3317. })
  3318. .Get("/long-query-value",
  3319. [&](const Request &req, Response & /*res*/) {
  3320. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3321. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3322. })
  3323. .Get("/too-long-query-value",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3326. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3327. })
  3328. .Get("/array-param",
  3329. [&](const Request &req, Response & /*res*/) {
  3330. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3331. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3332. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3333. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3334. })
  3335. .Get("/array-param-values",
  3336. [&](const Request &req, Response & /*res*/) {
  3337. auto values = req.get_param_values("array");
  3338. EXPECT_EQ(3u, values.size());
  3339. EXPECT_EQ("value1", values[0]);
  3340. EXPECT_EQ("value2", values[1]);
  3341. EXPECT_EQ("value3", values[2]);
  3342. auto empty = req.get_param_values("nonexistent");
  3343. EXPECT_TRUE(empty.empty());
  3344. })
  3345. .Post("/validate-no-multiple-headers",
  3346. [&](const Request &req, Response & /*res*/) {
  3347. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3348. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3349. })
  3350. .Post("/content_receiver",
  3351. [&](const Request &req, Response &res,
  3352. const ContentReader &content_reader) {
  3353. if (req.is_multipart_form_data()) {
  3354. std::vector<FormData> items;
  3355. content_reader(
  3356. [&](const FormData &file) {
  3357. items.push_back(file);
  3358. return true;
  3359. },
  3360. [&](const char *data, size_t data_length) {
  3361. items.back().content.append(data, data_length);
  3362. return true;
  3363. });
  3364. EXPECT_EQ(5u, items.size());
  3365. {
  3366. const auto &file = get_file_value(items, "text1");
  3367. EXPECT_TRUE(file.filename.empty());
  3368. EXPECT_EQ("text default", file.content);
  3369. }
  3370. {
  3371. const auto &file = get_file_value(items, "text2");
  3372. EXPECT_TRUE(file.filename.empty());
  3373. EXPECT_EQ("aωb", file.content);
  3374. }
  3375. {
  3376. const auto &file = get_file_value(items, "file1");
  3377. EXPECT_EQ("hello.txt", file.filename);
  3378. EXPECT_EQ("text/plain", file.content_type);
  3379. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3380. }
  3381. {
  3382. const auto &file = get_file_value(items, "file2");
  3383. EXPECT_EQ("world.json", file.filename);
  3384. EXPECT_EQ("application/json", file.content_type);
  3385. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3386. }
  3387. {
  3388. const auto &file = get_file_value(items, "file3");
  3389. EXPECT_TRUE(file.filename.empty());
  3390. EXPECT_EQ("application/octet-stream", file.content_type);
  3391. EXPECT_EQ(0u, file.content.size());
  3392. }
  3393. } else {
  3394. std::string body;
  3395. content_reader([&](const char *data, size_t data_length) {
  3396. EXPECT_EQ(7U, data_length);
  3397. body.append(data, data_length);
  3398. return true;
  3399. });
  3400. EXPECT_EQ(body, "content");
  3401. res.set_content(body, "text/plain");
  3402. }
  3403. })
  3404. .Put("/content_receiver",
  3405. [&](const Request & /*req*/, Response &res,
  3406. const ContentReader &content_reader) {
  3407. std::string body;
  3408. content_reader([&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. EXPECT_EQ(body, "content");
  3413. res.set_content(body, "text/plain");
  3414. })
  3415. .Patch("/content_receiver",
  3416. [&](const Request & /*req*/, Response &res,
  3417. const ContentReader &content_reader) {
  3418. std::string body;
  3419. content_reader([&](const char *data, size_t data_length) {
  3420. body.append(data, data_length);
  3421. return true;
  3422. });
  3423. EXPECT_EQ(body, "content");
  3424. res.set_content(body, "text/plain");
  3425. })
  3426. .Post("/query-string-and-body",
  3427. [&](const Request &req, Response & /*res*/) {
  3428. ASSERT_TRUE(req.has_param("key"));
  3429. EXPECT_EQ(req.get_param_value("key"), "value");
  3430. EXPECT_EQ(req.body, "content");
  3431. })
  3432. .Get("/last-request",
  3433. [&](const Request &req, Response & /*res*/) {
  3434. EXPECT_EQ("close", req.get_header_value("Connection"));
  3435. })
  3436. .Get(R"(/redirect/(\d+))",
  3437. [&](const Request &req, Response &res) {
  3438. auto num = std::stoi(req.matches[1]) + 1;
  3439. std::string url = "/redirect/" + std::to_string(num);
  3440. res.set_redirect(url);
  3441. })
  3442. .Post("/binary",
  3443. [&](const Request &req, Response &res) {
  3444. EXPECT_EQ(4U, req.body.size());
  3445. EXPECT_EQ("application/octet-stream",
  3446. req.get_header_value("Content-Type"));
  3447. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3448. res.set_content(req.body, "application/octet-stream");
  3449. })
  3450. .Put("/binary",
  3451. [&](const Request &req, Response &res) {
  3452. EXPECT_EQ(4U, req.body.size());
  3453. EXPECT_EQ("application/octet-stream",
  3454. req.get_header_value("Content-Type"));
  3455. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3456. res.set_content(req.body, "application/octet-stream");
  3457. })
  3458. .Patch("/binary",
  3459. [&](const Request &req, Response &res) {
  3460. EXPECT_EQ(4U, req.body.size());
  3461. EXPECT_EQ("application/octet-stream",
  3462. req.get_header_value("Content-Type"));
  3463. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3464. res.set_content(req.body, "application/octet-stream");
  3465. })
  3466. .Delete("/binary",
  3467. [&](const Request &req, Response &res) {
  3468. EXPECT_EQ(4U, req.body.size());
  3469. EXPECT_EQ("application/octet-stream",
  3470. req.get_header_value("Content-Type"));
  3471. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3472. res.set_content(req.body, "application/octet-stream");
  3473. })
  3474. .Get("/issue1772",
  3475. [&](const Request & /*req*/, Response &res) {
  3476. res.status = 401;
  3477. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3478. })
  3479. .Delete("/issue609",
  3480. [](const httplib::Request &, httplib::Response &res,
  3481. const httplib::ContentReader &) {
  3482. res.set_content("ok", "text/plain");
  3483. })
  3484. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3485. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3486. .Get("/compress",
  3487. [&](const Request & /*req*/, Response &res) {
  3488. res.set_content(
  3489. "12345678901234567890123456789012345678901234567890123456789"
  3490. "01234567890123456789012345678901234567890",
  3491. "text/plain");
  3492. })
  3493. .Get("/compress-with-charset",
  3494. [&](const Request & /*req*/, Response &res) {
  3495. res.set_content(
  3496. "12345678901234567890123456789012345678901234567890123456789"
  3497. "01234567890123456789012345678901234567890",
  3498. "application/json; charset=utf-8");
  3499. })
  3500. .Get("/nocompress",
  3501. [&](const Request & /*req*/, Response &res) {
  3502. res.set_content(
  3503. "12345678901234567890123456789012345678901234567890123456789"
  3504. "01234567890123456789012345678901234567890",
  3505. "application/octet-stream");
  3506. })
  3507. .Post("/compress-multipart",
  3508. [&](const Request &req, Response & /*res*/) {
  3509. EXPECT_EQ(2u, req.form.fields.size());
  3510. ASSERT_TRUE(!req.form.has_field("???"));
  3511. {
  3512. const auto &text = req.form.get_field("key1");
  3513. EXPECT_EQ("test", text);
  3514. }
  3515. {
  3516. const auto &text = req.form.get_field("key2");
  3517. EXPECT_EQ("--abcdefg123", text);
  3518. }
  3519. })
  3520. #endif
  3521. ;
  3522. persons_["john"] = "programmer";
  3523. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3524. svr_.wait_until_ready();
  3525. }
  3526. virtual void TearDown() {
  3527. svr_.stop();
  3528. if (!request_threads_.empty()) {
  3529. std::this_thread::sleep_for(std::chrono::seconds(1));
  3530. for (auto &t : request_threads_) {
  3531. t.join();
  3532. }
  3533. }
  3534. t_.join();
  3535. }
  3536. map<string, string> persons_;
  3537. #ifdef CPPHTTPLIB_SSL_ENABLED
  3538. SSLClient cli_;
  3539. SSLServer svr_;
  3540. #else
  3541. Client cli_;
  3542. Server svr_;
  3543. #endif
  3544. thread t_;
  3545. std::vector<thread> request_threads_;
  3546. };
  3547. TEST_F(ServerTest, GetMethod200) {
  3548. auto res = cli_.Get("/hi");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ("HTTP/1.1", res->version);
  3551. EXPECT_EQ(StatusCode::OK_200, res->status);
  3552. EXPECT_EQ("OK", res->reason);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3555. EXPECT_EQ("Hello World!", res->body);
  3556. }
  3557. TEST_F(ServerTest, GetEmptyFile) {
  3558. auto res = cli_.Get("/empty_file");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3563. EXPECT_EQ("", res->body);
  3564. }
  3565. TEST_F(ServerTest, GetFileContent) {
  3566. auto res = cli_.Get("/file_content");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3570. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3571. EXPECT_EQ("test.html", res->body);
  3572. }
  3573. TEST_F(ServerTest, GetFileContentWithRange) {
  3574. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3578. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3579. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3580. EXPECT_EQ("est", res->body);
  3581. }
  3582. TEST_F(ServerTest, GetFileContentWithContentType) {
  3583. auto res = cli_.Get("/file_content_with_content_type");
  3584. ASSERT_TRUE(res);
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3587. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3588. EXPECT_EQ("file\n", res->body);
  3589. }
  3590. TEST_F(ServerTest, GetInvalidFileContent) {
  3591. auto res = cli_.Get("/invalid_file_content");
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3596. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3597. ASSERT_TRUE(res);
  3598. EXPECT_EQ("HTTP/1.1", res->version);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3601. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3602. EXPECT_EQ("Hello World!", res->body);
  3603. }
  3604. TEST_F(ServerTest, GetMethod302) {
  3605. auto res = cli_.Get("/");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(StatusCode::Found_302, res->status);
  3608. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3609. }
  3610. TEST_F(ServerTest, GetMethod302Redirect) {
  3611. cli_.set_follow_location(true);
  3612. auto res = cli_.Get("/");
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. EXPECT_EQ("Hello World!", res->body);
  3616. EXPECT_EQ("/hi", res->location);
  3617. }
  3618. TEST_F(ServerTest, GetMethod404) {
  3619. auto res = cli_.Get("/invalid");
  3620. ASSERT_TRUE(res);
  3621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3622. }
  3623. TEST_F(ServerTest, HeadMethod200) {
  3624. auto res = cli_.Head("/hi");
  3625. ASSERT_TRUE(res);
  3626. EXPECT_EQ(StatusCode::OK_200, res->status);
  3627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3628. EXPECT_TRUE(res->body.empty());
  3629. }
  3630. TEST_F(ServerTest, HeadMethod200Static) {
  3631. auto res = cli_.Head("/mount/dir/index.html");
  3632. ASSERT_TRUE(res);
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3635. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3636. EXPECT_TRUE(res->body.empty());
  3637. }
  3638. TEST_F(ServerTest, HeadMethod404) {
  3639. auto res = cli_.Head("/invalid");
  3640. ASSERT_TRUE(res);
  3641. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3642. EXPECT_TRUE(res->body.empty());
  3643. }
  3644. TEST_F(ServerTest, GetMethodPersonJohn) {
  3645. auto res = cli_.Get("/person/john");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("programmer", res->body);
  3650. }
  3651. TEST_F(ServerTest, PostMethod1) {
  3652. auto res = cli_.Get("/person/john1");
  3653. ASSERT_TRUE(res);
  3654. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3655. res = cli_.Post("/person", "name=john1&note=coder",
  3656. "application/x-www-form-urlencoded");
  3657. ASSERT_TRUE(res);
  3658. ASSERT_EQ(StatusCode::OK_200, res->status);
  3659. res = cli_.Get("/person/john1");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3663. ASSERT_EQ("coder", res->body);
  3664. }
  3665. TEST_F(ServerTest, PostMethod2) {
  3666. auto res = cli_.Get("/person/john2");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3669. Params params;
  3670. params.emplace("name", "john2");
  3671. params.emplace("note", "coder");
  3672. res = cli_.Post("/person", params);
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. res = cli_.Get("/person/john2");
  3676. ASSERT_TRUE(res);
  3677. ASSERT_EQ(StatusCode::OK_200, res->status);
  3678. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3679. ASSERT_EQ("coder", res->body);
  3680. }
  3681. TEST_F(ServerTest, PutMethod3) {
  3682. auto res = cli_.Get("/person/john3");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3685. Params params;
  3686. params.emplace("name", "john3");
  3687. params.emplace("note", "coder");
  3688. res = cli_.Put("/person", params);
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. res = cli_.Get("/person/john3");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3695. ASSERT_EQ("coder", res->body);
  3696. }
  3697. TEST_F(ServerTest, DeleteMethod1) {
  3698. auto res = cli_.Get("/person/john4");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3701. Params params;
  3702. params.emplace("name", "john4");
  3703. params.emplace("note", "coder");
  3704. res = cli_.Post("/person", params);
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. res = cli_.Get("/person/john4");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3711. ASSERT_EQ("coder", res->body);
  3712. Params delete_params;
  3713. delete_params.emplace("name", "john4");
  3714. res = cli_.Delete("/person", delete_params);
  3715. ASSERT_TRUE(res);
  3716. ASSERT_EQ(StatusCode::OK_200, res->status);
  3717. ASSERT_EQ("DELETED", res->body);
  3718. res = cli_.Get("/person/john4");
  3719. ASSERT_TRUE(res);
  3720. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3721. }
  3722. TEST_F(ServerTest, DeleteMethod2) {
  3723. auto res = cli_.Get("/person/john5");
  3724. ASSERT_TRUE(res);
  3725. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3726. Params params;
  3727. params.emplace("name", "john5");
  3728. params.emplace("note", "developer");
  3729. res = cli_.Post("/person", params);
  3730. ASSERT_TRUE(res);
  3731. ASSERT_EQ(StatusCode::OK_200, res->status);
  3732. res = cli_.Get("/person/john5");
  3733. ASSERT_TRUE(res);
  3734. ASSERT_EQ(StatusCode::OK_200, res->status);
  3735. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3736. ASSERT_EQ("developer", res->body);
  3737. Params delete_params;
  3738. delete_params.emplace("name", "john5");
  3739. Headers headers;
  3740. headers.emplace("Custom-Header", "test-value");
  3741. res = cli_.Delete("/person", headers, delete_params);
  3742. ASSERT_TRUE(res);
  3743. ASSERT_EQ(StatusCode::OK_200, res->status);
  3744. ASSERT_EQ("DELETED", res->body);
  3745. res = cli_.Get("/person/john5");
  3746. ASSERT_TRUE(res);
  3747. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, DeleteMethod3) {
  3750. auto res = cli_.Get("/person/john6");
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3753. Params params;
  3754. params.emplace("name", "john6");
  3755. params.emplace("note", "tester");
  3756. res = cli_.Post("/person", params);
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::OK_200, res->status);
  3759. res = cli_.Get("/person/john6");
  3760. ASSERT_TRUE(res);
  3761. ASSERT_EQ(StatusCode::OK_200, res->status);
  3762. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3763. ASSERT_EQ("tester", res->body);
  3764. Params delete_params;
  3765. delete_params.emplace("name", "john6");
  3766. Headers headers;
  3767. headers.emplace("Custom-Header", "test-value");
  3768. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ("DELETED", res->body);
  3772. res = cli_.Get("/person/john6");
  3773. ASSERT_TRUE(res);
  3774. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3777. Params params;
  3778. params.emplace("json", JSON_DATA);
  3779. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3780. ASSERT_TRUE(res);
  3781. ASSERT_EQ(StatusCode::OK_200, res->status);
  3782. ASSERT_EQ(JSON_DATA, res->body);
  3783. }
  3784. TEST_F(ServerTest, PostEmptyContent) {
  3785. auto res = cli_.Post("/empty", "", "text/plain");
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::OK_200, res->status);
  3788. ASSERT_EQ("empty", res->body);
  3789. }
  3790. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3791. auto res = cli_.Post("/empty-no-content-type");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ("empty-no-content-type", res->body);
  3795. }
  3796. TEST_F(ServerTest, PostPathOnly) {
  3797. auto res = cli_.Post("/path-only");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::OK_200, res->status);
  3800. ASSERT_EQ("path-only", res->body);
  3801. }
  3802. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3803. auto res = cli_.Post("/path-headers-only",
  3804. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3805. ASSERT_TRUE(res);
  3806. ASSERT_EQ(StatusCode::OK_200, res->status);
  3807. ASSERT_EQ("path-headers-only", res->body);
  3808. }
  3809. TEST_F(ServerTest, PostLarge) {
  3810. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. EXPECT_EQ(LARGE_DATA, res->body);
  3814. }
  3815. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3816. auto res = cli_.Put("/empty-no-content-type");
  3817. ASSERT_TRUE(res);
  3818. ASSERT_EQ(StatusCode::OK_200, res->status);
  3819. ASSERT_EQ("empty-no-content-type", res->body);
  3820. }
  3821. TEST_F(ServerTest, GetMethodDir) {
  3822. auto res = cli_.Get("/dir/");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3826. auto body = R"(<html>
  3827. <head>
  3828. </head>
  3829. <body>
  3830. <a href="/dir/test.html">Test</a>
  3831. <a href="/hi">hi</a>
  3832. </body>
  3833. </html>
  3834. )";
  3835. EXPECT_EQ(body, res->body);
  3836. }
  3837. TEST_F(ServerTest, GetMethodDirTest) {
  3838. auto res = cli_.Get("/dir/test.html");
  3839. ASSERT_TRUE(res);
  3840. EXPECT_EQ(StatusCode::OK_200, res->status);
  3841. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3842. EXPECT_EQ("test.html", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3845. auto res = cli_.Get("/dir/../dir/test.html");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ("test.html", res->body);
  3850. }
  3851. TEST_F(ServerTest, GetMethodInvalidPath) {
  3852. auto res = cli_.Get("/dir/../test.html");
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3855. }
  3856. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3857. auto res = cli_.Get("/../www/dir/test.html");
  3858. ASSERT_TRUE(res);
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. }
  3861. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3862. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3865. }
  3866. TEST_F(ServerTest, GetMethodDirMountTest) {
  3867. auto res = cli_.Get("/mount/dir/test.html");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3871. EXPECT_EQ("test.html", res->body);
  3872. }
  3873. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3874. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::OK_200, res->status);
  3877. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3878. EXPECT_EQ("test.html", res->body);
  3879. }
  3880. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3881. auto res = cli_.Get("/mount/dir/../test.html");
  3882. ASSERT_TRUE(res);
  3883. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3884. }
  3885. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3886. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3889. }
  3890. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3891. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3894. }
  3895. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3896. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3899. }
  3900. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3901. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3904. }
  3905. TEST_F(ServerTest, PostMethod303) {
  3906. auto res = cli_.Post("/1", "body", "text/plain");
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3909. EXPECT_EQ("/2", res->get_header_value("Location"));
  3910. }
  3911. TEST_F(ServerTest, PostMethod303Redirect) {
  3912. cli_.set_follow_location(true);
  3913. auto res = cli_.Post("/1", "body", "text/plain");
  3914. ASSERT_TRUE(res);
  3915. EXPECT_EQ(StatusCode::OK_200, res->status);
  3916. EXPECT_EQ("redirected.", res->body);
  3917. EXPECT_EQ("/2", res->location);
  3918. }
  3919. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3920. auto res = cli_.Get("/dir/test.abcde");
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3924. EXPECT_EQ("abcde", res->body);
  3925. }
  3926. TEST_F(ServerTest, StaticFileRange) {
  3927. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3930. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3931. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(true, res->has_header("Content-Range"));
  3933. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3934. EXPECT_EQ(std::string("cd"), res->body);
  3935. }
  3936. TEST_F(ServerTest, StaticFileRanges) {
  3937. auto res =
  3938. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3941. EXPECT_TRUE(
  3942. res->get_header_value("Content-Type")
  3943. .find(
  3944. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3945. 0);
  3946. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3947. }
  3948. TEST_F(ServerTest, StaticFileRangeHead) {
  3949. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3952. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3953. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3954. EXPECT_EQ(true, res->has_header("Content-Range"));
  3955. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3956. }
  3957. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3958. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3962. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3963. EXPECT_EQ(true, res->has_header("Content-Range"));
  3964. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3965. res->get_header_value("Content-Range"));
  3966. EXPECT_EQ("LAST\n", res->body);
  3967. }
  3968. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3969. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3974. EXPECT_EQ(true, res->has_header("Content-Range"));
  3975. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3976. }
  3977. TEST_F(ServerTest, StaticFileBigFile) {
  3978. auto res = cli_.Get("/dir/1MB.txt");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3982. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3983. }
  3984. TEST_F(ServerTest, InvalidBaseDirMount) {
  3985. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3986. }
  3987. TEST_F(ServerTest, Binary) {
  3988. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3989. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3990. "application/octet-stream");
  3991. ASSERT_TRUE(res);
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_EQ(4U, res->body.size());
  3994. res = cli_.Put("/binary", binary.data(), binary.size(),
  3995. "application/octet-stream");
  3996. ASSERT_TRUE(res);
  3997. ASSERT_EQ(StatusCode::OK_200, res->status);
  3998. ASSERT_EQ(4U, res->body.size());
  3999. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4000. "application/octet-stream");
  4001. ASSERT_TRUE(res);
  4002. ASSERT_EQ(StatusCode::OK_200, res->status);
  4003. ASSERT_EQ(4U, res->body.size());
  4004. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4005. "application/octet-stream");
  4006. ASSERT_TRUE(res);
  4007. ASSERT_EQ(StatusCode::OK_200, res->status);
  4008. ASSERT_EQ(4U, res->body.size());
  4009. }
  4010. TEST_F(ServerTest, BinaryString) {
  4011. auto binary = std::string("\x00\x01\x02\x03", 4);
  4012. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4013. ASSERT_TRUE(res);
  4014. ASSERT_EQ(StatusCode::OK_200, res->status);
  4015. ASSERT_EQ(4U, res->body.size());
  4016. res = cli_.Put("/binary", binary, "application/octet-stream");
  4017. ASSERT_TRUE(res);
  4018. ASSERT_EQ(StatusCode::OK_200, res->status);
  4019. ASSERT_EQ(4U, res->body.size());
  4020. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ(4U, res->body.size());
  4024. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::OK_200, res->status);
  4027. ASSERT_EQ(4U, res->body.size());
  4028. }
  4029. TEST_F(ServerTest, EmptyRequest) {
  4030. auto res = cli_.Get("");
  4031. ASSERT_TRUE(!res);
  4032. EXPECT_EQ(Error::Connection, res.error());
  4033. }
  4034. TEST_F(ServerTest, LongRequest) {
  4035. std::string request;
  4036. for (size_t i = 0; i < 545; i++) {
  4037. request += "/TooLongRequest";
  4038. }
  4039. request += "OK";
  4040. auto res = cli_.Get(request.c_str());
  4041. ASSERT_TRUE(res);
  4042. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4043. }
  4044. TEST_F(ServerTest, TooLongRequest) {
  4045. std::string request;
  4046. for (size_t i = 0; i < 546; i++) {
  4047. request += "/TooLongRequest";
  4048. }
  4049. request += "_NG";
  4050. auto start = std::chrono::high_resolution_clock::now();
  4051. cli_.set_keep_alive(true);
  4052. auto res = cli_.Get(request.c_str());
  4053. auto end = std::chrono::high_resolution_clock::now();
  4054. auto elapsed =
  4055. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4056. .count();
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4059. EXPECT_LE(elapsed, 1000);
  4060. EXPECT_EQ("close", res->get_header_value("Connection"));
  4061. EXPECT_FALSE(cli_.is_socket_open());
  4062. }
  4063. TEST_F(ServerTest, AlmostTooLongRequest) {
  4064. // test for #2046 - URI length check shouldn't include other content on req
  4065. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4066. // leading /, space, HTTP/1.1)
  4067. std::string request =
  4068. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4069. auto res = cli_.Get(request.c_str());
  4070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4072. }
  4073. TEST_F(ServerTest, LongHeader) {
  4074. Request req;
  4075. req.method = "GET";
  4076. req.path = "/hi";
  4077. std::string host_and_port;
  4078. host_and_port += HOST;
  4079. host_and_port += ":";
  4080. host_and_port += std::to_string(PORT);
  4081. req.headers.emplace("Host", host_and_port.c_str());
  4082. req.headers.emplace("Accept", "*/*");
  4083. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4084. req.headers.emplace(
  4085. "Header-Name",
  4086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4114. "@@@@@@@@@@@@@@@@");
  4115. auto res = std::make_shared<Response>();
  4116. auto error = Error::Success;
  4117. auto ret = cli_.send(req, *res, error);
  4118. ASSERT_TRUE(ret);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. }
  4121. TEST_F(ServerTest, LongQueryValue) {
  4122. auto start = std::chrono::high_resolution_clock::now();
  4123. cli_.set_keep_alive(true);
  4124. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4125. auto end = std::chrono::high_resolution_clock::now();
  4126. auto elapsed =
  4127. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4128. .count();
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4131. EXPECT_LE(elapsed, 1000);
  4132. EXPECT_EQ("close", res->get_header_value("Connection"));
  4133. EXPECT_FALSE(cli_.is_socket_open());
  4134. }
  4135. TEST_F(ServerTest, TooLongQueryValue) {
  4136. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4137. ASSERT_FALSE(res);
  4138. EXPECT_EQ(Error::Read, res.error());
  4139. }
  4140. TEST_F(ServerTest, TooLongHeader) {
  4141. Request req;
  4142. req.method = "GET";
  4143. req.path = "/hi";
  4144. std::string host_and_port;
  4145. host_and_port += HOST;
  4146. host_and_port += ":";
  4147. host_and_port += std::to_string(PORT);
  4148. req.headers.emplace("Host", host_and_port.c_str());
  4149. req.headers.emplace("Accept", "*/*");
  4150. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4151. req.headers.emplace(
  4152. "Header-Name",
  4153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4181. "@@@@@@@@@@@@@@@@@");
  4182. auto res = std::make_shared<Response>();
  4183. auto error = Error::Success;
  4184. auto ret = cli_.send(req, *res, error);
  4185. ASSERT_TRUE(ret);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. }
  4188. TEST_F(ServerTest, HeaderCountAtLimit) {
  4189. // Test with headers just under the 100 limit
  4190. httplib::Headers headers;
  4191. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4192. // This should keep us just under the 100 header limit
  4193. for (int i = 0; i < 95; i++) {
  4194. std::string name = "X-Test-Header-" + std::to_string(i);
  4195. std::string value = "value" + std::to_string(i);
  4196. headers.emplace(name, value);
  4197. }
  4198. // This should work fine as we're under the limit
  4199. auto res = cli_.Get("/hi", headers);
  4200. EXPECT_TRUE(res);
  4201. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4202. }
  4203. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4204. // Test with many headers to exceed the 100 limit
  4205. httplib::Headers headers;
  4206. // Add 150 headers to definitely exceed the 100 limit
  4207. for (int i = 0; i < 150; i++) {
  4208. std::string name = "X-Test-Header-" + std::to_string(i);
  4209. std::string value = "value" + std::to_string(i);
  4210. headers.emplace(name, value);
  4211. }
  4212. // This should fail due to exceeding header count limit
  4213. cli_.set_keep_alive(true);
  4214. auto res = cli_.Get("/hi", headers);
  4215. // The server should respond with 400 Bad Request
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4218. EXPECT_EQ("close", res->get_header_value("Connection"));
  4219. EXPECT_FALSE(cli_.is_socket_open());
  4220. }
  4221. TEST_F(ServerTest, PercentEncoding) {
  4222. auto res = cli_.Get("/e%6edwith%");
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::OK_200, res->status);
  4225. }
  4226. TEST_F(ServerTest, PercentEncodingUnicode) {
  4227. auto res = cli_.Get("/e%u006edwith%");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST_F(ServerTest, InvalidPercentEncoding) {
  4232. auto res = cli_.Get("/%endwith%");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4235. }
  4236. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4237. auto res = cli_.Get("/%uendwith%");
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4240. }
  4241. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4242. auto res = cli_.Get("/hello?aaa=bbb%");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4245. }
  4246. TEST_F(ServerTest, PlusSignEncoding) {
  4247. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("a +b", res->body);
  4251. }
  4252. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4253. // This test simulates a potential DoS attack using many headers
  4254. // to verify our security fix prevents memory exhaustion
  4255. httplib::Headers attack_headers;
  4256. // Attempt to add many headers like an attacker would (200 headers to far
  4257. // exceed limit)
  4258. for (int i = 0; i < 200; i++) {
  4259. std::string name = "X-Attack-Header-" + std::to_string(i);
  4260. std::string value = "attack_payload_" + std::to_string(i);
  4261. attack_headers.emplace(name, value);
  4262. }
  4263. // Try to POST with excessive headers
  4264. cli_.set_keep_alive(true);
  4265. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4266. // Should either fail or return 400 Bad Request due to security limit
  4267. if (res) {
  4268. // If we get a response, it should be 400 Bad Request
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ("close", res->get_header_value("Connection"));
  4271. }
  4272. EXPECT_FALSE(cli_.is_socket_open());
  4273. }
  4274. TEST_F(ServerTest, MultipartFormData) {
  4275. UploadFormDataItems items = {
  4276. {"text1", "text default", "", ""},
  4277. {"text2", "aωb", "", ""},
  4278. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4279. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4280. {"file3", "", "", "application/octet-stream"},
  4281. {"file4", "", "", " application/json tmp-string "}};
  4282. auto res = cli_.Post("/multipart", items);
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. }
  4286. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4287. UploadFormDataItems items = {
  4288. {"text", "default text", "", ""},
  4289. {"multi_text1", "aaaaa", "", ""},
  4290. {"multi_text1", "bbbbb", "", ""},
  4291. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4292. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4293. "application/json"},
  4294. };
  4295. auto res = cli_.Post("/multipart/multi_file_values", items);
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. }
  4299. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4300. auto res = cli_.Get("/hi");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4304. EXPECT_EQ("Hello World!", res->body);
  4305. }
  4306. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4307. Request req;
  4308. req.method = "POST";
  4309. req.path = "/chunked";
  4310. std::string host_and_port;
  4311. host_and_port += HOST;
  4312. host_and_port += ":";
  4313. host_and_port += std::to_string(PORT);
  4314. req.headers.emplace("Host", host_and_port.c_str());
  4315. req.headers.emplace("Accept", "*/*");
  4316. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4317. req.headers.emplace("Content-Type", "text/plain");
  4318. req.headers.emplace("Content-Length", "0");
  4319. req.headers.emplace(
  4320. "Transfer-Encoding",
  4321. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4322. // Client does not chunk, so make a chunked body manually.
  4323. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4324. auto res = std::make_shared<Response>();
  4325. auto error = Error::Success;
  4326. auto ret = cli_.send(req, *res, error);
  4327. ASSERT_TRUE(ret);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. }
  4330. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4331. // rather than treat them as valid lengths.
  4332. template <typename ClientT>
  4333. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4334. Request req;
  4335. req.method = "POST";
  4336. req.path = "/chunked";
  4337. std::string host_and_port;
  4338. host_and_port += HOST;
  4339. host_and_port += ":";
  4340. host_and_port += std::to_string(PORT);
  4341. req.headers.emplace("Host", host_and_port.c_str());
  4342. req.headers.emplace("Content-Length", "0");
  4343. req.headers.emplace("Transfer-Encoding", "chunked");
  4344. req.body = body;
  4345. auto res = std::make_shared<Response>();
  4346. auto error = Error::Success;
  4347. ASSERT_TRUE(cli.send(req, *res, error));
  4348. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4349. }
  4350. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4351. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4352. }
  4353. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4354. expect_chunked_body_rejected(
  4355. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4356. }
  4357. TEST_F(ServerTest, GetStreamed2) {
  4358. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4361. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4362. EXPECT_EQ(true, res->has_header("Content-Range"));
  4363. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4364. EXPECT_EQ(std::string("ab"), res->body);
  4365. }
  4366. TEST_F(ServerTest, GetStreamed) {
  4367. auto res = cli_.Get("/streamed");
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4371. EXPECT_EQ(std::string("aaabbb"), res->body);
  4372. }
  4373. TEST_F(ServerTest, GetStreamedWithRange1) {
  4374. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4377. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4378. EXPECT_EQ(true, res->has_header("Content-Range"));
  4379. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4380. EXPECT_EQ(std::string("def"), res->body);
  4381. }
  4382. TEST_F(ServerTest, GetStreamedWithRange2) {
  4383. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4386. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4387. EXPECT_EQ(true, res->has_header("Content-Range"));
  4388. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4389. EXPECT_EQ(std::string("bcdefg"), res->body);
  4390. }
  4391. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4392. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4393. ASSERT_TRUE(res);
  4394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4395. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4396. EXPECT_EQ(true, res->has_header("Content-Range"));
  4397. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4398. EXPECT_EQ(std::string("efg"), res->body);
  4399. }
  4400. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4401. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4404. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4405. EXPECT_EQ(false, res->has_header("Content-Range"));
  4406. EXPECT_EQ(0U, res->body.size());
  4407. }
  4408. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4409. auto res = cli_.Get("/streamed-with-range",
  4410. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4411. "92233720368547758079223372036854775807"}});
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4414. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4415. EXPECT_EQ(false, res->has_header("Content-Range"));
  4416. EXPECT_EQ(0U, res->body.size());
  4417. }
  4418. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4419. auto res = cli_.Get(
  4420. "/with-range",
  4421. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4422. {"Accept-Encoding", ""}});
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4425. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4426. EXPECT_EQ(true, res->has_header("Content-Range"));
  4427. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4428. EXPECT_EQ(std::string("abcdefg"), res->body);
  4429. }
  4430. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4431. auto res = cli_.Get("/with-range", {
  4432. {"Range", "bytes=0-"},
  4433. {"Accept-Encoding", ""},
  4434. });
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4437. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4438. EXPECT_EQ(true, res->has_header("Content-Range"));
  4439. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4440. EXPECT_EQ(std::string("abcdefg"), res->body);
  4441. }
  4442. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4443. auto res =
  4444. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4445. ASSERT_TRUE(res);
  4446. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4447. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4448. EXPECT_EQ(false, res->has_header("Content-Range"));
  4449. EXPECT_EQ(267U, res->body.size());
  4450. // Check that both range contents are present
  4451. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4452. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4453. // Check that Content-Range headers are present for both ranges
  4454. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4455. std::string::npos);
  4456. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4457. std::string::npos);
  4458. }
  4459. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4460. Ranges ranges;
  4461. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4462. ranges.emplace_back(0, -1);
  4463. }
  4464. auto res =
  4465. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4466. ASSERT_TRUE(res);
  4467. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4468. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4469. EXPECT_EQ(false, res->has_header("Content-Range"));
  4470. EXPECT_EQ(0U, res->body.size());
  4471. }
  4472. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4473. auto res =
  4474. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4475. ASSERT_TRUE(res);
  4476. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4477. EXPECT_EQ(5U, res->body.size());
  4478. // Check that overlapping ranges are coalesced into a single range
  4479. EXPECT_EQ("bcdef", res->body);
  4480. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4481. // Should be single range, not multipart
  4482. EXPECT_TRUE(res->has_header("Content-Range"));
  4483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4484. }
  4485. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4486. auto res =
  4487. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4488. ASSERT_TRUE(res);
  4489. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4490. EXPECT_EQ(268U, res->body.size());
  4491. // Check that both range contents are present
  4492. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4493. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4494. // Check that Content-Range headers are present for both ranges
  4495. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4496. std::string::npos);
  4497. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4498. std::string::npos);
  4499. }
  4500. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4501. auto res =
  4502. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4503. ASSERT_TRUE(res);
  4504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4505. EXPECT_EQ(269U, res->body.size());
  4506. // Check that both duplicate range contents are present
  4507. size_t first_abc = res->body.find("abc\r\n");
  4508. EXPECT_TRUE(first_abc != std::string::npos);
  4509. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4510. EXPECT_TRUE(second_abc != std::string::npos);
  4511. // Check that Content-Range headers are present for both ranges
  4512. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4513. EXPECT_TRUE(first_range != std::string::npos);
  4514. size_t second_range =
  4515. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4516. EXPECT_TRUE(second_range != std::string::npos);
  4517. }
  4518. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4519. auto res = cli_.Get("/streamed-with-range?error",
  4520. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4523. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4524. EXPECT_EQ(false, res->has_header("Content-Range"));
  4525. EXPECT_EQ(0U, res->body.size());
  4526. }
  4527. TEST_F(ServerTest, GetStreamedEndless) {
  4528. uint64_t offset = 0;
  4529. auto res = cli_.Get("/streamed-cancel",
  4530. [&](const char * /*data*/, uint64_t data_length) {
  4531. if (offset < 100) {
  4532. offset += data_length;
  4533. return true;
  4534. }
  4535. return false;
  4536. });
  4537. ASSERT_TRUE(!res);
  4538. EXPECT_EQ(Error::Canceled, res.error());
  4539. }
  4540. TEST_F(ServerTest, ClientStop) {
  4541. std::atomic_size_t count{4};
  4542. std::vector<std::thread> threads;
  4543. for (auto i = count.load(); i != 0; --i) {
  4544. threads.emplace_back([&]() {
  4545. auto res = cli_.Get("/streamed-cancel",
  4546. [&](const char *, uint64_t) { return true; });
  4547. --count;
  4548. ASSERT_TRUE(!res);
  4549. EXPECT_TRUE(res.error() == Error::Canceled ||
  4550. res.error() == Error::Read || res.error() == Error::Write);
  4551. });
  4552. }
  4553. std::this_thread::sleep_for(std::chrono::seconds(2));
  4554. while (count != 0) {
  4555. cli_.stop();
  4556. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4557. }
  4558. for (auto &t : threads) {
  4559. t.join();
  4560. }
  4561. }
  4562. TEST_F(ServerTest, GetWithRange1) {
  4563. auto res = cli_.Get("/with-range", {
  4564. make_range_header({{3, 5}}),
  4565. {"Accept-Encoding", ""},
  4566. });
  4567. ASSERT_TRUE(res);
  4568. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4569. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4570. EXPECT_EQ(true, res->has_header("Content-Range"));
  4571. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4572. EXPECT_EQ(std::string("def"), res->body);
  4573. }
  4574. TEST_F(ServerTest, GetWithRange2) {
  4575. auto res = cli_.Get("/with-range", {
  4576. make_range_header({{1, -1}}),
  4577. {"Accept-Encoding", ""},
  4578. });
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4581. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4582. EXPECT_EQ(true, res->has_header("Content-Range"));
  4583. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4584. EXPECT_EQ(std::string("bcdefg"), res->body);
  4585. }
  4586. TEST_F(ServerTest, GetWithRange3) {
  4587. auto res = cli_.Get("/with-range", {
  4588. make_range_header({{0, 0}}),
  4589. {"Accept-Encoding", ""},
  4590. });
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4593. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4594. EXPECT_EQ(true, res->has_header("Content-Range"));
  4595. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4596. EXPECT_EQ(std::string("a"), res->body);
  4597. }
  4598. TEST_F(ServerTest, GetWithRange4) {
  4599. auto res = cli_.Get("/with-range", {
  4600. make_range_header({{-1, 2}}),
  4601. {"Accept-Encoding", ""},
  4602. });
  4603. ASSERT_TRUE(res);
  4604. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4605. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4606. EXPECT_EQ(true, res->has_header("Content-Range"));
  4607. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4608. EXPECT_EQ(std::string("fg"), res->body);
  4609. }
  4610. TEST_F(ServerTest, GetWithRange5) {
  4611. auto res = cli_.Get("/with-range", {
  4612. make_range_header({{0, 5}}),
  4613. {"Accept-Encoding", ""},
  4614. });
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4617. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4618. EXPECT_EQ(true, res->has_header("Content-Range"));
  4619. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4620. EXPECT_EQ(std::string("abcdef"), res->body);
  4621. }
  4622. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4623. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4624. ASSERT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4626. }
  4627. TEST_F(ServerTest, GetWithRangeMultipart) {
  4628. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4631. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4632. EXPECT_EQ(false, res->has_header("Content-Range"));
  4633. EXPECT_EQ(267U, res->body.size());
  4634. }
  4635. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4636. auto res =
  4637. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4640. }
  4641. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4642. auto res = cli_.Get("/with-range-customized-response",
  4643. {{make_range_header({{1, 2}})}});
  4644. ASSERT_TRUE(res);
  4645. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4646. EXPECT_EQ(true, res->has_header("Content-Length"));
  4647. EXPECT_EQ(false, res->has_header("Content-Range"));
  4648. EXPECT_EQ(JSON_DATA, res->body);
  4649. }
  4650. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4651. auto res = cli_.Get("/with-range-customized-response",
  4652. {{make_range_header({{1, 2}, {4, 5}})}});
  4653. ASSERT_TRUE(res);
  4654. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4655. EXPECT_EQ(true, res->has_header("Content-Length"));
  4656. EXPECT_EQ(false, res->has_header("Content-Range"));
  4657. EXPECT_EQ(JSON_DATA, res->body);
  4658. }
  4659. TEST_F(ServerTest, Issue1772) {
  4660. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4661. ASSERT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4663. }
  4664. TEST_F(ServerTest, Issue609) {
  4665. auto res = cli_.Delete("/issue609");
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ(std::string("ok"), res->body);
  4669. }
  4670. TEST_F(ServerTest, GetStreamedChunked) {
  4671. auto res = cli_.Get("/streamed-chunked");
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. EXPECT_EQ(std::string("123456789"), res->body);
  4675. }
  4676. TEST_F(ServerTest, GetStreamedChunked2) {
  4677. auto res = cli_.Get("/streamed-chunked2");
  4678. ASSERT_TRUE(res);
  4679. EXPECT_EQ(StatusCode::OK_200, res->status);
  4680. EXPECT_EQ(std::string("123456789"), res->body);
  4681. }
  4682. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4683. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4684. ASSERT_TRUE(res);
  4685. EXPECT_EQ(StatusCode::OK_200, res->status);
  4686. EXPECT_EQ(std::string("123456789"), res->body);
  4687. EXPECT_TRUE(res->has_header("Trailer"));
  4688. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4689. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4690. // Trailers are now stored separately from headers (security fix)
  4691. EXPECT_EQ(2U, res->trailers.size());
  4692. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4693. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4694. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4695. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4696. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4697. // Verify trailers are NOT in headers (security verification)
  4698. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4699. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4700. }
  4701. TEST_F(ServerTest, LargeChunkedPost) {
  4702. Request req;
  4703. req.method = "POST";
  4704. req.path = "/large-chunked";
  4705. std::string host_and_port;
  4706. host_and_port += HOST;
  4707. host_and_port += ":";
  4708. host_and_port += std::to_string(PORT);
  4709. req.headers.emplace("Host", host_and_port.c_str());
  4710. req.headers.emplace("Accept", "*/*");
  4711. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4712. req.headers.emplace("Content-Type", "text/plain");
  4713. req.headers.emplace("Content-Length", "0");
  4714. req.headers.emplace("Transfer-Encoding", "chunked");
  4715. std::string long_string(30 * 1024u, 'a');
  4716. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4717. // Attempt to make a large enough post to exceed OS buffers, to test that
  4718. // the server handles short reads if the full chunk data isn't available.
  4719. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4720. auto res = std::make_shared<Response>();
  4721. auto error = Error::Success;
  4722. auto ret = cli_.send(req, *res, error);
  4723. ASSERT_TRUE(ret);
  4724. EXPECT_EQ(StatusCode::OK_200, res->status);
  4725. }
  4726. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4727. auto res = cli_.Get("/remote_addr");
  4728. ASSERT_TRUE(res);
  4729. EXPECT_EQ(StatusCode::OK_200, res->status);
  4730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4731. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4732. }
  4733. TEST_F(ServerTest, GetMethodLocalAddr) {
  4734. auto res = cli_.Get("/local_addr");
  4735. ASSERT_TRUE(res);
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4738. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4739. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4740. }
  4741. TEST_F(ServerTest, HTTPResponseSplitting) {
  4742. auto res = cli_.Get("/http_response_splitting");
  4743. ASSERT_TRUE(res);
  4744. EXPECT_EQ(StatusCode::OK_200, res->status);
  4745. }
  4746. TEST_F(ServerTest, SlowRequest) {
  4747. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4748. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4749. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4750. }
  4751. #if 0
  4752. TEST_F(ServerTest, SlowPost) {
  4753. char buffer[64 * 1024];
  4754. memset(buffer, 0x42, sizeof(buffer));
  4755. auto res = cli_.Post(
  4756. "/slowpost", 64 * 1024 * 1024,
  4757. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4758. auto ret = sink.write(buffer, sizeof(buffer));
  4759. EXPECT_TRUE(ret);
  4760. return true;
  4761. },
  4762. "text/plain");
  4763. ASSERT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. }
  4766. TEST_F(ServerTest, SlowPostFail) {
  4767. char buffer[64 * 1024];
  4768. memset(buffer, 0x42, sizeof(buffer));
  4769. cli_.set_write_timeout(std::chrono::seconds(0));
  4770. auto res = cli_.Post(
  4771. "/slowpost", 64 * 1024 * 1024,
  4772. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4773. sink.write(buffer, sizeof(buffer));
  4774. return true;
  4775. },
  4776. "text/plain");
  4777. ASSERT_TRUE(!res);
  4778. EXPECT_EQ(Error::Write, res.error());
  4779. }
  4780. #endif
  4781. TEST_F(ServerTest, Put) {
  4782. auto res = cli_.Put("/put", "PUT", "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PUT", res->body);
  4786. }
  4787. TEST_F(ServerTest, PutWithContentProvider) {
  4788. auto res = cli_.Put(
  4789. "/put", 3,
  4790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4791. sink.os << "PUT";
  4792. return true;
  4793. },
  4794. "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("PUT", res->body);
  4798. }
  4799. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4800. auto res = cli_.Post(
  4801. "/post", 42,
  4802. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4803. return false;
  4804. },
  4805. "text/plain");
  4806. ASSERT_TRUE(!res);
  4807. EXPECT_EQ(Error::Canceled, res.error());
  4808. }
  4809. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4810. auto res = cli_.Put(
  4811. "/put",
  4812. [](size_t /*offset*/, DataSink &sink) {
  4813. sink.os << "PUT";
  4814. sink.done();
  4815. return true;
  4816. },
  4817. "text/plain");
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. EXPECT_EQ("PUT", res->body);
  4821. }
  4822. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4823. auto res = cli_.Post(
  4824. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4825. "text/plain");
  4826. ASSERT_TRUE(!res);
  4827. EXPECT_EQ(Error::Canceled, res.error());
  4828. }
  4829. TEST_F(ServerTest, PostLoopBack) {
  4830. std::string body;
  4831. auto res = cli_.Post(
  4832. "/post-loopback", 9,
  4833. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4834. EXPECT_EQ(9u, length);
  4835. sink.write("123", 3);
  4836. sink.write("456", 3);
  4837. sink.write("789", 3);
  4838. return true;
  4839. },
  4840. "text/plain",
  4841. [&body](const char *data, size_t data_length) {
  4842. body.append(data, data_length);
  4843. return true;
  4844. });
  4845. ASSERT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::OK_200, res->status);
  4847. EXPECT_EQ("123456789", body);
  4848. }
  4849. TEST_F(ServerTest, PutLoopBack) {
  4850. std::string body;
  4851. auto res = cli_.Put(
  4852. "/put-loopback", 9,
  4853. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4854. EXPECT_EQ(9u, length);
  4855. sink.write("123", 3);
  4856. sink.write("456", 3);
  4857. sink.write("789", 3);
  4858. return true;
  4859. },
  4860. "text/plain",
  4861. [&body](const char *data, size_t data_length) {
  4862. body.append(data, data_length);
  4863. return true;
  4864. });
  4865. ASSERT_TRUE(res);
  4866. EXPECT_EQ(StatusCode::OK_200, res->status);
  4867. EXPECT_EQ("123456789", body);
  4868. }
  4869. TEST_F(ServerTest, PatchLoopBack) {
  4870. std::string body;
  4871. auto res = cli_.Patch(
  4872. "/patch-loopback", 9,
  4873. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4874. EXPECT_EQ(9u, length);
  4875. sink.write("123", 3);
  4876. sink.write("456", 3);
  4877. sink.write("789", 3);
  4878. return true;
  4879. },
  4880. "text/plain",
  4881. [&body](const char *data, size_t data_length) {
  4882. body.append(data, data_length);
  4883. return true;
  4884. });
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. EXPECT_EQ("123456789", body);
  4888. }
  4889. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4890. std::string body;
  4891. auto res = cli_.Post(
  4892. "/post-loopback",
  4893. [](size_t /*offset*/, DataSink &sink) {
  4894. sink.write("123", 3);
  4895. sink.write("456", 3);
  4896. sink.write("789", 3);
  4897. sink.done();
  4898. return true;
  4899. },
  4900. "text/plain",
  4901. [&body](const char *data, size_t data_length) {
  4902. body.append(data, data_length);
  4903. return true;
  4904. });
  4905. ASSERT_TRUE(res);
  4906. EXPECT_EQ(StatusCode::OK_200, res->status);
  4907. EXPECT_EQ("123456789", body);
  4908. }
  4909. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4910. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4911. cli_.set_compress(true);
  4912. auto res = cli_.Put(
  4913. "/put", 3,
  4914. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4915. sink.os << "PUT";
  4916. return true;
  4917. },
  4918. "text/plain");
  4919. ASSERT_TRUE(res);
  4920. EXPECT_EQ(StatusCode::OK_200, res->status);
  4921. EXPECT_EQ("PUT", res->body);
  4922. }
  4923. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4924. cli_.set_compress(true);
  4925. auto res = cli_.Post(
  4926. "/post", 42,
  4927. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4928. return false;
  4929. },
  4930. "text/plain");
  4931. ASSERT_TRUE(!res);
  4932. EXPECT_EQ(Error::Canceled, res.error());
  4933. }
  4934. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4935. cli_.set_compress(true);
  4936. auto res = cli_.Put(
  4937. "/put",
  4938. [](size_t /*offset*/, DataSink &sink) {
  4939. sink.os << "PUT";
  4940. sink.done();
  4941. return true;
  4942. },
  4943. "text/plain");
  4944. ASSERT_TRUE(res);
  4945. EXPECT_EQ(StatusCode::OK_200, res->status);
  4946. EXPECT_EQ("PUT", res->body);
  4947. }
  4948. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4949. cli_.set_compress(true);
  4950. auto res = cli_.Post(
  4951. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4952. "text/plain");
  4953. ASSERT_TRUE(!res);
  4954. EXPECT_EQ(Error::Canceled, res.error());
  4955. }
  4956. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4957. cli_.set_compress(true);
  4958. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4959. ASSERT_TRUE(res);
  4960. EXPECT_EQ(StatusCode::OK_200, res->status);
  4961. EXPECT_EQ(LARGE_DATA, res->body);
  4962. }
  4963. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4964. #ifdef CPPHTTPLIB_SSL_ENABLED
  4965. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4966. Client cli(s.c_str());
  4967. cli.enable_server_certificate_verification(false);
  4968. #else
  4969. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4970. Client cli(s.c_str());
  4971. #endif
  4972. cli.set_compress(true);
  4973. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. EXPECT_EQ(LARGE_DATA, res->body);
  4977. // The compressed size should be less than a 10th of the original. May vary
  4978. // depending on the zlib library.
  4979. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4980. static_cast<uint64_t>(10 * 1024 * 1024));
  4981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4982. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4983. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4984. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4985. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4986. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4987. #endif
  4988. }
  4989. TEST_F(ServerTest, PutContentWithDeflate) {
  4990. cli_.set_compress(false);
  4991. Headers headers;
  4992. headers.emplace("Content-Encoding", "deflate");
  4993. // PUT in deflate format:
  4994. auto res = cli_.Put("/put", headers,
  4995. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4996. ASSERT_TRUE(res);
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("PUT", res->body);
  4999. }
  5000. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5001. Headers headers;
  5002. headers.emplace("Accept-Encoding", "gzip, deflate");
  5003. auto res = cli_.Get("/streamed-chunked", headers);
  5004. ASSERT_TRUE(res);
  5005. EXPECT_EQ(StatusCode::OK_200, res->status);
  5006. EXPECT_EQ(std::string("123456789"), res->body);
  5007. }
  5008. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5009. Headers headers;
  5010. headers.emplace("Accept-Encoding", "gzip, deflate");
  5011. auto res = cli_.Get("/streamed-chunked2", headers);
  5012. ASSERT_TRUE(res);
  5013. EXPECT_EQ(StatusCode::OK_200, res->status);
  5014. EXPECT_EQ(std::string("123456789"), res->body);
  5015. }
  5016. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5017. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5018. ASSERT_TRUE(res);
  5019. EXPECT_EQ(StatusCode::OK_200, res->status);
  5020. }
  5021. TEST(GzipDecompressor, ChunkedDecompression) {
  5022. std::string data;
  5023. for (size_t i = 0; i < 32 * 1024; ++i) {
  5024. data.push_back(static_cast<char>('a' + i % 26));
  5025. }
  5026. std::string compressed_data;
  5027. {
  5028. httplib::detail::gzip_compressor compressor;
  5029. bool result = compressor.compress(
  5030. data.data(), data.size(),
  5031. /*last=*/true,
  5032. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5033. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5034. compressed_data_size);
  5035. return true;
  5036. });
  5037. ASSERT_TRUE(result);
  5038. }
  5039. std::string decompressed_data;
  5040. {
  5041. httplib::detail::gzip_decompressor decompressor;
  5042. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5043. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5044. size_t chunk_size = 130;
  5045. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5046. chunk_begin += chunk_size) {
  5047. size_t current_chunk_size =
  5048. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5049. bool result = decompressor.decompress(
  5050. compressed_data.data() + chunk_begin, current_chunk_size,
  5051. [&](const char *decompressed_data_chunk,
  5052. size_t decompressed_data_chunk_size) {
  5053. decompressed_data.insert(decompressed_data.size(),
  5054. decompressed_data_chunk,
  5055. decompressed_data_chunk_size);
  5056. return true;
  5057. });
  5058. ASSERT_TRUE(result);
  5059. }
  5060. }
  5061. ASSERT_EQ(data, decompressed_data);
  5062. }
  5063. TEST(GzipDecompressor, DeflateDecompression) {
  5064. std::string original_text = "Raw deflate without gzip";
  5065. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5066. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5067. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5068. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5069. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5070. std::string decompressed_data;
  5071. {
  5072. httplib::detail::gzip_decompressor decompressor;
  5073. bool result = decompressor.decompress(
  5074. compressed_data.data(), compressed_data.size(),
  5075. [&](const char *decompressed_data_chunk,
  5076. size_t decompressed_data_chunk_size) {
  5077. decompressed_data.insert(decompressed_data.size(),
  5078. decompressed_data_chunk,
  5079. decompressed_data_chunk_size);
  5080. return true;
  5081. });
  5082. ASSERT_TRUE(result);
  5083. }
  5084. ASSERT_EQ(original_text, decompressed_data);
  5085. }
  5086. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5087. std::string original_text = "Raw deflate without gzip";
  5088. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5089. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5090. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5091. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5092. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5093. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5094. std::string decompressed_data;
  5095. {
  5096. httplib::detail::gzip_decompressor decompressor;
  5097. bool result = decompressor.decompress(
  5098. compressed_data.data(), compressed_data.size(),
  5099. [&](const char *decompressed_data_chunk,
  5100. size_t decompressed_data_chunk_size) {
  5101. decompressed_data.insert(decompressed_data.size(),
  5102. decompressed_data_chunk,
  5103. decompressed_data_chunk_size);
  5104. return true;
  5105. });
  5106. ASSERT_TRUE(result);
  5107. }
  5108. ASSERT_EQ(original_text, decompressed_data);
  5109. }
  5110. #endif
  5111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5112. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5113. Headers headers;
  5114. headers.emplace("Accept-Encoding", "br");
  5115. auto res = cli_.Get("/streamed-chunked", headers);
  5116. ASSERT_TRUE(res);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. EXPECT_EQ(std::string("123456789"), res->body);
  5119. }
  5120. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5121. Headers headers;
  5122. headers.emplace("Accept-Encoding", "br");
  5123. auto res = cli_.Get("/streamed-chunked2", headers);
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ(std::string("123456789"), res->body);
  5127. }
  5128. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5129. cli_.set_compress(true);
  5130. auto res = cli_.Put(
  5131. "/put", 3,
  5132. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5133. sink.os << "PUT";
  5134. return true;
  5135. },
  5136. "text/plain");
  5137. ASSERT_TRUE(res);
  5138. EXPECT_EQ(StatusCode::OK_200, res->status);
  5139. EXPECT_EQ("PUT", res->body);
  5140. }
  5141. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5142. cli_.set_compress(true);
  5143. auto res = cli_.Put(
  5144. "/put",
  5145. [](size_t /*offset*/, DataSink &sink) {
  5146. sink.os << "PUT";
  5147. sink.done();
  5148. return true;
  5149. },
  5150. "text/plain");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("PUT", res->body);
  5154. }
  5155. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5156. cli_.set_compress(true);
  5157. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5158. ASSERT_TRUE(res);
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. EXPECT_EQ(LARGE_DATA, res->body);
  5161. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5162. }
  5163. #endif
  5164. TEST_F(ServerTest, Patch) {
  5165. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5166. ASSERT_TRUE(res);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. EXPECT_EQ("PATCH", res->body);
  5169. }
  5170. TEST_F(ServerTest, Delete) {
  5171. auto res = cli_.Delete("/delete");
  5172. ASSERT_TRUE(res);
  5173. EXPECT_EQ(StatusCode::OK_200, res->status);
  5174. EXPECT_EQ("DELETE", res->body);
  5175. }
  5176. TEST_F(ServerTest, DeleteContentReceiver) {
  5177. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5178. ASSERT_TRUE(res);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("content", res->body);
  5181. }
  5182. TEST_F(ServerTest, Options) {
  5183. auto res = cli_.Options("*");
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::OK_200, res->status);
  5186. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5187. EXPECT_TRUE(res->body.empty());
  5188. }
  5189. TEST_F(ServerTest, URL) {
  5190. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5191. ASSERT_TRUE(res);
  5192. EXPECT_EQ(StatusCode::OK_200, res->status);
  5193. }
  5194. TEST_F(ServerTest, ArrayParam) {
  5195. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5196. ASSERT_TRUE(res);
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. }
  5199. TEST_F(ServerTest, ArrayParamValues) {
  5200. auto res =
  5201. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5202. ASSERT_TRUE(res);
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. }
  5205. TEST_F(ServerTest, NoMultipleHeaders) {
  5206. Headers headers = {{"Content-Length", "5"}};
  5207. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5208. "text/plain");
  5209. ASSERT_TRUE(res);
  5210. EXPECT_EQ(StatusCode::OK_200, res->status);
  5211. }
  5212. TEST_F(ServerTest, PostContentReceiver) {
  5213. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5214. ASSERT_TRUE(res);
  5215. ASSERT_EQ(StatusCode::OK_200, res->status);
  5216. ASSERT_EQ("content", res->body);
  5217. }
  5218. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5219. UploadFormDataItems items = {
  5220. {"text1", "text default", "", ""},
  5221. {"text2", "aωb", "", ""},
  5222. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5223. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5224. {"file3", "", "", "application/octet-stream"},
  5225. };
  5226. auto res = cli_.Post("/content_receiver", items);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. }
  5230. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5231. UploadFormDataItems items = {
  5232. {"text1", "text default", "", ""},
  5233. {"text2", "aωb", "", ""},
  5234. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5235. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5236. {"file3", "", "", "application/octet-stream"},
  5237. };
  5238. auto boundary = std::string("+++++");
  5239. std::string body;
  5240. for (const auto &item : items) {
  5241. body += "--" + boundary + "\r\n";
  5242. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5243. if (!item.filename.empty()) {
  5244. body += "; filename=\"" + item.filename + "\"";
  5245. }
  5246. body += "\r\n";
  5247. if (!item.content_type.empty()) {
  5248. body += "Content-Type: " + item.content_type + "\r\n";
  5249. }
  5250. body += "\r\n";
  5251. body += item.content + "\r\n";
  5252. }
  5253. body += "--" + boundary + "--\r\n";
  5254. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5255. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5256. ASSERT_TRUE(res);
  5257. EXPECT_EQ(StatusCode::OK_200, res->status);
  5258. }
  5259. TEST_F(ServerTest, PostContentReceiverGzip) {
  5260. cli_.set_compress(true);
  5261. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5262. ASSERT_TRUE(res);
  5263. ASSERT_EQ(StatusCode::OK_200, res->status);
  5264. ASSERT_EQ("content", res->body);
  5265. }
  5266. TEST_F(ServerTest, PutContentReceiver) {
  5267. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5268. ASSERT_TRUE(res);
  5269. ASSERT_EQ(StatusCode::OK_200, res->status);
  5270. ASSERT_EQ("content", res->body);
  5271. }
  5272. TEST_F(ServerTest, PatchContentReceiver) {
  5273. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5274. ASSERT_TRUE(res);
  5275. ASSERT_EQ(StatusCode::OK_200, res->status);
  5276. ASSERT_EQ("content", res->body);
  5277. }
  5278. template <typename ClientType>
  5279. void TestWithHeadersAndContentReceiver(
  5280. ClientType &cli,
  5281. std::function<Result(ClientType &, const std::string &, const Headers &,
  5282. const std::string &, const std::string &,
  5283. ContentReceiver, DownloadProgress)>
  5284. request_func) {
  5285. Headers headers;
  5286. headers.emplace("X-Custom-Header", "test-value");
  5287. std::string received_body;
  5288. auto res = request_func(
  5289. cli, "/content_receiver", headers, "content", "application/json",
  5290. [&](const char *data, size_t data_length) {
  5291. received_body.append(data, data_length);
  5292. return true;
  5293. },
  5294. nullptr);
  5295. ASSERT_TRUE(res);
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("content", received_body);
  5298. }
  5299. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5300. #ifdef CPPHTTPLIB_SSL_ENABLED
  5301. using ClientT = SSLClient;
  5302. #else
  5303. using ClientT = Client;
  5304. #endif
  5305. TestWithHeadersAndContentReceiver<ClientT>(
  5306. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5307. const std::string &body, const std::string &content_type,
  5308. ContentReceiver receiver, DownloadProgress progress) {
  5309. return cli.Post(path, headers, body, content_type, receiver, progress);
  5310. });
  5311. }
  5312. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5313. #ifdef CPPHTTPLIB_SSL_ENABLED
  5314. using ClientT = SSLClient;
  5315. #else
  5316. using ClientT = Client;
  5317. #endif
  5318. TestWithHeadersAndContentReceiver<ClientT>(
  5319. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5320. const std::string &body, const std::string &content_type,
  5321. ContentReceiver receiver, DownloadProgress progress) {
  5322. return cli.Put(path, headers, body, content_type, receiver, progress);
  5323. });
  5324. }
  5325. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5326. #ifdef CPPHTTPLIB_SSL_ENABLED
  5327. using ClientT = SSLClient;
  5328. #else
  5329. using ClientT = Client;
  5330. #endif
  5331. TestWithHeadersAndContentReceiver<ClientT>(
  5332. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5333. const std::string &body, const std::string &content_type,
  5334. ContentReceiver receiver, DownloadProgress progress) {
  5335. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5336. });
  5337. }
  5338. template <typename ClientType>
  5339. void TestWithHeadersAndContentReceiverWithProgress(
  5340. ClientType &cli,
  5341. std::function<Result(ClientType &, const std::string &, const Headers &,
  5342. const std::string &, const std::string &,
  5343. ContentReceiver, DownloadProgress)>
  5344. request_func) {
  5345. Headers headers;
  5346. headers.emplace("X-Test-Header", "progress-test");
  5347. std::string received_body;
  5348. auto progress_called = false;
  5349. auto res = request_func(
  5350. cli, "/content_receiver", headers, "content", "text/plain",
  5351. [&](const char *data, size_t data_length) {
  5352. received_body.append(data, data_length);
  5353. return true;
  5354. },
  5355. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5356. progress_called = true;
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(res);
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. EXPECT_EQ("content", received_body);
  5362. EXPECT_TRUE(progress_called);
  5363. }
  5364. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5365. #ifdef CPPHTTPLIB_SSL_ENABLED
  5366. using ClientT = SSLClient;
  5367. #else
  5368. using ClientT = Client;
  5369. #endif
  5370. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5371. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5372. const std::string &body, const std::string &content_type,
  5373. ContentReceiver receiver, DownloadProgress progress) {
  5374. return cli.Post(path, headers, body, content_type, receiver, progress);
  5375. });
  5376. }
  5377. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5378. #ifdef CPPHTTPLIB_SSL_ENABLED
  5379. using ClientT = SSLClient;
  5380. #else
  5381. using ClientT = Client;
  5382. #endif
  5383. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5384. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5385. const std::string &body, const std::string &content_type,
  5386. ContentReceiver receiver, DownloadProgress progress) {
  5387. return cli.Put(path, headers, body, content_type, receiver, progress);
  5388. });
  5389. }
  5390. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5391. #ifdef CPPHTTPLIB_SSL_ENABLED
  5392. using ClientT = SSLClient;
  5393. #else
  5394. using ClientT = Client;
  5395. #endif
  5396. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5397. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5398. const std::string &body, const std::string &content_type,
  5399. ContentReceiver receiver, DownloadProgress progress) {
  5400. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5401. });
  5402. }
  5403. template <typename ClientType>
  5404. void TestWithHeadersAndContentReceiverError(
  5405. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5406. const Headers &, const std::string &,
  5407. const std::string &, ContentReceiver)>
  5408. request_func) {
  5409. Headers headers;
  5410. headers.emplace("X-Error-Test", "true");
  5411. std::string received_body;
  5412. auto receiver_failed = false;
  5413. auto res =
  5414. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5415. [&](const char *data, size_t data_length) {
  5416. received_body.append(data, data_length);
  5417. receiver_failed = true;
  5418. return false;
  5419. });
  5420. ASSERT_FALSE(res);
  5421. EXPECT_TRUE(receiver_failed);
  5422. }
  5423. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5424. #ifdef CPPHTTPLIB_SSL_ENABLED
  5425. using ClientT = SSLClient;
  5426. #else
  5427. using ClientT = Client;
  5428. #endif
  5429. TestWithHeadersAndContentReceiverError<ClientT>(
  5430. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5431. const std::string &body, const std::string &content_type,
  5432. ContentReceiver receiver) {
  5433. return cli.Post(path, headers, body, content_type, receiver);
  5434. });
  5435. }
  5436. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5437. #ifdef CPPHTTPLIB_SSL_ENABLED
  5438. using ClientT = SSLClient;
  5439. #else
  5440. using ClientT = Client;
  5441. #endif
  5442. TestWithHeadersAndContentReceiverError<ClientT>(
  5443. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5444. const std::string &body, const std::string &content_type,
  5445. ContentReceiver receiver) {
  5446. return cli.Put(path, headers, body, content_type, receiver);
  5447. });
  5448. }
  5449. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5450. #ifdef CPPHTTPLIB_SSL_ENABLED
  5451. using ClientT = SSLClient;
  5452. #else
  5453. using ClientT = Client;
  5454. #endif
  5455. TestWithHeadersAndContentReceiverError<ClientT>(
  5456. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5457. const std::string &body, const std::string &content_type,
  5458. ContentReceiver receiver) {
  5459. return cli.Patch(path, headers, body, content_type, receiver);
  5460. });
  5461. }
  5462. TEST_F(ServerTest, PostQueryStringAndBody) {
  5463. auto res =
  5464. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5465. ASSERT_TRUE(res);
  5466. ASSERT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. TEST_F(ServerTest, HTTP2Magic) {
  5469. Request req;
  5470. req.method = "PRI";
  5471. req.path = "*";
  5472. req.body = "SM";
  5473. auto res = std::make_shared<Response>();
  5474. auto error = Error::Success;
  5475. auto ret = cli_.send(req, *res, error);
  5476. ASSERT_TRUE(ret);
  5477. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5478. }
  5479. TEST_F(ServerTest, KeepAlive) {
  5480. auto res = cli_.Get("/hi");
  5481. ASSERT_TRUE(res);
  5482. EXPECT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5484. EXPECT_EQ("Hello World!", res->body);
  5485. res = cli_.Get("/hi");
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5489. EXPECT_EQ("Hello World!", res->body);
  5490. res = cli_.Get("/hi");
  5491. ASSERT_TRUE(res);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5494. EXPECT_EQ("Hello World!", res->body);
  5495. res = cli_.Get("/not-exist");
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5498. res = cli_.Post("/empty", "", "text/plain");
  5499. ASSERT_TRUE(res);
  5500. EXPECT_EQ(StatusCode::OK_200, res->status);
  5501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5502. EXPECT_EQ("empty", res->body);
  5503. EXPECT_EQ("close", res->get_header_value("Connection"));
  5504. res = cli_.Post(
  5505. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5506. "text/plain");
  5507. ASSERT_TRUE(res);
  5508. EXPECT_EQ(StatusCode::OK_200, res->status);
  5509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5510. EXPECT_EQ("empty", res->body);
  5511. cli_.set_keep_alive(false);
  5512. res = cli_.Get("/last-request");
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_EQ("close", res->get_header_value("Connection"));
  5516. }
  5517. TEST_F(ServerTest, TooManyRedirect) {
  5518. cli_.set_follow_location(true);
  5519. auto res = cli_.Get("/redirect/0");
  5520. ASSERT_TRUE(!res);
  5521. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5522. }
  5523. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5524. Request req;
  5525. req.method = "FOOBAR";
  5526. req.path = "/hi";
  5527. cli_.set_keep_alive(true);
  5528. auto res = cli_.send(req);
  5529. ASSERT_TRUE(res);
  5530. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5531. EXPECT_EQ("close", res->get_header_value("Connection"));
  5532. EXPECT_FALSE(cli_.is_socket_open());
  5533. }
  5534. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5535. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5536. TEST_F(ServerTest, Gzip) {
  5537. Headers headers;
  5538. headers.emplace("Accept-Encoding", "gzip, deflate");
  5539. auto res = cli_.Get("/compress", headers);
  5540. ASSERT_TRUE(res);
  5541. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5543. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5545. "7890123456789012345678901234567890",
  5546. res->body);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. }
  5549. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5550. Headers headers;
  5551. headers.emplace("Accept-Encoding", "gzip, deflate");
  5552. auto res = cli_.Get("/compress-with-charset", headers);
  5553. ASSERT_TRUE(res);
  5554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5555. EXPECT_EQ("application/json; charset=utf-8",
  5556. res->get_header_value("Content-Type"));
  5557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5558. "7890123456789012345678901234567890",
  5559. res->body);
  5560. EXPECT_EQ(StatusCode::OK_200, res->status);
  5561. }
  5562. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5563. Headers headers;
  5564. headers.emplace("Accept-Encoding", "");
  5565. auto res = cli_.Get("/compress", headers);
  5566. ASSERT_TRUE(res);
  5567. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5569. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5571. "7890123456789012345678901234567890",
  5572. res->body);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. }
  5575. TEST_F(ServerTest, GzipWithContentReceiver) {
  5576. Headers headers;
  5577. headers.emplace("Accept-Encoding", "gzip, deflate");
  5578. std::string body;
  5579. auto res = cli_.Get("/compress", headers,
  5580. [&](const char *data, uint64_t data_length) {
  5581. EXPECT_EQ(100U, data_length);
  5582. body.append(data, data_length);
  5583. return true;
  5584. });
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5587. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5588. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5589. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5590. "7890123456789012345678901234567890",
  5591. body);
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. }
  5594. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5595. Headers headers;
  5596. headers.emplace("Accept-Encoding", "gzip, deflate");
  5597. cli_.set_decompress(false);
  5598. auto res = cli_.Get("/compress", headers);
  5599. ASSERT_TRUE(res);
  5600. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(33U, res->body.size());
  5604. EXPECT_EQ(StatusCode::OK_200, res->status);
  5605. }
  5606. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "");
  5609. std::string body;
  5610. auto res = cli_.Get("/compress", headers,
  5611. [&](const char *data, uint64_t data_length) {
  5612. EXPECT_EQ(100U, data_length);
  5613. body.append(data, data_length);
  5614. return true;
  5615. });
  5616. ASSERT_TRUE(res);
  5617. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5618. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5619. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5620. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5621. "7890123456789012345678901234567890",
  5622. body);
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. }
  5625. TEST_F(ServerTest, NoGzip) {
  5626. Headers headers;
  5627. headers.emplace("Accept-Encoding", "gzip, deflate");
  5628. auto res = cli_.Get("/nocompress", headers);
  5629. ASSERT_TRUE(res);
  5630. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5631. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5634. "7890123456789012345678901234567890",
  5635. res->body);
  5636. EXPECT_EQ(StatusCode::OK_200, res->status);
  5637. }
  5638. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5639. Headers headers;
  5640. headers.emplace("Accept-Encoding", "gzip, deflate");
  5641. std::string body;
  5642. auto res = cli_.Get("/nocompress", headers,
  5643. [&](const char *data, uint64_t data_length) {
  5644. EXPECT_EQ(100U, data_length);
  5645. body.append(data, data_length);
  5646. return true;
  5647. });
  5648. ASSERT_TRUE(res);
  5649. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5650. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5651. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5652. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5653. "7890123456789012345678901234567890",
  5654. body);
  5655. EXPECT_EQ(StatusCode::OK_200, res->status);
  5656. }
  5657. TEST_F(ServerTest, MultipartFormDataGzip) {
  5658. UploadFormDataItems items = {
  5659. {"key1", "test", "", ""},
  5660. {"key2", "--abcdefg123", "", ""},
  5661. };
  5662. cli_.set_compress(true);
  5663. auto res = cli_.Post("/compress-multipart", items);
  5664. ASSERT_TRUE(res);
  5665. EXPECT_EQ(StatusCode::OK_200, res->status);
  5666. }
  5667. #endif
  5668. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5669. TEST_F(ServerTest, Brotli) {
  5670. Headers headers;
  5671. headers.emplace("Accept-Encoding", "br");
  5672. auto res = cli_.Get("/compress", headers);
  5673. ASSERT_TRUE(res);
  5674. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5675. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5676. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5677. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5678. "7890123456789012345678901234567890",
  5679. res->body);
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. }
  5682. #endif
  5683. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5684. TEST_F(ServerTest, Zstd) {
  5685. Headers headers;
  5686. headers.emplace("Accept-Encoding", "zstd");
  5687. auto res = cli_.Get("/compress", headers);
  5688. ASSERT_TRUE(res);
  5689. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5690. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5691. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5692. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5693. "7890123456789012345678901234567890",
  5694. res->body);
  5695. EXPECT_EQ(StatusCode::OK_200, res->status);
  5696. }
  5697. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5698. Headers headers;
  5699. headers.emplace("Accept-Encoding", "");
  5700. auto res = cli_.Get("/compress", headers);
  5701. ASSERT_TRUE(res);
  5702. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5704. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5705. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5706. "7890123456789012345678901234567890",
  5707. res->body);
  5708. EXPECT_EQ(StatusCode::OK_200, res->status);
  5709. }
  5710. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5711. Headers headers;
  5712. headers.emplace("Accept-Encoding", "zstd");
  5713. std::string body;
  5714. auto res = cli_.Get("/compress", headers,
  5715. [&](const char *data, uint64_t data_length) {
  5716. EXPECT_EQ(100U, data_length);
  5717. body.append(data, data_length);
  5718. return true;
  5719. });
  5720. ASSERT_TRUE(res);
  5721. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5722. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5723. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5724. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5725. "7890123456789012345678901234567890",
  5726. body);
  5727. EXPECT_EQ(StatusCode::OK_200, res->status);
  5728. }
  5729. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5730. Headers headers;
  5731. headers.emplace("Accept-Encoding", "zstd");
  5732. cli_.set_decompress(false);
  5733. auto res = cli_.Get("/compress", headers);
  5734. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5735. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5736. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5737. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5738. ASSERT_TRUE(res);
  5739. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5741. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. ASSERT_EQ(26U, res->body.size());
  5744. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5745. 0);
  5746. }
  5747. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5748. Headers headers;
  5749. headers.emplace("Accept-Encoding", "");
  5750. std::string body;
  5751. auto res = cli_.Get("/compress", headers,
  5752. [&](const char *data, uint64_t data_length) {
  5753. EXPECT_EQ(100U, data_length);
  5754. body.append(data, data_length);
  5755. return true;
  5756. });
  5757. ASSERT_TRUE(res);
  5758. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5760. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5761. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5762. "7890123456789012345678901234567890",
  5763. body);
  5764. EXPECT_EQ(StatusCode::OK_200, res->status);
  5765. }
  5766. TEST_F(ServerTest, NoZstd) {
  5767. Headers headers;
  5768. headers.emplace("Accept-Encoding", "zstd");
  5769. auto res = cli_.Get("/nocompress", headers);
  5770. ASSERT_TRUE(res);
  5771. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5772. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5773. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5774. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5775. "7890123456789012345678901234567890",
  5776. res->body);
  5777. EXPECT_EQ(StatusCode::OK_200, res->status);
  5778. }
  5779. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5780. Headers headers;
  5781. headers.emplace("Accept-Encoding", "zstd");
  5782. std::string body;
  5783. auto res = cli_.Get("/nocompress", headers,
  5784. [&](const char *data, uint64_t data_length) {
  5785. EXPECT_EQ(100U, data_length);
  5786. body.append(data, data_length);
  5787. return true;
  5788. });
  5789. ASSERT_TRUE(res);
  5790. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5791. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5792. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5793. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5794. "7890123456789012345678901234567890",
  5795. body);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. }
  5798. // TODO: How to enable zstd ??
  5799. TEST_F(ServerTest, MultipartFormDataZstd) {
  5800. UploadFormDataItems items = {
  5801. {"key1", "test", "", ""},
  5802. {"key2", "--abcdefg123", "", ""},
  5803. };
  5804. Headers headers;
  5805. headers.emplace("Accept-Encoding", "zstd");
  5806. cli_.set_compress(true);
  5807. auto res = cli_.Post("/compress-multipart", headers, items);
  5808. ASSERT_TRUE(res);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. }
  5811. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5812. Headers headers;
  5813. headers.emplace("Accept-Encoding", "zstd");
  5814. cli_.set_compress(true);
  5815. auto res = cli_.Put(
  5816. "/put", headers, 3,
  5817. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5818. sink.os << "PUT";
  5819. return true;
  5820. },
  5821. "text/plain");
  5822. ASSERT_TRUE(res);
  5823. EXPECT_EQ(StatusCode::OK_200, res->status);
  5824. EXPECT_EQ("PUT", res->body);
  5825. }
  5826. // Pre-compression logging tests
  5827. TEST_F(ServerTest, PreCompressionLogging) {
  5828. // Test data for compression (matches the actual /compress endpoint content)
  5829. const std::string test_content =
  5830. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5831. "3456789012345678901234567890";
  5832. // Variables to capture logging data
  5833. std::string pre_compression_body;
  5834. std::string pre_compression_content_type;
  5835. std::string pre_compression_content_encoding;
  5836. std::string post_compression_body;
  5837. std::string post_compression_content_type;
  5838. std::string post_compression_content_encoding;
  5839. // Set up pre-compression logger
  5840. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5841. const Response &res) {
  5842. pre_compression_body = res.body;
  5843. pre_compression_content_type = res.get_header_value("Content-Type");
  5844. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5845. });
  5846. // Set up post-compression logger
  5847. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5848. post_compression_body = res.body;
  5849. post_compression_content_type = res.get_header_value("Content-Type");
  5850. post_compression_content_encoding =
  5851. res.get_header_value("Content-Encoding");
  5852. });
  5853. // Test with gzip compression
  5854. Headers headers;
  5855. headers.emplace("Accept-Encoding", "gzip");
  5856. auto res = cli_.Get("/compress", headers);
  5857. // Verify response was compressed
  5858. ASSERT_TRUE(res);
  5859. EXPECT_EQ(StatusCode::OK_200, res->status);
  5860. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5861. // Verify pre-compression logger captured uncompressed content
  5862. EXPECT_EQ(test_content, pre_compression_body);
  5863. EXPECT_EQ("text/plain", pre_compression_content_type);
  5864. EXPECT_TRUE(pre_compression_content_encoding
  5865. .empty()); // No encoding header before compression
  5866. // Verify post-compression logger captured compressed content
  5867. EXPECT_NE(test_content,
  5868. post_compression_body); // Should be different after compression
  5869. EXPECT_EQ("text/plain", post_compression_content_type);
  5870. EXPECT_EQ("gzip", post_compression_content_encoding);
  5871. // Verify compressed content is smaller
  5872. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5873. }
  5874. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5875. const std::string test_content =
  5876. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5877. "3456789012345678901234567890";
  5878. std::string pre_compression_body;
  5879. std::string post_compression_body;
  5880. svr_.set_pre_compression_logger(
  5881. [&](const Request & /*req*/, const Response &res) {
  5882. pre_compression_body = res.body;
  5883. });
  5884. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5885. post_compression_body = res.body;
  5886. });
  5887. Headers headers;
  5888. headers.emplace("Accept-Encoding", "br");
  5889. auto res = cli_.Get("/compress", headers);
  5890. ASSERT_TRUE(res);
  5891. EXPECT_EQ(StatusCode::OK_200, res->status);
  5892. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5893. // Verify pre-compression content is uncompressed
  5894. EXPECT_EQ(test_content, pre_compression_body);
  5895. // Verify post-compression content is compressed
  5896. EXPECT_NE(test_content, post_compression_body);
  5897. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5898. }
  5899. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5900. const std::string test_content =
  5901. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5902. "3456789012345678901234567890";
  5903. std::string pre_compression_body;
  5904. std::string post_compression_body;
  5905. svr_.set_pre_compression_logger(
  5906. [&](const Request & /*req*/, const Response &res) {
  5907. pre_compression_body = res.body;
  5908. });
  5909. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5910. post_compression_body = res.body;
  5911. });
  5912. // Request without compression (use /nocompress endpoint)
  5913. Headers headers;
  5914. auto res = cli_.Get("/nocompress", headers);
  5915. ASSERT_TRUE(res);
  5916. EXPECT_EQ(StatusCode::OK_200, res->status);
  5917. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5918. // Pre-compression logger should not be called when no compression is applied
  5919. EXPECT_TRUE(
  5920. pre_compression_body.empty()); // Pre-compression logger not called
  5921. EXPECT_EQ(
  5922. test_content,
  5923. post_compression_body); // Post-compression logger captures final content
  5924. }
  5925. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5926. const std::string test_content =
  5927. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5928. "3456789012345678901234567890";
  5929. std::string pre_compression_body;
  5930. bool pre_logger_called = false;
  5931. // Set only pre-compression logger
  5932. svr_.set_pre_compression_logger(
  5933. [&](const Request & /*req*/, const Response &res) {
  5934. pre_compression_body = res.body;
  5935. pre_logger_called = true;
  5936. });
  5937. Headers headers;
  5938. headers.emplace("Accept-Encoding", "gzip");
  5939. auto res = cli_.Get("/compress", headers);
  5940. ASSERT_TRUE(res);
  5941. EXPECT_EQ(StatusCode::OK_200, res->status);
  5942. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5943. // Verify pre-compression logger was called
  5944. EXPECT_TRUE(pre_logger_called);
  5945. EXPECT_EQ(test_content, pre_compression_body);
  5946. }
  5947. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5948. {
  5949. // Test with Expect: 100-continue header - success case
  5950. // Server returns 100 Continue, client sends body, server returns 200 OK
  5951. Request req;
  5952. req.method = "POST";
  5953. req.path = "/post-large";
  5954. req.set_header("Expect", "100-continue");
  5955. req.body = LARGE_DATA;
  5956. Response res;
  5957. auto error = Error::Success;
  5958. cli_.set_keep_alive(true);
  5959. auto ret = cli_.send(req, res, error);
  5960. EXPECT_TRUE(ret);
  5961. EXPECT_EQ(StatusCode::OK_200, res.status);
  5962. EXPECT_EQ(LARGE_DATA, res.body);
  5963. }
  5964. {
  5965. // Test with Expect: 100-continue header - error case
  5966. // Client should not send the body when server returns an error
  5967. Request req;
  5968. req.method = "POST";
  5969. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5970. req.set_header("Expect", "100-continue");
  5971. req.body = LARGE_DATA;
  5972. Response res;
  5973. auto error = Error::Success;
  5974. auto start = std::chrono::high_resolution_clock::now();
  5975. cli_.set_keep_alive(true);
  5976. auto ret = cli_.send(req, res, error);
  5977. auto end = std::chrono::high_resolution_clock::now();
  5978. auto elapsed =
  5979. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5980. .count();
  5981. // With Expect: 100-continue, request completes successfully but with error
  5982. EXPECT_TRUE(ret);
  5983. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5984. EXPECT_EQ("close", res.get_header_value("Connection"));
  5985. EXPECT_FALSE(cli_.is_socket_open());
  5986. EXPECT_LE(elapsed, 2000);
  5987. }
  5988. {
  5989. // Send an extra GET request to ensure error recovery without hanging
  5990. Request req;
  5991. req.method = "GET";
  5992. req.path = "/hi";
  5993. auto start = std::chrono::high_resolution_clock::now();
  5994. auto res = cli_.send(req);
  5995. auto end = std::chrono::high_resolution_clock::now();
  5996. auto elapsed =
  5997. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5998. .count();
  5999. ASSERT_TRUE(res);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. EXPECT_EQ("Hello World!", res->body);
  6002. EXPECT_LE(elapsed, 500);
  6003. }
  6004. }
  6005. TEST(ZstdDecompressor, ChunkedDecompression) {
  6006. std::string data;
  6007. for (size_t i = 0; i < 32 * 1024; ++i) {
  6008. data.push_back(static_cast<char>('a' + i % 26));
  6009. }
  6010. std::string compressed_data;
  6011. {
  6012. httplib::detail::zstd_compressor compressor;
  6013. bool result = compressor.compress(
  6014. data.data(), data.size(),
  6015. /*last=*/true,
  6016. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6017. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6018. compressed_data_size);
  6019. return true;
  6020. });
  6021. ASSERT_TRUE(result);
  6022. }
  6023. std::string decompressed_data;
  6024. {
  6025. httplib::detail::zstd_decompressor decompressor;
  6026. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6027. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6028. size_t chunk_size = 130;
  6029. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6030. chunk_begin += chunk_size) {
  6031. size_t current_chunk_size =
  6032. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6033. bool result = decompressor.decompress(
  6034. compressed_data.data() + chunk_begin, current_chunk_size,
  6035. [&](const char *decompressed_data_chunk,
  6036. size_t decompressed_data_chunk_size) {
  6037. decompressed_data.insert(decompressed_data.size(),
  6038. decompressed_data_chunk,
  6039. decompressed_data_chunk_size);
  6040. return true;
  6041. });
  6042. ASSERT_TRUE(result);
  6043. }
  6044. }
  6045. ASSERT_EQ(data, decompressed_data);
  6046. }
  6047. TEST(ZstdDecompressor, Decompress) {
  6048. std::string original_text = "Compressed with ZSTD";
  6049. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6050. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6051. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6052. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6053. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6054. std::string decompressed_data;
  6055. {
  6056. httplib::detail::zstd_decompressor decompressor;
  6057. bool result = decompressor.decompress(
  6058. compressed_data.data(), compressed_data.size(),
  6059. [&](const char *decompressed_data_chunk,
  6060. size_t decompressed_data_chunk_size) {
  6061. decompressed_data.insert(decompressed_data.size(),
  6062. decompressed_data_chunk,
  6063. decompressed_data_chunk_size);
  6064. return true;
  6065. });
  6066. ASSERT_TRUE(result);
  6067. }
  6068. ASSERT_EQ(original_text, decompressed_data);
  6069. }
  6070. #endif
  6071. // Sends a raw request to a server listening at HOST:PORT.
  6072. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6073. std::string *resp = nullptr) {
  6074. auto error = Error::Success;
  6075. auto client_sock = detail::create_client_socket(
  6076. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6077. /*connection_timeout_sec=*/5, 0,
  6078. /*read_timeout_sec=*/5, 0,
  6079. /*write_timeout_sec=*/5, 0, std::string(), error);
  6080. if (client_sock == INVALID_SOCKET) { return false; }
  6081. auto ret = detail::process_client_socket(
  6082. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6083. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6084. if (req.size() !=
  6085. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6086. return false;
  6087. }
  6088. char buf[512];
  6089. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6090. while (line_reader.getline()) {
  6091. if (resp) { *resp += line_reader.ptr(); }
  6092. }
  6093. return true;
  6094. });
  6095. detail::close_socket(client_sock);
  6096. return ret;
  6097. }
  6098. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6099. Server svr;
  6100. std::string header_value;
  6101. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6102. header_value = req.get_header_value("foo");
  6103. res.set_content("ok", "text/plain");
  6104. });
  6105. thread t = thread([&] { svr.listen(HOST, PORT); });
  6106. auto se = detail::scope_exit([&] {
  6107. svr.stop();
  6108. t.join();
  6109. ASSERT_FALSE(svr.is_running());
  6110. });
  6111. svr.wait_until_ready();
  6112. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6113. // like characters are not treated the same - use vertical tab and escape.
  6114. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6115. "foo: \t \v bar \x1B\t \r\n"
  6116. "Connection: close\r\n"
  6117. "\r\n";
  6118. std::string res;
  6119. ASSERT_TRUE(send_request(5, req, &res));
  6120. EXPECT_EQ(header_value, "");
  6121. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6122. }
  6123. // Sends a raw request and verifies that there isn't a crash or exception.
  6124. static void test_raw_request(const std::string &req,
  6125. std::string *out = nullptr) {
  6126. Server svr;
  6127. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6128. res.set_content("ok", "text/plain");
  6129. });
  6130. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6131. res.set_content("ok", "text/plain");
  6132. });
  6133. svr.Get("/header_field_value_check",
  6134. [&](const Request & /*req*/, Response &res) {
  6135. res.set_content("ok", "text/plain");
  6136. });
  6137. // Server read timeout must be longer than the client read timeout for the
  6138. // bug to reproduce, probably to force the server to process a request
  6139. // without a trailing blank line.
  6140. const time_t client_read_timeout_sec = 1;
  6141. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6142. bool listen_thread_ok = false;
  6143. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6144. auto se = detail::scope_exit([&] {
  6145. svr.stop();
  6146. t.join();
  6147. ASSERT_FALSE(svr.is_running());
  6148. EXPECT_TRUE(listen_thread_ok);
  6149. });
  6150. svr.wait_until_ready();
  6151. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6152. }
  6153. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6154. // A certain header line causes an exception if the header property is parsed
  6155. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6156. test_raw_request(
  6157. "GET /hi HTTP/1.1\r\n"
  6158. " : "
  6159. " "
  6160. " ");
  6161. }
  6162. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6163. // A certain header line causes an exception if the header property *name* is
  6164. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6165. // greedy matcher and requires backtracking when there are a lot of ":"
  6166. // characters.
  6167. // This occurs with libc++ but not libstdc++.
  6168. test_raw_request(
  6169. "GET /hi HTTP/1.1\r\n"
  6170. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6171. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6172. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6173. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6174. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6175. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6176. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6177. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6178. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6179. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6180. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6181. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6182. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6183. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6184. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6185. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6186. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6187. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6188. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6189. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6190. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6191. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6192. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6193. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6194. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6195. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6196. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6197. "&&&%%%");
  6198. }
  6199. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6200. // Make sure this doesn't crash the server.
  6201. // In a previous version of the header line regex, the "\r" rendered the line
  6202. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6203. // a new position where the leading white space ended and the field value
  6204. // began.
  6205. // The crash occurs with libc++ but not libstdc++.
  6206. test_raw_request("GET /hi HTTP/1.1\r\n"
  6207. "a:" +
  6208. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6209. "\r\n"
  6210. "\r\n");
  6211. }
  6212. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6213. std::string out;
  6214. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6215. "Content-Type: text/plain\r\n"
  6216. "Transfer-Encoding: chunked\r\n"
  6217. "\r\n"
  6218. "nothex\r\n",
  6219. &out);
  6220. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6221. }
  6222. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6223. std::string out;
  6224. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6225. "Content-Type: text/plain\r\n"
  6226. "Transfer-Encoding: chunked\r\n"
  6227. "\r\n"
  6228. "3\r\n"
  6229. "xyz\r\n"
  6230. "NaN\r\n",
  6231. &out);
  6232. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6233. }
  6234. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6235. std::string out;
  6236. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6237. "Content-Type: text/plain\r\n"
  6238. "Transfer-Encoding: chunked\r\n"
  6239. "\r\n"
  6240. // Length is too large for 64 bits.
  6241. "1ffffffffffffffff\r\n"
  6242. "xyz\r\n",
  6243. &out);
  6244. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6245. }
  6246. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6247. test_raw_request("GET /hi HTTP/1.1\r\n"
  6248. "Content-Type: text/plain\r\n\r");
  6249. }
  6250. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6251. std::string out;
  6252. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6253. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6254. }
  6255. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6256. Server svr;
  6257. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6258. EXPECT_TRUE(!req.remote_addr.empty());
  6259. });
  6260. thread t = thread([&] { svr.listen(HOST, PORT); });
  6261. auto se = detail::scope_exit([&] {
  6262. svr.stop();
  6263. t.join();
  6264. ASSERT_FALSE(svr.is_running());
  6265. });
  6266. svr.wait_until_ready();
  6267. // Send an invalid request line to trigger Bad Request
  6268. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6269. std::string out;
  6270. ASSERT_TRUE(send_request(5, bad_req, &out));
  6271. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6272. }
  6273. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6274. std::string out;
  6275. std::string request(
  6276. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6277. test_raw_request(request, &out);
  6278. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6279. }
  6280. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6281. std::string out;
  6282. std::string request(
  6283. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6284. test_raw_request(request, &out);
  6285. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6286. }
  6287. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6288. std::string out;
  6289. std::string request(
  6290. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6291. test_raw_request(request, &out);
  6292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6293. }
  6294. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6295. std::string out;
  6296. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6297. "Test: \r\n\r\n",
  6298. &out);
  6299. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6300. }
  6301. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6302. Server svr;
  6303. std::string x_custom;
  6304. std::string cookie;
  6305. std::string xff;
  6306. std::string x_unicode;
  6307. std::string x_iis;
  6308. svr.Get("/check", [&](const Request &req, Response &res) {
  6309. x_custom = req.get_header_value("X-Custom");
  6310. cookie = req.get_header_value("Cookie");
  6311. xff = req.get_header_value("X-Forwarded-For");
  6312. x_unicode = req.get_header_value("X-Unicode");
  6313. x_iis = req.get_header_value("X-IIS");
  6314. res.set_content("ok", "text/plain");
  6315. });
  6316. thread t = thread([&] { svr.listen(HOST, PORT); });
  6317. auto se = detail::scope_exit([&] {
  6318. svr.stop();
  6319. t.join();
  6320. ASSERT_FALSE(svr.is_running());
  6321. });
  6322. svr.wait_until_ready();
  6323. const std::string req = "GET /check HTTP/1.1\r\n"
  6324. "Host: localhost\r\n"
  6325. "X-Custom: a%0D%0AInjected: b\r\n"
  6326. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6327. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6328. "X-Unicode: %E3%81%82\r\n"
  6329. "X-IIS: %u00E9\r\n"
  6330. "Connection: close\r\n"
  6331. "\r\n";
  6332. std::string res;
  6333. ASSERT_TRUE(send_request(5, req, &res));
  6334. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6335. // Every value must be returned verbatim (wire form), with no decoding.
  6336. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6337. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6338. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6339. EXPECT_EQ("%E3%81%82", x_unicode);
  6340. EXPECT_EQ("%u00E9", x_iis);
  6341. }
  6342. // Applications that previously relied on automatic percent-decoding can
  6343. // reproduce the old behavior by explicitly calling decode_path_component()
  6344. // or, for RFC 3986 conformance, decode_uri_component().
  6345. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6346. Server svr;
  6347. std::string decoded;
  6348. svr.Get("/check", [&](const Request &req, Response &res) {
  6349. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6350. res.set_content("ok", "text/plain");
  6351. });
  6352. thread t = thread([&] { svr.listen(HOST, PORT); });
  6353. auto se = detail::scope_exit([&] {
  6354. svr.stop();
  6355. t.join();
  6356. ASSERT_FALSE(svr.is_running());
  6357. });
  6358. svr.wait_until_ready();
  6359. const std::string req = "GET /check HTTP/1.1\r\n"
  6360. "Host: localhost\r\n"
  6361. "X-Custom: hello%20world\r\n"
  6362. "Connection: close\r\n"
  6363. "\r\n";
  6364. std::string res;
  6365. ASSERT_TRUE(send_request(5, req, &res));
  6366. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6367. EXPECT_EQ("hello world", decoded);
  6368. }
  6369. // Regression test for #2033. Browsers send Referer values that include
  6370. // percent-encoded characters such as %0A inside the URL. Decoding the
  6371. // header value would either trip the post-decode CR/LF/NUL guard (the
  6372. // original bug, returning 400) or, after that guard was relaxed, silently
  6373. // store a literal LF — both unacceptable. The wire form must round-trip.
  6374. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6375. Server svr;
  6376. std::string referer;
  6377. svr.Get("/check", [&](const Request &req, Response &res) {
  6378. referer = req.get_header_value("Referer");
  6379. res.set_content("ok", "text/plain");
  6380. });
  6381. thread t = thread([&] { svr.listen(HOST, PORT); });
  6382. auto se = detail::scope_exit([&] {
  6383. svr.stop();
  6384. t.join();
  6385. ASSERT_FALSE(svr.is_running());
  6386. });
  6387. svr.wait_until_ready();
  6388. const std::string req = "GET /check HTTP/1.1\r\n"
  6389. "Host: localhost\r\n"
  6390. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6391. "Connection: close\r\n"
  6392. "\r\n";
  6393. std::string res;
  6394. ASSERT_TRUE(send_request(5, req, &res));
  6395. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6396. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6397. }
  6398. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6399. Server svr;
  6400. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6401. res.set_header("Cache-Control", "no-cache");
  6402. res.set_chunked_content_provider(
  6403. "text/event-stream", [](size_t offset, DataSink &sink) {
  6404. std::string s = "data:";
  6405. s += std::to_string(offset);
  6406. s += "\n\n";
  6407. auto ret = sink.write(s.data(), s.size());
  6408. EXPECT_TRUE(ret);
  6409. std::this_thread::sleep_for(std::chrono::seconds(1));
  6410. return true;
  6411. });
  6412. });
  6413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6414. svr.wait_until_ready();
  6415. Client client(HOST, PORT);
  6416. const Headers headers = {{"Accept", "text/event-stream"}};
  6417. auto get_thread = std::thread([&client, &headers]() {
  6418. auto res = client.Get(
  6419. "/events", headers,
  6420. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6421. });
  6422. auto se = detail::scope_exit([&] {
  6423. svr.stop();
  6424. get_thread.join();
  6425. listen_thread.join();
  6426. ASSERT_FALSE(svr.is_running());
  6427. });
  6428. // Give GET time to get a few messages.
  6429. std::this_thread::sleep_for(std::chrono::seconds(2));
  6430. }
  6431. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6432. httplib::Server svr;
  6433. svr.Post("/hi",
  6434. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6435. res.status = StatusCode::OK_200;
  6436. });
  6437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6438. svr.wait_until_ready();
  6439. Client cli(HOST, PORT);
  6440. auto res = cli.Post("/hi", "data", "text/plain");
  6441. ASSERT_TRUE(res);
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. svr.stop();
  6444. thread.join();
  6445. ASSERT_FALSE(svr.is_running());
  6446. res = cli.Post("/hi", "data", "text/plain");
  6447. ASSERT_FALSE(res);
  6448. }
  6449. TEST(ServerStopTest, ListenFailure) {
  6450. Server svr;
  6451. auto t = thread([&]() {
  6452. auto ret = svr.listen("????", PORT);
  6453. EXPECT_FALSE(ret);
  6454. });
  6455. svr.wait_until_ready();
  6456. svr.stop();
  6457. t.join();
  6458. }
  6459. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6460. TEST(ServerStopTest, Decommision) {
  6461. Server svr;
  6462. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6463. for (int i = 0; i < 4; i++) {
  6464. auto is_even = !(i % 2);
  6465. std::thread t{[&] {
  6466. try {
  6467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6468. if (is_even) {
  6469. throw std::runtime_error("Some thing that happens to go wrong.");
  6470. }
  6471. svr.listen(HOST, PORT);
  6472. } catch (...) { svr.decommission(); }
  6473. }};
  6474. svr.wait_until_ready();
  6475. // Server is up
  6476. {
  6477. Client cli(HOST, PORT);
  6478. auto res = cli.Get("/hi");
  6479. if (is_even) {
  6480. EXPECT_FALSE(res);
  6481. } else {
  6482. EXPECT_TRUE(res);
  6483. EXPECT_EQ("hi...", res->body);
  6484. }
  6485. }
  6486. svr.stop();
  6487. t.join();
  6488. // Server is down...
  6489. {
  6490. Client cli(HOST, PORT);
  6491. auto res = cli.Get("/hi");
  6492. EXPECT_FALSE(res);
  6493. }
  6494. }
  6495. }
  6496. #endif
  6497. // Helper function for string body upload progress tests
  6498. template <typename SetupHandler, typename ClientCall>
  6499. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6500. ClientCall &&client_call,
  6501. const string &body) {
  6502. Server svr;
  6503. setup_handler(svr);
  6504. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6505. auto se = detail::scope_exit([&] {
  6506. svr.stop();
  6507. t.join();
  6508. });
  6509. svr.wait_until_ready();
  6510. Client cli(HOST, PORT);
  6511. vector<uint64_t> progress_values;
  6512. bool progress_called = false;
  6513. auto res =
  6514. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6515. progress_values.push_back(current);
  6516. progress_called = true;
  6517. return true;
  6518. });
  6519. ASSERT_TRUE(res);
  6520. EXPECT_EQ(200, res->status);
  6521. EXPECT_TRUE(progress_called);
  6522. }
  6523. TEST(UploadProgressTest, PostStringBodyBasic) {
  6524. TestStringBodyUploadProgress(
  6525. [](Server &svr) {
  6526. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6527. res.set_content("received", "text/plain");
  6528. });
  6529. },
  6530. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6531. return cli.Post("/test", body, "text/plain", progress_callback);
  6532. },
  6533. "test data for upload progress");
  6534. }
  6535. TEST(UploadProgressTest, PutStringBodyBasic) {
  6536. TestStringBodyUploadProgress(
  6537. [](Server &svr) {
  6538. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6539. res.set_content("put received", "text/plain");
  6540. });
  6541. },
  6542. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6543. return cli.Put("/test", body, "text/plain", progress_callback);
  6544. },
  6545. "put test data for upload progress");
  6546. }
  6547. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6548. TestStringBodyUploadProgress(
  6549. [](Server &svr) {
  6550. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6551. res.set_content("patch received", "text/plain");
  6552. });
  6553. },
  6554. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6555. return cli.Patch("/test", body, "text/plain", progress_callback);
  6556. },
  6557. "patch test data for upload progress");
  6558. }
  6559. // Helper function for content provider upload progress tests
  6560. template <typename SetupHandler, typename ClientCall>
  6561. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6562. ClientCall &&client_call) {
  6563. Server svr;
  6564. setup_handler(svr);
  6565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6566. auto se = detail::scope_exit([&] {
  6567. svr.stop();
  6568. t.join();
  6569. });
  6570. svr.wait_until_ready();
  6571. Client cli(HOST, PORT);
  6572. vector<uint64_t> progress_values;
  6573. auto res =
  6574. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6575. progress_values.push_back(current);
  6576. return true;
  6577. });
  6578. ASSERT_TRUE(res);
  6579. EXPECT_EQ(200, res->status);
  6580. EXPECT_FALSE(progress_values.empty());
  6581. }
  6582. TEST(UploadProgressTest, PostContentProviderProgress) {
  6583. TestContentProviderUploadProgress(
  6584. [](Server &svr) {
  6585. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6586. res.set_content("provider received", "text/plain");
  6587. });
  6588. },
  6589. [](Client &cli, UploadProgress progress_callback) {
  6590. return cli.Post(
  6591. "/test", 10,
  6592. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6593. sink.os << "test data";
  6594. return true;
  6595. },
  6596. "text/plain", progress_callback);
  6597. });
  6598. }
  6599. // Helper function for multipart upload progress tests
  6600. template <typename SetupHandler, typename ClientCall>
  6601. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6602. ClientCall &&client_call,
  6603. const string &endpoint) {
  6604. Server svr;
  6605. setup_handler(svr);
  6606. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6607. auto se = detail::scope_exit([&] {
  6608. svr.stop();
  6609. t.join();
  6610. });
  6611. svr.wait_until_ready();
  6612. Client cli(HOST, PORT);
  6613. vector<uint64_t> progress_values;
  6614. UploadFormDataItems items = {
  6615. {"field1", "value1", "", ""},
  6616. {"field2", "longer value for progress tracking test", "", ""},
  6617. {"file1", "file content data for upload progress", "test.txt",
  6618. "text/plain"}};
  6619. auto res = client_call(cli, endpoint, items,
  6620. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6621. progress_values.push_back(current);
  6622. return true;
  6623. });
  6624. ASSERT_TRUE(res);
  6625. EXPECT_EQ(200, res->status);
  6626. EXPECT_FALSE(progress_values.empty());
  6627. }
  6628. TEST(UploadProgressTest, PostMultipartProgress) {
  6629. TestMultipartUploadProgress(
  6630. [](Server &svr) {
  6631. svr.Post("/multipart", [](const Request &req, Response &res) {
  6632. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6633. res.set_content("multipart received", "text/plain");
  6634. });
  6635. },
  6636. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6637. UploadProgress progress_callback) {
  6638. return cli.Post(endpoint, items, progress_callback);
  6639. },
  6640. "/multipart");
  6641. }
  6642. // Helper function for basic download progress tests
  6643. template <typename SetupHandler, typename ClientCall>
  6644. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6645. ClientCall &&client_call, const string &endpoint,
  6646. size_t expected_content_size) {
  6647. Server svr;
  6648. setup_handler(svr);
  6649. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6650. auto se = detail::scope_exit([&] {
  6651. svr.stop();
  6652. t.join();
  6653. });
  6654. svr.wait_until_ready();
  6655. Client cli(HOST, PORT);
  6656. vector<uint64_t> progress_values;
  6657. auto res = client_call(cli, endpoint,
  6658. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6659. progress_values.push_back(current);
  6660. return true;
  6661. });
  6662. ASSERT_TRUE(res);
  6663. EXPECT_EQ(200, res->status);
  6664. EXPECT_FALSE(progress_values.empty());
  6665. EXPECT_EQ(expected_content_size, res->body.size());
  6666. }
  6667. TEST(DownloadProgressTest, GetBasic) {
  6668. TestBasicDownloadProgress(
  6669. [](Server &svr) {
  6670. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6671. string content(1000, 'D');
  6672. res.set_content(content, "text/plain");
  6673. });
  6674. },
  6675. [](Client &cli, const string &endpoint,
  6676. DownloadProgress progress_callback) {
  6677. return cli.Get(endpoint, progress_callback);
  6678. },
  6679. "/download", 1000u);
  6680. }
  6681. // Helper function for content receiver download progress tests
  6682. template <typename SetupHandler, typename ClientCall>
  6683. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6684. ClientCall &&client_call,
  6685. const string &endpoint,
  6686. size_t expected_content_size) {
  6687. Server svr;
  6688. setup_handler(svr);
  6689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6690. auto se = detail::scope_exit([&] {
  6691. svr.stop();
  6692. t.join();
  6693. });
  6694. svr.wait_until_ready();
  6695. Client cli(HOST, PORT);
  6696. vector<uint64_t> progress_values;
  6697. string received_body;
  6698. auto res = client_call(
  6699. cli, endpoint,
  6700. [&](const char *data, size_t data_length) -> bool {
  6701. received_body.append(data, data_length);
  6702. return true;
  6703. },
  6704. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6705. progress_values.push_back(current);
  6706. return true;
  6707. });
  6708. ASSERT_TRUE(res);
  6709. EXPECT_EQ(200, res->status);
  6710. EXPECT_FALSE(progress_values.empty());
  6711. EXPECT_EQ(expected_content_size, received_body.size());
  6712. EXPECT_TRUE(res->body.empty());
  6713. }
  6714. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6715. TestContentReceiverDownloadProgress(
  6716. [](Server &svr) {
  6717. svr.Get("/download-receiver",
  6718. [](const Request & /*req*/, Response &res) {
  6719. string content(2000, 'R');
  6720. res.set_content(content, "text/plain");
  6721. });
  6722. },
  6723. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6724. DownloadProgress progress_callback) {
  6725. return cli.Get(endpoint, content_receiver, progress_callback);
  6726. },
  6727. "/download-receiver", 2000u);
  6728. }
  6729. TEST(StreamingTest, NoContentLengthStreaming) {
  6730. Server svr;
  6731. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6732. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6733. if (offset < 6) {
  6734. sink.os << (offset < 3 ? "a" : "b");
  6735. } else {
  6736. sink.done();
  6737. }
  6738. return true;
  6739. });
  6740. });
  6741. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6742. auto listen_se = detail::scope_exit([&] {
  6743. svr.stop();
  6744. listen_thread.join();
  6745. ASSERT_FALSE(svr.is_running());
  6746. });
  6747. svr.wait_until_ready();
  6748. Client client(HOST, PORT);
  6749. auto get_thread = std::thread([&client]() {
  6750. std::string s;
  6751. auto res =
  6752. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6753. s += std::string(data, len);
  6754. return true;
  6755. });
  6756. ASSERT_TRUE(res);
  6757. EXPECT_EQ(StatusCode::OK_200, res->status);
  6758. EXPECT_EQ("aaabbb", s);
  6759. });
  6760. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6761. // Give GET time to get a few messages.
  6762. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6763. }
  6764. TEST(MountTest, Unmount) {
  6765. Server svr;
  6766. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6767. auto se = detail::scope_exit([&] {
  6768. svr.stop();
  6769. listen_thread.join();
  6770. ASSERT_FALSE(svr.is_running());
  6771. });
  6772. svr.wait_until_ready();
  6773. Client cli("localhost", PORT);
  6774. svr.set_mount_point("/mount2", "./www2");
  6775. auto res = cli.Get("/");
  6776. ASSERT_TRUE(res);
  6777. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6778. res = cli.Get("/mount2/dir/test.html");
  6779. ASSERT_TRUE(res);
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. svr.set_mount_point("/", "./www");
  6782. res = cli.Get("/dir/");
  6783. ASSERT_TRUE(res);
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. svr.remove_mount_point("/");
  6786. res = cli.Get("/dir/");
  6787. ASSERT_TRUE(res);
  6788. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6789. svr.remove_mount_point("/mount2");
  6790. res = cli.Get("/mount2/dir/test.html");
  6791. ASSERT_TRUE(res);
  6792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6793. }
  6794. TEST(MountTest, Redicect) {
  6795. Server svr;
  6796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6797. auto se = detail::scope_exit([&] {
  6798. svr.stop();
  6799. listen_thread.join();
  6800. ASSERT_FALSE(svr.is_running());
  6801. });
  6802. svr.set_mount_point("/", "./www");
  6803. svr.wait_until_ready();
  6804. Client cli("localhost", PORT);
  6805. auto res = cli.Get("/dir/");
  6806. ASSERT_TRUE(res);
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. res = cli.Get("/dir");
  6809. ASSERT_TRUE(res);
  6810. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6811. res = cli.Get("/file");
  6812. ASSERT_TRUE(res);
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. res = cli.Get("/file/");
  6815. ASSERT_TRUE(res);
  6816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6817. cli.set_follow_location(true);
  6818. res = cli.Get("/dir");
  6819. ASSERT_TRUE(res);
  6820. EXPECT_EQ(StatusCode::OK_200, res->status);
  6821. }
  6822. TEST(MountTest, MultibytesPathName) {
  6823. Server svr;
  6824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. listen_thread.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. });
  6830. svr.set_mount_point("/", "./www");
  6831. svr.wait_until_ready();
  6832. Client cli("localhost", PORT);
  6833. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6834. ASSERT_TRUE(res);
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6837. }
  6838. #ifdef _WIN32
  6839. // Issue #2435: mmap::open() must succeed even when another handle holds
  6840. // the file open for writing (e.g. an active log file).
  6841. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6842. const char *path = "mmap_concurrent_writer_test.txt";
  6843. const char *content = "hello";
  6844. {
  6845. std::ofstream f(path, std::ios::binary);
  6846. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6847. }
  6848. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6849. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6850. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6851. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6852. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6853. detail::mmap m(path);
  6854. ASSERT_TRUE(m.is_open());
  6855. EXPECT_EQ(strlen(content), m.size());
  6856. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6857. }
  6858. #endif
  6859. TEST(KeepAliveTest, ReadTimeout) {
  6860. Server svr;
  6861. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6862. std::this_thread::sleep_for(std::chrono::seconds(2));
  6863. res.set_content("a", "text/plain");
  6864. });
  6865. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6866. res.set_content("b", "text/plain");
  6867. });
  6868. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6869. auto se = detail::scope_exit([&] {
  6870. svr.stop();
  6871. listen_thread.join();
  6872. ASSERT_FALSE(svr.is_running());
  6873. });
  6874. svr.wait_until_ready();
  6875. Client cli("localhost", PORT);
  6876. cli.set_keep_alive(true);
  6877. cli.set_read_timeout(std::chrono::seconds(1));
  6878. auto resa = cli.Get("/a");
  6879. ASSERT_FALSE(resa);
  6880. EXPECT_EQ(Error::Read, resa.error());
  6881. auto resb = cli.Get("/b");
  6882. ASSERT_TRUE(resb);
  6883. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6884. EXPECT_EQ("b", resb->body);
  6885. }
  6886. TEST(KeepAliveTest, MaxCount) {
  6887. size_t keep_alive_max_count = 3;
  6888. Server svr;
  6889. svr.set_keep_alive_max_count(keep_alive_max_count);
  6890. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6891. res.set_content("Hello World!", "text/plain");
  6892. });
  6893. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6894. auto se = detail::scope_exit([&] {
  6895. svr.stop();
  6896. listen_thread.join();
  6897. ASSERT_FALSE(svr.is_running());
  6898. });
  6899. svr.wait_until_ready();
  6900. Client cli(HOST, PORT);
  6901. cli.set_keep_alive(true);
  6902. for (size_t i = 0; i < 5; i++) {
  6903. auto result = cli.Get("/hi");
  6904. ASSERT_TRUE(result);
  6905. EXPECT_EQ(StatusCode::OK_200, result->status);
  6906. if (i == keep_alive_max_count - 1) {
  6907. EXPECT_EQ("close", result->get_header_value("Connection"));
  6908. } else {
  6909. EXPECT_FALSE(result->has_header("Connection"));
  6910. }
  6911. }
  6912. }
  6913. TEST(KeepAliveTest, Issue1041) {
  6914. Server svr;
  6915. svr.set_keep_alive_timeout(3);
  6916. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6917. res.set_content("Hello World!", "text/plain");
  6918. });
  6919. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6920. auto se = detail::scope_exit([&] {
  6921. svr.stop();
  6922. listen_thread.join();
  6923. ASSERT_FALSE(svr.is_running());
  6924. });
  6925. svr.wait_until_ready();
  6926. Client cli(HOST, PORT);
  6927. cli.set_keep_alive(true);
  6928. auto result = cli.Get("/hi");
  6929. ASSERT_TRUE(result);
  6930. EXPECT_EQ(StatusCode::OK_200, result->status);
  6931. std::this_thread::sleep_for(std::chrono::seconds(5));
  6932. result = cli.Get("/hi");
  6933. ASSERT_TRUE(result);
  6934. EXPECT_EQ(StatusCode::OK_200, result->status);
  6935. }
  6936. TEST(KeepAliveTest, Issue1959) {
  6937. Server svr;
  6938. svr.set_keep_alive_timeout(5);
  6939. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6940. res.set_content("a", "text/plain");
  6941. });
  6942. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6943. auto se = detail::scope_exit([&] {
  6944. if (!svr.is_running()) return;
  6945. svr.stop();
  6946. listen_thread.join();
  6947. ASSERT_FALSE(svr.is_running());
  6948. });
  6949. svr.wait_until_ready();
  6950. Client cli("localhost", PORT);
  6951. cli.set_keep_alive(true);
  6952. using namespace std::chrono;
  6953. auto start = steady_clock::now();
  6954. cli.Get("/a");
  6955. svr.stop();
  6956. listen_thread.join();
  6957. auto end = steady_clock::now();
  6958. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6959. EXPECT_LT(elapsed, 5000);
  6960. }
  6961. #ifdef CPPHTTPLIB_SSL_ENABLED
  6962. TEST(KeepAliveTest, SSLClientReconnection) {
  6963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6964. ASSERT_TRUE(svr.is_valid());
  6965. svr.set_keep_alive_timeout(1);
  6966. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6967. res.set_content("Hello World!", "text/plain");
  6968. });
  6969. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6970. auto se = detail::scope_exit([&] {
  6971. svr.stop();
  6972. listen_thread.join();
  6973. ASSERT_FALSE(svr.is_running());
  6974. });
  6975. svr.wait_until_ready();
  6976. SSLClient cli(HOST, PORT);
  6977. cli.enable_server_certificate_verification(false);
  6978. cli.set_keep_alive(true);
  6979. auto result = cli.Get("/hi");
  6980. ASSERT_TRUE(result);
  6981. EXPECT_EQ(StatusCode::OK_200, result->status);
  6982. result = cli.Get("/hi");
  6983. ASSERT_TRUE(result);
  6984. EXPECT_EQ(StatusCode::OK_200, result->status);
  6985. std::this_thread::sleep_for(std::chrono::seconds(2));
  6986. // Recoonect
  6987. result = cli.Get("/hi");
  6988. ASSERT_TRUE(result);
  6989. EXPECT_EQ(StatusCode::OK_200, result->status);
  6990. result = cli.Get("/hi");
  6991. ASSERT_TRUE(result);
  6992. EXPECT_EQ(StatusCode::OK_200, result->status);
  6993. }
  6994. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6996. ASSERT_TRUE(svr.is_valid());
  6997. svr.set_keep_alive_timeout(1);
  6998. std::string content = "reconnect";
  6999. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7000. res.set_content("Hello World!", "text/plain");
  7001. });
  7002. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7003. auto se = detail::scope_exit([&] {
  7004. svr.stop();
  7005. listen_thread.join();
  7006. ASSERT_FALSE(svr.is_running());
  7007. });
  7008. svr.wait_until_ready();
  7009. SSLClient cli(HOST, PORT);
  7010. cli.enable_server_certificate_verification(false);
  7011. cli.set_keep_alive(true);
  7012. auto result = cli.Post(
  7013. "/hi", content.size(),
  7014. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7015. sink.write(content.c_str(), content.size());
  7016. return true;
  7017. },
  7018. "text/plain");
  7019. ASSERT_TRUE(result);
  7020. EXPECT_EQ(200, result->status);
  7021. std::this_thread::sleep_for(std::chrono::seconds(2));
  7022. // Recoonect
  7023. result = cli.Post(
  7024. "/hi", content.size(),
  7025. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7026. sink.write(content.c_str(), content.size());
  7027. return true;
  7028. },
  7029. "text/plain");
  7030. ASSERT_TRUE(result);
  7031. EXPECT_EQ(200, result->status);
  7032. result = cli.Post(
  7033. "/hi", content.size(),
  7034. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7035. sink.write(content.c_str(), content.size());
  7036. return true;
  7037. },
  7038. "text/plain");
  7039. ASSERT_TRUE(result);
  7040. EXPECT_EQ(200, result->status);
  7041. }
  7042. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7043. using namespace httplib::tls;
  7044. {
  7045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7046. ASSERT_TRUE(svr.is_valid());
  7047. svr.Get("/sni", [&](const Request &req, Response &res) {
  7048. std::string expected = req.sni();
  7049. EXPECT_EQ(expected, req.get_param_value("expected"));
  7050. res.set_content("ok", "text/plain");
  7051. });
  7052. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7053. auto se = detail::scope_exit([&] {
  7054. svr.stop();
  7055. listen_thread.join();
  7056. ASSERT_FALSE(svr.is_running());
  7057. });
  7058. svr.wait_until_ready();
  7059. {
  7060. SSLClient cli("localhost", PORT);
  7061. cli.enable_server_certificate_verification(false);
  7062. auto res = cli.Get("/sni?expected=localhost");
  7063. ASSERT_TRUE(res);
  7064. }
  7065. {
  7066. SSLClient cli("::1", PORT);
  7067. cli.enable_server_certificate_verification(false);
  7068. auto res = cli.Get("/sni?expected=");
  7069. // NOTE: This may fail if the server is listening on IPv4 only
  7070. // (e.g., when localhost resolves to 127.0.0.1 only)
  7071. if (res) {
  7072. EXPECT_EQ(StatusCode::OK_200, res->status);
  7073. } else {
  7074. EXPECT_EQ(Error::Connection, res.error());
  7075. }
  7076. }
  7077. }
  7078. }
  7079. #endif
  7080. TEST(ClientProblemDetectionTest, ContentProvider) {
  7081. Server svr;
  7082. size_t content_length = 1024 * 1024;
  7083. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7084. res.set_content_provider(
  7085. content_length, "text/plain",
  7086. [&](size_t offset, size_t length, DataSink &sink) {
  7087. auto out_len = std::min(length, static_cast<size_t>(1024));
  7088. std::string out(out_len, '@');
  7089. sink.write(out.data(), out_len);
  7090. return offset < 4096;
  7091. },
  7092. [](bool success) { ASSERT_FALSE(success); });
  7093. });
  7094. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7095. res.set_content_provider(
  7096. 0, "text/plain",
  7097. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7098. EXPECT_TRUE(false);
  7099. return true;
  7100. },
  7101. [](bool success) { ASSERT_FALSE(success); });
  7102. });
  7103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7104. auto se = detail::scope_exit([&] {
  7105. svr.stop();
  7106. listen_thread.join();
  7107. ASSERT_FALSE(svr.is_running());
  7108. });
  7109. svr.wait_until_ready();
  7110. Client cli("localhost", PORT);
  7111. {
  7112. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7113. size_t /*data_length*/) { return false; });
  7114. ASSERT_FALSE(res);
  7115. }
  7116. {
  7117. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7118. size_t /*data_length*/) { return false; });
  7119. ASSERT_TRUE(res);
  7120. }
  7121. }
  7122. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7123. Server svr;
  7124. svr.set_error_handler([](Request const &, Response &res) -> void {
  7125. res.set_chunked_content_provider(
  7126. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7127. sink.os << "hello";
  7128. sink.os << "world";
  7129. sink.done();
  7130. return true;
  7131. });
  7132. });
  7133. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7134. auto se = detail::scope_exit([&] {
  7135. svr.stop();
  7136. listen_thread.join();
  7137. ASSERT_FALSE(svr.is_running());
  7138. });
  7139. svr.wait_until_ready();
  7140. Client cli("localhost", PORT);
  7141. auto res = cli.Get("/");
  7142. ASSERT_TRUE(res);
  7143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7144. EXPECT_EQ("helloworld", res->body);
  7145. }
  7146. TEST(LongPollingTest, ClientCloseDetection) {
  7147. Server svr;
  7148. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7149. res.set_chunked_content_provider(
  7150. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7151. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7152. sink.os << "hello";
  7153. auto count = 10;
  7154. while (count > 0 && sink.is_writable()) {
  7155. this_thread::sleep_for(chrono::milliseconds(10));
  7156. count--;
  7157. }
  7158. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7159. return true;
  7160. });
  7161. });
  7162. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7163. auto se = detail::scope_exit([&] {
  7164. svr.stop();
  7165. listen_thread.join();
  7166. ASSERT_FALSE(svr.is_running());
  7167. });
  7168. svr.wait_until_ready();
  7169. Client cli("localhost", PORT);
  7170. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7171. EXPECT_EQ("hello", string(data, data_length));
  7172. return false; // close the socket immediately.
  7173. });
  7174. ASSERT_FALSE(res);
  7175. }
  7176. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7177. Server svr;
  7178. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7179. res.set_chunked_content_provider(
  7180. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7181. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7182. sink.os << "hello";
  7183. EXPECT_TRUE(sink.os.good());
  7184. // Wait for the client to close the connection
  7185. auto count = 10;
  7186. while (count > 0 && sink.is_writable()) {
  7187. this_thread::sleep_for(chrono::milliseconds(10));
  7188. count--;
  7189. }
  7190. // After client disconnect, write repeatedly until the socket
  7191. // write actually fails (small writes may be absorbed by the
  7192. // kernel buffer)
  7193. std::string chunk(1024, 'x');
  7194. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7195. sink.os << chunk;
  7196. }
  7197. EXPECT_TRUE(sink.os.fail());
  7198. return true;
  7199. });
  7200. });
  7201. auto port = svr.bind_to_any_port("localhost");
  7202. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7203. auto se = detail::scope_exit([&] {
  7204. svr.stop();
  7205. listen_thread.join();
  7206. ASSERT_FALSE(svr.is_running());
  7207. });
  7208. svr.wait_until_ready();
  7209. Client cli("localhost", port);
  7210. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7211. EXPECT_EQ("hello", string(data, data_length));
  7212. return false; // close the socket immediately.
  7213. });
  7214. ASSERT_FALSE(res);
  7215. }
  7216. TEST(GetWithParametersTest, GetWithParameters) {
  7217. Server svr;
  7218. svr.Get("/", [&](const Request &req, Response &) {
  7219. EXPECT_EQ("world", req.get_param_value("hello"));
  7220. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7221. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7222. });
  7223. svr.Get("/params", [&](const Request &req, Response &) {
  7224. EXPECT_EQ("world", req.get_param_value("hello"));
  7225. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7226. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7227. });
  7228. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7229. EXPECT_EQ("resource-id", req.matches[1]);
  7230. EXPECT_EQ("foo", req.get_param_value("param1"));
  7231. EXPECT_EQ("bar", req.get_param_value("param2"));
  7232. });
  7233. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7234. EXPECT_EQ("user-id", req.path_params.at("id"));
  7235. EXPECT_EQ("foo", req.get_param_value("param1"));
  7236. EXPECT_EQ("bar", req.get_param_value("param2"));
  7237. });
  7238. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7239. auto se = detail::scope_exit([&] {
  7240. svr.stop();
  7241. listen_thread.join();
  7242. ASSERT_FALSE(svr.is_running());
  7243. });
  7244. svr.wait_until_ready();
  7245. {
  7246. Client cli(HOST, PORT);
  7247. Params params;
  7248. params.emplace("hello", "world");
  7249. params.emplace("hello2", "world2");
  7250. params.emplace("hello3", "world3");
  7251. auto res = cli.Get("/", params, Headers{});
  7252. ASSERT_TRUE(res);
  7253. EXPECT_EQ(StatusCode::OK_200, res->status);
  7254. }
  7255. {
  7256. Client cli(HOST, PORT);
  7257. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7258. ASSERT_TRUE(res);
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. }
  7261. {
  7262. Client cli(HOST, PORT);
  7263. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7264. ASSERT_TRUE(res);
  7265. EXPECT_EQ(StatusCode::OK_200, res->status);
  7266. }
  7267. {
  7268. Client cli(HOST, PORT);
  7269. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7270. ASSERT_TRUE(res);
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. }
  7273. }
  7274. TEST(GetWithParametersTest, GetWithParameters2) {
  7275. Server svr;
  7276. svr.Get("/", [&](const Request &req, Response &res) {
  7277. auto text = req.get_param_value("hello");
  7278. res.set_content(text, "text/plain");
  7279. });
  7280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7281. auto se = detail::scope_exit([&] {
  7282. svr.stop();
  7283. listen_thread.join();
  7284. ASSERT_FALSE(svr.is_running());
  7285. });
  7286. svr.wait_until_ready();
  7287. Client cli("localhost", PORT);
  7288. Params params;
  7289. params.emplace("hello", "world");
  7290. std::string body;
  7291. auto res = cli.Get("/", params, Headers{},
  7292. [&](const char *data, size_t data_length) {
  7293. body.append(data, data_length);
  7294. return true;
  7295. });
  7296. ASSERT_TRUE(res);
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ("world", body);
  7299. }
  7300. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7301. auto host = "httpbingo.org";
  7302. auto path = std::string{"/range/32"};
  7303. #ifdef CPPHTTPLIB_SSL_ENABLED
  7304. SSLClient cli(host);
  7305. #else
  7306. Client cli(host);
  7307. #endif
  7308. cli.set_default_headers({make_range_header({{1, 10}})});
  7309. cli.set_connection_timeout(5);
  7310. {
  7311. auto res = cli.Get(path);
  7312. ASSERT_TRUE(res);
  7313. EXPECT_EQ("bcdefghijk", res->body);
  7314. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7315. }
  7316. {
  7317. auto res = cli.Get(path);
  7318. ASSERT_TRUE(res);
  7319. EXPECT_EQ("bcdefghijk", res->body);
  7320. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7321. }
  7322. }
  7323. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7324. Server svr;
  7325. svr.set_default_headers({{"Hello", "World"}});
  7326. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7327. res.set_content("ok", "text/plain");
  7328. });
  7329. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7330. auto se = detail::scope_exit([&] {
  7331. svr.stop();
  7332. listen_thread.join();
  7333. ASSERT_FALSE(svr.is_running());
  7334. });
  7335. svr.wait_until_ready();
  7336. Client cli("localhost", PORT);
  7337. auto res = cli.Get("/");
  7338. ASSERT_TRUE(res);
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. EXPECT_EQ("ok", res->body);
  7341. EXPECT_EQ("World", res->get_header_value("Hello"));
  7342. }
  7343. #ifdef CPPHTTPLIB_SSL_ENABLED
  7344. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7345. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7346. ASSERT_TRUE(svr.is_valid());
  7347. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7348. std::this_thread::sleep_for(std::chrono::seconds(2));
  7349. res.set_content("a", "text/plain");
  7350. });
  7351. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7352. res.set_content("b", "text/plain");
  7353. });
  7354. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7355. auto se = detail::scope_exit([&] {
  7356. svr.stop();
  7357. listen_thread.join();
  7358. ASSERT_FALSE(svr.is_running());
  7359. });
  7360. svr.wait_until_ready();
  7361. SSLClient cli("localhost", PORT);
  7362. cli.enable_server_certificate_verification(false);
  7363. cli.set_keep_alive(true);
  7364. cli.set_read_timeout(std::chrono::seconds(1));
  7365. auto resa = cli.Get("/a");
  7366. ASSERT_TRUE(!resa);
  7367. EXPECT_EQ(Error::Read, resa.error());
  7368. auto resb = cli.Get("/b");
  7369. ASSERT_TRUE(resb);
  7370. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7371. EXPECT_EQ("b", resb->body);
  7372. }
  7373. #endif
  7374. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7375. protected:
  7376. ServerTestWithAI_PASSIVE()
  7377. : cli_(HOST, PORT)
  7378. #ifdef CPPHTTPLIB_SSL_ENABLED
  7379. ,
  7380. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7381. #endif
  7382. {
  7383. #ifdef CPPHTTPLIB_SSL_ENABLED
  7384. cli_.enable_server_certificate_verification(false);
  7385. #endif
  7386. }
  7387. virtual void SetUp() {
  7388. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7389. res.set_content("Hello World!", "text/plain");
  7390. });
  7391. t_ = thread(
  7392. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7393. svr_.wait_until_ready();
  7394. }
  7395. virtual void TearDown() {
  7396. svr_.stop();
  7397. t_.join();
  7398. }
  7399. #ifdef CPPHTTPLIB_SSL_ENABLED
  7400. SSLClient cli_;
  7401. SSLServer svr_;
  7402. #else
  7403. Client cli_;
  7404. Server svr_;
  7405. #endif
  7406. thread t_;
  7407. };
  7408. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7409. auto res = cli_.Get("/hi");
  7410. ASSERT_TRUE(res);
  7411. EXPECT_EQ(StatusCode::OK_200, res->status);
  7412. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7413. EXPECT_EQ("Hello World!", res->body);
  7414. }
  7415. class ServerUpDownTest : public ::testing::Test {
  7416. protected:
  7417. ServerUpDownTest() : cli_(HOST, PORT) {}
  7418. virtual void SetUp() {
  7419. t_ = thread([&]() {
  7420. svr_.bind_to_any_port(HOST);
  7421. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7422. ASSERT_TRUE(svr_.listen_after_bind());
  7423. });
  7424. svr_.wait_until_ready();
  7425. }
  7426. virtual void TearDown() {
  7427. svr_.stop();
  7428. t_.join();
  7429. }
  7430. Client cli_;
  7431. Server svr_;
  7432. thread t_;
  7433. };
  7434. TEST_F(ServerUpDownTest, QuickStartStop) {
  7435. // Should not crash, especially when run with
  7436. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7437. }
  7438. class PayloadMaxLengthTest : public ::testing::Test {
  7439. protected:
  7440. PayloadMaxLengthTest()
  7441. : cli_(HOST, PORT)
  7442. #ifdef CPPHTTPLIB_SSL_ENABLED
  7443. ,
  7444. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7445. #endif
  7446. {
  7447. #ifdef CPPHTTPLIB_SSL_ENABLED
  7448. cli_.enable_server_certificate_verification(false);
  7449. #endif
  7450. }
  7451. virtual void SetUp() {
  7452. svr_.set_payload_max_length(8);
  7453. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7454. res.set_content("test", "text/plain");
  7455. });
  7456. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7457. svr_.wait_until_ready();
  7458. }
  7459. virtual void TearDown() {
  7460. svr_.stop();
  7461. t_.join();
  7462. }
  7463. #ifdef CPPHTTPLIB_SSL_ENABLED
  7464. SSLClient cli_;
  7465. SSLServer svr_;
  7466. #else
  7467. Client cli_;
  7468. Server svr_;
  7469. #endif
  7470. thread t_;
  7471. };
  7472. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7473. auto res = cli_.Post("/test", "123456789", "text/plain");
  7474. ASSERT_TRUE(res);
  7475. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7476. res = cli_.Post("/test", "12345678", "text/plain");
  7477. ASSERT_TRUE(res);
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. }
  7480. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7481. // Test chunked encoding with payload exceeding the 8-byte limit
  7482. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7483. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7484. ASSERT_TRUE(res);
  7485. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7486. }
  7487. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7488. // Test chunked encoding with payload within the 8-byte limit
  7489. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7490. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7491. ASSERT_TRUE(res);
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. }
  7494. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7495. // Test using send_request to send chunked data exceeding payload limit
  7496. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7497. "Host: " +
  7498. std::string(HOST) + ":" + std::to_string(PORT) +
  7499. "\r\n"
  7500. "Transfer-Encoding: chunked\r\n"
  7501. "Connection: close\r\n"
  7502. "\r\n"
  7503. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7504. "0123456789\r\n"
  7505. "0\r\n" // End chunk
  7506. "\r\n";
  7507. std::string response;
  7508. bool result = send_request(1, chunked_request, &response);
  7509. if (!result) {
  7510. // If send_request fails, it might be because the server closed the
  7511. // connection due to payload limit enforcement, which is acceptable
  7512. SUCCEED()
  7513. << "Server rejected oversized chunked request (connection closed)";
  7514. } else {
  7515. // If we got a response, check if it's an error response or connection was
  7516. // closed early Short response length indicates connection was closed due to
  7517. // payload limit
  7518. if (response.length() <= 10) {
  7519. SUCCEED() << "Server closed connection for oversized chunked request";
  7520. } else {
  7521. // Check for error status codes
  7522. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7523. response.find("Payload Too Large") != std::string::npos ||
  7524. response.find("400") != std::string::npos);
  7525. }
  7526. }
  7527. }
  7528. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7529. // Test request without Content-Length header exceeding payload limit
  7530. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7531. "Host: " +
  7532. std::string(HOST) + ":" +
  7533. std::to_string(PORT) +
  7534. "\r\n"
  7535. "Connection: close\r\n"
  7536. "\r\n";
  7537. // Add payload exceeding the 8-byte limit
  7538. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7539. request_without_content_length += large_payload;
  7540. std::string response;
  7541. bool result = send_request(1, request_without_content_length, &response);
  7542. if (!result) {
  7543. // If send_request fails, server likely closed connection due to payload
  7544. // limit
  7545. SUCCEED() << "Server rejected oversized request without Content-Length "
  7546. "(connection closed)";
  7547. } else {
  7548. // Check if server responded with error or closed connection early
  7549. if (response.length() <= 10) {
  7550. SUCCEED() << "Server closed connection for oversized request without "
  7551. "Content-Length";
  7552. } else {
  7553. // Check for error status codes
  7554. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7555. response.find("Payload Too Large") != std::string::npos ||
  7556. response.find("400") != std::string::npos);
  7557. }
  7558. }
  7559. }
  7560. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7561. // Test request without Content-Length header within payload limit
  7562. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7563. "Host: " +
  7564. std::string(HOST) + ":" +
  7565. std::to_string(PORT) +
  7566. "\r\n"
  7567. "Connection: close\r\n"
  7568. "\r\n";
  7569. // Add payload within the 8-byte limit
  7570. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7571. request_without_content_length += small_payload;
  7572. std::string response;
  7573. bool result = send_request(1, request_without_content_length, &response);
  7574. // For requests without Content-Length, the server may have different behavior
  7575. // The key is that it should not reject due to payload limit for small
  7576. // payloads
  7577. if (result) {
  7578. // Check for any HTTP response (success or error, but not connection closed)
  7579. if (response.length() > 10) {
  7580. SUCCEED()
  7581. << "Server processed request without Content-Length within limit";
  7582. } else {
  7583. // Short response might indicate connection closed, which is acceptable
  7584. SUCCEED() << "Server closed connection for request without "
  7585. "Content-Length (acceptable behavior)";
  7586. }
  7587. } else {
  7588. // Connection failure might be due to protocol requirements
  7589. SUCCEED() << "Connection issue with request without Content-Length "
  7590. "(environment-specific)";
  7591. }
  7592. }
  7593. class LargePayloadMaxLengthTest : public ::testing::Test {
  7594. protected:
  7595. LargePayloadMaxLengthTest()
  7596. : cli_(HOST, PORT)
  7597. #ifdef CPPHTTPLIB_SSL_ENABLED
  7598. ,
  7599. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7600. #endif
  7601. {
  7602. #ifdef CPPHTTPLIB_SSL_ENABLED
  7603. cli_.enable_server_certificate_verification(false);
  7604. #endif
  7605. }
  7606. virtual void SetUp() {
  7607. // Set 10MB payload limit
  7608. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7609. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7610. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7611. res.set_content("Large payload test", "text/plain");
  7612. });
  7613. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7614. svr_.wait_until_ready();
  7615. }
  7616. virtual void TearDown() {
  7617. svr_.stop();
  7618. t_.join();
  7619. }
  7620. #ifdef CPPHTTPLIB_SSL_ENABLED
  7621. SSLClient cli_;
  7622. SSLServer svr_;
  7623. #else
  7624. Client cli_;
  7625. Server svr_;
  7626. #endif
  7627. thread t_;
  7628. };
  7629. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7630. // Test chunked encoding with payload within 10MB limit
  7631. std::string medium_payload(5 * 1024 * 1024,
  7632. 'A'); // 5MB payload, within 10MB limit
  7633. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7634. ASSERT_TRUE(res);
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. }
  7637. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7638. // Test chunked encoding with payload exceeding 10MB limit
  7639. std::string large_payload(12 * 1024 * 1024,
  7640. 'B'); // 12MB payload, exceeds 10MB limit
  7641. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7642. // Server may either return 413 or close the connection
  7643. if (res) {
  7644. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7645. } else {
  7646. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7647. }
  7648. }
  7649. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7650. // Test request without Content-Length header within 10MB limit
  7651. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7652. "Host: " +
  7653. std::string(HOST) + ":" +
  7654. std::to_string(PORT) +
  7655. "\r\n"
  7656. "Connection: close\r\n"
  7657. "\r\n";
  7658. // Add 1MB payload (within 10MB limit)
  7659. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7660. request_without_content_length += medium_payload;
  7661. std::string response;
  7662. bool result = send_request(5, request_without_content_length, &response);
  7663. if (result) {
  7664. // Should get a proper HTTP response for payloads within limit
  7665. if (response.length() > 10) {
  7666. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7667. "10MB limit";
  7668. } else {
  7669. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7670. "Content-Length)";
  7671. }
  7672. } else {
  7673. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7674. }
  7675. }
  7676. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7677. // Test request without Content-Length header exceeding 10MB limit
  7678. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7679. "Host: " +
  7680. std::string(HOST) + ":" +
  7681. std::to_string(PORT) +
  7682. "\r\n"
  7683. "Connection: close\r\n"
  7684. "\r\n";
  7685. // Add 12MB payload (exceeds 10MB limit)
  7686. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7687. request_without_content_length += large_payload;
  7688. std::string response;
  7689. bool result = send_request(10, request_without_content_length, &response);
  7690. if (!result) {
  7691. // Server should close connection due to payload limit
  7692. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7693. "(connection closed)";
  7694. } else {
  7695. // Check for error response
  7696. if (response.length() <= 10) {
  7697. SUCCEED()
  7698. << "Server closed connection for 12MB request exceeding 10MB limit";
  7699. } else {
  7700. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7701. response.find("Payload Too Large") != std::string::npos ||
  7702. response.find("400") != std::string::npos);
  7703. }
  7704. }
  7705. }
  7706. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7707. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7708. // path.
  7709. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7710. Server svr;
  7711. const size_t LIMIT = 64 * 1024; // 64KB
  7712. svr.set_payload_max_length(LIMIT);
  7713. size_t total = 0;
  7714. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7715. const ContentReader &content_reader) {
  7716. content_reader([&](const char * /*data*/, size_t len) {
  7717. total += len;
  7718. return true;
  7719. });
  7720. res.status = 200;
  7721. res.set_content("stream_ok", "text/plain");
  7722. });
  7723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7724. auto se = detail::scope_exit([&] {
  7725. svr.stop();
  7726. thread.join();
  7727. ASSERT_FALSE(svr.is_running());
  7728. });
  7729. svr.wait_until_ready();
  7730. // Prepare 256KB raw data and gzip-compress it
  7731. std::string raw(256 * 1024, 'A');
  7732. std::string gz;
  7733. {
  7734. z_stream zs{};
  7735. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7736. Z_DEFAULT_STRATEGY);
  7737. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7738. zs.avail_in = static_cast<uInt>(raw.size());
  7739. char outbuf[4096];
  7740. int ret;
  7741. do {
  7742. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7743. zs.avail_out = sizeof(outbuf);
  7744. ret = deflate(&zs, Z_FINISH);
  7745. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7746. } while (ret != Z_STREAM_END);
  7747. deflateEnd(&zs);
  7748. }
  7749. Client cli(HOST, PORT);
  7750. cli.set_connection_timeout(std::chrono::seconds(5));
  7751. Headers headers = {{"Content-Encoding", "gzip"}};
  7752. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7753. "application/octet-stream");
  7754. ASSERT_TRUE(res);
  7755. // Server must reject oversized decompressed payloads with 413.
  7756. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7757. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7758. EXPECT_LE(total, LIMIT);
  7759. }
  7760. #endif
  7761. // Regression test for DoS vulnerability: a malicious server sending a response
  7762. // without Content-Length header must not cause unbounded memory consumption on
  7763. // the client side. The client should stop reading after a reasonable limit,
  7764. // similar to the server-side set_payload_max_length protection.
  7765. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7766. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7767. #ifndef _WIN32
  7768. signal(SIGPIPE, SIG_IGN);
  7769. #endif
  7770. auto server_thread = std::thread([] {
  7771. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7772. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7773. default_socket_options(srv);
  7774. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7775. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7776. sockaddr_in addr{};
  7777. addr.sin_family = AF_INET;
  7778. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7779. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7780. int opt = 1;
  7781. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7782. #ifdef _WIN32
  7783. reinterpret_cast<const char *>(&opt),
  7784. #else
  7785. &opt,
  7786. #endif
  7787. sizeof(opt));
  7788. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7789. ::listen(srv, 1);
  7790. sockaddr_in cli_addr{};
  7791. socklen_t cli_len = sizeof(cli_addr);
  7792. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7793. if (cli != INVALID_SOCKET) {
  7794. char buf[4096];
  7795. ::recv(cli, buf, sizeof(buf), 0);
  7796. // Malicious response: no Content-Length, no chunked encoding
  7797. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7798. "Connection: close\r\n"
  7799. "\r\n";
  7800. ::send(cli,
  7801. #ifdef _WIN32
  7802. static_cast<const char *>(response_header.c_str()),
  7803. static_cast<int>(response_header.size()),
  7804. #else
  7805. response_header.c_str(), response_header.size(),
  7806. #endif
  7807. 0);
  7808. // Send 10MB of data
  7809. std::string chunk(64 * 1024, 'A');
  7810. size_t total_sent = 0;
  7811. while (total_sent < MALICIOUS_DATA_SIZE) {
  7812. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7813. auto sent = ::send(cli,
  7814. #ifdef _WIN32
  7815. static_cast<const char *>(chunk.c_str()),
  7816. static_cast<int>(to_send),
  7817. #else
  7818. chunk.c_str(), to_send,
  7819. #endif
  7820. 0);
  7821. if (sent <= 0) break;
  7822. total_sent += static_cast<size_t>(sent);
  7823. }
  7824. detail::close_socket(cli);
  7825. }
  7826. detail::close_socket(srv);
  7827. });
  7828. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7829. size_t total_read = 0;
  7830. {
  7831. Client cli("127.0.0.1", PORT + 2);
  7832. cli.set_read_timeout(5, 0);
  7833. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7834. auto stream = cli.open_stream("GET", "/malicious");
  7835. ASSERT_TRUE(stream.is_valid());
  7836. char buffer[64 * 1024];
  7837. ssize_t n;
  7838. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7839. total_read += static_cast<size_t>(n);
  7840. }
  7841. } // StreamHandle and Client destroyed here, closing the socket
  7842. server_thread.join();
  7843. // With set_payload_max_length, the client must stop reading before consuming
  7844. // all 10MB. The read loop should be cut off at or near the configured limit.
  7845. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7846. << "Client read " << total_read << " bytes, exceeding the configured "
  7847. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7848. }
  7849. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7850. // the entire response body without truncation.
  7851. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7852. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7853. #ifndef _WIN32
  7854. signal(SIGPIPE, SIG_IGN);
  7855. #endif
  7856. auto server_thread = std::thread([] {
  7857. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7858. default_socket_options(srv);
  7859. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7860. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7861. sockaddr_in addr{};
  7862. addr.sin_family = AF_INET;
  7863. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7864. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7865. int opt = 1;
  7866. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7867. #ifdef _WIN32
  7868. reinterpret_cast<const char *>(&opt),
  7869. #else
  7870. &opt,
  7871. #endif
  7872. sizeof(opt));
  7873. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7874. ::listen(srv, 1);
  7875. sockaddr_in cli_addr{};
  7876. socklen_t cli_len = sizeof(cli_addr);
  7877. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7878. if (cli != INVALID_SOCKET) {
  7879. char buf[4096];
  7880. ::recv(cli, buf, sizeof(buf), 0);
  7881. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7882. "Connection: close\r\n"
  7883. "\r\n";
  7884. ::send(cli,
  7885. #ifdef _WIN32
  7886. static_cast<const char *>(response_header.c_str()),
  7887. static_cast<int>(response_header.size()),
  7888. #else
  7889. response_header.c_str(), response_header.size(),
  7890. #endif
  7891. 0);
  7892. std::string chunk(64 * 1024, 'A');
  7893. size_t total_sent = 0;
  7894. while (total_sent < DATA_SIZE) {
  7895. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7896. auto sent = ::send(cli,
  7897. #ifdef _WIN32
  7898. static_cast<const char *>(chunk.c_str()),
  7899. static_cast<int>(to_send),
  7900. #else
  7901. chunk.c_str(), to_send,
  7902. #endif
  7903. 0);
  7904. if (sent <= 0) break;
  7905. total_sent += static_cast<size_t>(sent);
  7906. }
  7907. #ifdef _WIN32
  7908. ::shutdown(cli, SD_SEND);
  7909. #else
  7910. ::shutdown(cli, SHUT_WR);
  7911. #endif
  7912. // Drain until the client closes its end, ensuring all data is delivered
  7913. char drain[1024];
  7914. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7915. detail::close_socket(cli);
  7916. }
  7917. detail::close_socket(srv);
  7918. });
  7919. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7920. size_t total_read = 0;
  7921. {
  7922. Client cli("127.0.0.1", PORT + 2);
  7923. cli.set_read_timeout(5, 0);
  7924. cli.set_payload_max_length(0); // 0 means no limit
  7925. auto stream = cli.open_stream("GET", "/data");
  7926. ASSERT_TRUE(stream.is_valid());
  7927. char buffer[64 * 1024];
  7928. ssize_t n;
  7929. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7930. total_read += static_cast<size_t>(n);
  7931. }
  7932. }
  7933. server_thread.join();
  7934. EXPECT_EQ(total_read, DATA_SIZE)
  7935. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7936. << " bytes without truncation, but only read " << total_read << " bytes.";
  7937. }
  7938. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  7939. // enormous Content-Length must not cause the client to pre-allocate a huge
  7940. // response body buffer. The reservation is capped at payload_max_length_, and
  7941. // the read itself fails when the body exceeds the limit.
  7942. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  7943. #ifndef _WIN32
  7944. signal(SIGPIPE, SIG_IGN);
  7945. #endif
  7946. auto server_thread = std::thread([] {
  7947. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7948. default_socket_options(srv);
  7949. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7950. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7951. sockaddr_in addr{};
  7952. addr.sin_family = AF_INET;
  7953. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7954. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7955. int opt = 1;
  7956. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7957. #ifdef _WIN32
  7958. reinterpret_cast<const char *>(&opt),
  7959. #else
  7960. &opt,
  7961. #endif
  7962. sizeof(opt));
  7963. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7964. ::listen(srv, 1);
  7965. sockaddr_in cli_addr{};
  7966. socklen_t cli_len = sizeof(cli_addr);
  7967. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7968. if (cli != INVALID_SOCKET) {
  7969. char buf[4096];
  7970. ::recv(cli, buf, sizeof(buf), 0);
  7971. // Malicious response: claim a 20GB body but send only a tiny payload.
  7972. std::string response = "HTTP/1.1 200 OK\r\n"
  7973. "Content-Length: 20000000000\r\n"
  7974. "\r\n"
  7975. "abc";
  7976. ::send(cli,
  7977. #ifdef _WIN32
  7978. static_cast<const char *>(response.c_str()),
  7979. static_cast<int>(response.size()),
  7980. #else
  7981. response.c_str(), response.size(),
  7982. #endif
  7983. 0);
  7984. detail::close_socket(cli);
  7985. }
  7986. detail::close_socket(srv);
  7987. });
  7988. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7989. {
  7990. Client cli("127.0.0.1", PORT + 2);
  7991. cli.set_read_timeout(5, 0);
  7992. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  7993. // result in a 20GB pre-allocation. The Get() call is expected to fail
  7994. // (server claims more bytes than payload_max_length permits), but it must
  7995. // not exhaust memory before getting there.
  7996. auto res = cli.Get("/malicious");
  7997. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  7998. }
  7999. server_thread.join();
  8000. }
  8001. // Verify that content_receiver bypasses the default payload_max_length,
  8002. // allowing streaming downloads larger than 100MB without requiring an explicit
  8003. // set_payload_max_length call.
  8004. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8005. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8006. #ifndef _WIN32
  8007. signal(SIGPIPE, SIG_IGN);
  8008. #endif
  8009. auto server_thread = std::thread([] {
  8010. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8011. default_socket_options(srv);
  8012. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8013. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8014. sockaddr_in addr{};
  8015. addr.sin_family = AF_INET;
  8016. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8017. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8018. int opt = 1;
  8019. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8020. #ifdef _WIN32
  8021. reinterpret_cast<const char *>(&opt),
  8022. #else
  8023. &opt,
  8024. #endif
  8025. sizeof(opt));
  8026. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8027. ::listen(srv, 1);
  8028. sockaddr_in cli_addr{};
  8029. socklen_t cli_len = sizeof(cli_addr);
  8030. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8031. if (cli != INVALID_SOCKET) {
  8032. char buf[4096];
  8033. ::recv(cli, buf, sizeof(buf), 0);
  8034. // Response with Content-Length larger than default 100MB limit
  8035. auto content_length = std::to_string(DATA_SIZE);
  8036. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8037. "Content-Length: " +
  8038. content_length +
  8039. "\r\n"
  8040. "Connection: close\r\n"
  8041. "\r\n";
  8042. ::send(cli,
  8043. #ifdef _WIN32
  8044. static_cast<const char *>(response_header.c_str()),
  8045. static_cast<int>(response_header.size()),
  8046. #else
  8047. response_header.c_str(), response_header.size(),
  8048. #endif
  8049. 0);
  8050. std::string chunk(64 * 1024, 'A');
  8051. size_t total_sent = 0;
  8052. while (total_sent < DATA_SIZE) {
  8053. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8054. auto sent = ::send(cli,
  8055. #ifdef _WIN32
  8056. static_cast<const char *>(chunk.c_str()),
  8057. static_cast<int>(to_send),
  8058. #else
  8059. chunk.c_str(), to_send,
  8060. #endif
  8061. 0);
  8062. if (sent <= 0) break;
  8063. total_sent += static_cast<size_t>(sent);
  8064. }
  8065. detail::close_socket(cli);
  8066. }
  8067. detail::close_socket(srv);
  8068. });
  8069. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8070. size_t total_received = 0;
  8071. {
  8072. Client cli("127.0.0.1", PORT + 2);
  8073. cli.set_read_timeout(10, 0);
  8074. // Do NOT call set_payload_max_length — use the default 100MB limit
  8075. auto res =
  8076. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8077. total_received += data_length;
  8078. return true;
  8079. });
  8080. ASSERT_TRUE(res);
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. }
  8083. server_thread.join();
  8084. EXPECT_EQ(total_received, DATA_SIZE)
  8085. << "With content_receiver, the client should read all " << DATA_SIZE
  8086. << " bytes despite the default 100MB payload_max_length, but only read "
  8087. << total_received << " bytes.";
  8088. }
  8089. // Verify that an explicit set_payload_max_length smaller than the response is
  8090. // enforced even when a content_receiver is used.
  8091. TEST(ClientVulnerabilityTest,
  8092. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8093. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8094. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8095. #ifndef _WIN32
  8096. signal(SIGPIPE, SIG_IGN);
  8097. #endif
  8098. auto server_thread = std::thread([] {
  8099. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8100. default_socket_options(srv);
  8101. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8102. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8103. sockaddr_in addr{};
  8104. addr.sin_family = AF_INET;
  8105. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8106. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8107. int opt = 1;
  8108. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8109. #ifdef _WIN32
  8110. reinterpret_cast<const char *>(&opt),
  8111. #else
  8112. &opt,
  8113. #endif
  8114. sizeof(opt));
  8115. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8116. ::listen(srv, 1);
  8117. sockaddr_in cli_addr{};
  8118. socklen_t cli_len = sizeof(cli_addr);
  8119. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8120. if (cli != INVALID_SOCKET) {
  8121. char buf[4096];
  8122. ::recv(cli, buf, sizeof(buf), 0);
  8123. auto content_length = std::to_string(DATA_SIZE);
  8124. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8125. "Content-Length: " +
  8126. content_length +
  8127. "\r\n"
  8128. "Connection: close\r\n"
  8129. "\r\n";
  8130. ::send(cli,
  8131. #ifdef _WIN32
  8132. static_cast<const char *>(response_header.c_str()),
  8133. static_cast<int>(response_header.size()),
  8134. #else
  8135. response_header.c_str(), response_header.size(),
  8136. #endif
  8137. 0);
  8138. std::string chunk(64 * 1024, 'A');
  8139. size_t total_sent = 0;
  8140. while (total_sent < DATA_SIZE) {
  8141. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8142. auto sent = ::send(cli,
  8143. #ifdef _WIN32
  8144. static_cast<const char *>(chunk.c_str()),
  8145. static_cast<int>(to_send),
  8146. #else
  8147. chunk.c_str(), to_send,
  8148. #endif
  8149. 0);
  8150. if (sent <= 0) break;
  8151. total_sent += static_cast<size_t>(sent);
  8152. }
  8153. detail::close_socket(cli);
  8154. }
  8155. detail::close_socket(srv);
  8156. });
  8157. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8158. size_t total_received = 0;
  8159. {
  8160. Client cli("127.0.0.1", PORT + 2);
  8161. cli.set_read_timeout(10, 0);
  8162. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8163. auto res =
  8164. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8165. total_received += data_length;
  8166. return true;
  8167. });
  8168. // Should fail because 200MB exceeds the explicit 150MB limit
  8169. EXPECT_FALSE(res);
  8170. }
  8171. server_thread.join();
  8172. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8173. << "Client with content_receiver should respect the explicit "
  8174. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8175. << total_received << " bytes.";
  8176. }
  8177. // Verify that an explicit set_payload_max_length larger than the response
  8178. // allows the content_receiver to read all data successfully.
  8179. TEST(ClientVulnerabilityTest,
  8180. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8181. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8182. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8183. #ifndef _WIN32
  8184. signal(SIGPIPE, SIG_IGN);
  8185. #endif
  8186. auto server_thread = std::thread([] {
  8187. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8188. default_socket_options(srv);
  8189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8190. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8191. sockaddr_in addr{};
  8192. addr.sin_family = AF_INET;
  8193. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8194. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8195. int opt = 1;
  8196. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8197. #ifdef _WIN32
  8198. reinterpret_cast<const char *>(&opt),
  8199. #else
  8200. &opt,
  8201. #endif
  8202. sizeof(opt));
  8203. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8204. ::listen(srv, 1);
  8205. sockaddr_in cli_addr{};
  8206. socklen_t cli_len = sizeof(cli_addr);
  8207. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8208. if (cli != INVALID_SOCKET) {
  8209. char buf[4096];
  8210. ::recv(cli, buf, sizeof(buf), 0);
  8211. auto content_length = std::to_string(DATA_SIZE);
  8212. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8213. "Content-Length: " +
  8214. content_length +
  8215. "\r\n"
  8216. "Connection: close\r\n"
  8217. "\r\n";
  8218. ::send(cli,
  8219. #ifdef _WIN32
  8220. static_cast<const char *>(response_header.c_str()),
  8221. static_cast<int>(response_header.size()),
  8222. #else
  8223. response_header.c_str(), response_header.size(),
  8224. #endif
  8225. 0);
  8226. std::string chunk(64 * 1024, 'A');
  8227. size_t total_sent = 0;
  8228. while (total_sent < DATA_SIZE) {
  8229. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8230. auto sent = ::send(cli,
  8231. #ifdef _WIN32
  8232. static_cast<const char *>(chunk.c_str()),
  8233. static_cast<int>(to_send),
  8234. #else
  8235. chunk.c_str(), to_send,
  8236. #endif
  8237. 0);
  8238. if (sent <= 0) break;
  8239. total_sent += static_cast<size_t>(sent);
  8240. }
  8241. #ifdef _WIN32
  8242. ::shutdown(cli, SD_SEND);
  8243. #else
  8244. ::shutdown(cli, SHUT_WR);
  8245. #endif
  8246. char drain[1024];
  8247. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8248. detail::close_socket(cli);
  8249. }
  8250. detail::close_socket(srv);
  8251. });
  8252. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8253. size_t total_received = 0;
  8254. {
  8255. Client cli("127.0.0.1", PORT + 2);
  8256. cli.set_read_timeout(10, 0);
  8257. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8258. auto res =
  8259. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8260. total_received += data_length;
  8261. return true;
  8262. });
  8263. ASSERT_TRUE(res);
  8264. EXPECT_EQ(StatusCode::OK_200, res->status);
  8265. }
  8266. server_thread.join();
  8267. EXPECT_EQ(total_received, DATA_SIZE)
  8268. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8269. << " bytes (larger than " << DATA_SIZE
  8270. << " bytes response), content_receiver should read all data, but only "
  8271. "read "
  8272. << total_received << " bytes.";
  8273. }
  8274. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8275. // Regression test for "zip bomb" attack on the client side: a malicious server
  8276. // sends a small gzip-compressed response that decompresses to a huge payload.
  8277. // The client must enforce payload_max_length on the decompressed size.
  8278. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8279. constexpr size_t DECOMPRESSED_SIZE =
  8280. 10 * 1024 * 1024; // 10MB after decompression
  8281. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8282. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8283. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8284. std::string compressed;
  8285. {
  8286. httplib::detail::gzip_compressor compressor;
  8287. bool ok =
  8288. compressor.compress(uncompressed.data(), uncompressed.size(),
  8289. /*last=*/true, [&](const char *buf, size_t len) {
  8290. compressed.append(buf, len);
  8291. return true;
  8292. });
  8293. ASSERT_TRUE(ok);
  8294. }
  8295. // Sanity: compressed data should be much smaller than the decompressed size
  8296. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8297. #ifndef _WIN32
  8298. signal(SIGPIPE, SIG_IGN);
  8299. #endif
  8300. // Set up the listening socket in the main thread so the server is guaranteed
  8301. // to be ready before the client connects (eliminates race condition).
  8302. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8303. default_socket_options(srv);
  8304. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8305. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8306. sockaddr_in addr{};
  8307. addr.sin_family = AF_INET;
  8308. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8309. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8310. int opt = 1;
  8311. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8312. #ifdef _WIN32
  8313. reinterpret_cast<const char *>(&opt),
  8314. #else
  8315. &opt,
  8316. #endif
  8317. sizeof(opt));
  8318. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8319. ASSERT_EQ(0, ::listen(srv, 1));
  8320. auto server_thread = std::thread([&compressed, srv] {
  8321. sockaddr_in cli_addr{};
  8322. socklen_t cli_len = sizeof(cli_addr);
  8323. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8324. if (cli != INVALID_SOCKET) {
  8325. // Read the full HTTP request (until \r\n\r\n)
  8326. char buf[4096];
  8327. size_t total = 0;
  8328. while (total < sizeof(buf)) {
  8329. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8330. if (n <= 0) break;
  8331. total += static_cast<size_t>(n);
  8332. // Check for end of headers
  8333. if (total >= 4) {
  8334. std::string req(buf, total);
  8335. if (req.find("\r\n\r\n") != std::string::npos) break;
  8336. }
  8337. }
  8338. // Malicious response: gzip-compressed body, no Content-Length
  8339. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8340. "Content-Encoding: gzip\r\n"
  8341. "Connection: close\r\n"
  8342. "\r\n";
  8343. ::send(cli,
  8344. #ifdef _WIN32
  8345. static_cast<const char *>(response_header.c_str()),
  8346. static_cast<int>(response_header.size()),
  8347. #else
  8348. response_header.c_str(), response_header.size(),
  8349. #endif
  8350. 0);
  8351. // Send the compressed payload (small on the wire, huge when decompressed)
  8352. size_t total_sent = 0;
  8353. while (total_sent < compressed.size()) {
  8354. auto to_send = std::min(compressed.size() - total_sent,
  8355. static_cast<size_t>(64 * 1024));
  8356. auto sent =
  8357. ::send(cli,
  8358. #ifdef _WIN32
  8359. static_cast<const char *>(compressed.c_str() + total_sent),
  8360. static_cast<int>(to_send),
  8361. #else
  8362. compressed.c_str() + total_sent, to_send,
  8363. #endif
  8364. 0);
  8365. if (sent <= 0) break;
  8366. total_sent += static_cast<size_t>(sent);
  8367. }
  8368. detail::close_socket(cli);
  8369. }
  8370. });
  8371. auto se = detail::scope_exit([&] {
  8372. detail::close_socket(srv);
  8373. server_thread.join();
  8374. });
  8375. size_t total_decompressed = 0;
  8376. {
  8377. Client cli("127.0.0.1", PORT + 3);
  8378. cli.set_read_timeout(5, 0);
  8379. cli.set_decompress(true);
  8380. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8381. auto stream = cli.open_stream("GET", "/zipbomb");
  8382. ASSERT_TRUE(stream.is_valid());
  8383. char buffer[64 * 1024];
  8384. ssize_t n;
  8385. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8386. total_decompressed += static_cast<size_t>(n);
  8387. }
  8388. }
  8389. // The decompressed size must be capped by payload_max_length. Without
  8390. // protection, the client would decompress the full 10MB from a tiny
  8391. // compressed payload, enabling a zip bomb DoS attack.
  8392. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8393. << "Client decompressed " << total_decompressed
  8394. << " bytes from a gzip response. The decompressed size should be "
  8395. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8396. }
  8397. #endif
  8398. TEST(HostAndPortPropertiesTest, NoSSL) {
  8399. httplib::Client cli("www.google.com", 1234);
  8400. ASSERT_EQ("www.google.com", cli.host());
  8401. ASSERT_EQ(1234, cli.port());
  8402. }
  8403. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8404. httplib::Client cli("www.google.com:1234");
  8405. ASSERT_EQ("www.google.com", cli.host());
  8406. ASSERT_EQ(1234, cli.port());
  8407. }
  8408. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8409. // Port number that overflows int — should not crash, client becomes invalid
  8410. httplib::Client cli("http://www.google.com:99999999999999999999");
  8411. ASSERT_FALSE(cli.is_valid());
  8412. }
  8413. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8414. // Port 99999 exceeds valid range (1-65535) — should not crash
  8415. httplib::Client cli("http://www.google.com:99999");
  8416. ASSERT_FALSE(cli.is_valid());
  8417. }
  8418. #ifdef CPPHTTPLIB_SSL_ENABLED
  8419. TEST(HostAndPortPropertiesTest, SSL) {
  8420. httplib::SSLClient cli("www.google.com");
  8421. ASSERT_EQ("www.google.com", cli.host());
  8422. ASSERT_EQ(443, cli.port());
  8423. }
  8424. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8425. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8426. std::string cert;
  8427. read_file(CA_CERT_FILE, cert);
  8428. httplib::SSLClient httplib_client("www.google.com");
  8429. // Load CA store first time
  8430. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8431. // Load CA store second time (update)
  8432. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8433. // Verify client is still valid and can make connections
  8434. httplib_client.enable_server_certificate_verification(true);
  8435. auto res = httplib_client.Get("/");
  8436. ASSERT_TRUE(res);
  8437. // Google may return 200 or 301 depending on various factors
  8438. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8439. res->status == StatusCode::MovedPermanently_301);
  8440. }
  8441. TEST(SSLClientTest, ServerNameIndication_Online) {
  8442. auto host = "httpbingo.org";
  8443. auto path = std::string{"/get"};
  8444. SSLClient cli(host, 443);
  8445. auto res = cli.Get(path);
  8446. ASSERT_TRUE(res);
  8447. ASSERT_EQ(StatusCode::OK_200, res->status);
  8448. }
  8449. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8450. // Use a site that will cause SSL verification failure due to self-signed cert
  8451. SSLClient cli("self-signed.badssl.com", 443);
  8452. cli.enable_server_certificate_verification(true);
  8453. auto res = cli.Get("/");
  8454. ASSERT_TRUE(!res);
  8455. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8456. // Verify backend error is captured for SSLServerVerification
  8457. // This occurs when certificate verification fails
  8458. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8459. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8460. EXPECT_NE(0UL, res.ssl_backend_error());
  8461. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8462. // For OpenSSL, ssl_error is 0 for verification errors
  8463. EXPECT_EQ(0, res.ssl_error());
  8464. #if !defined(_WIN32) || \
  8465. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8466. // On non-Windows or when Windows Schannel is disabled, the error comes
  8467. // from OpenSSL's verification
  8468. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8469. res.ssl_backend_error());
  8470. #endif
  8471. #endif
  8472. }
  8473. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8474. // Use a site where hostname doesn't match the certificate
  8475. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8476. SSLClient cli("wrong.host.badssl.com", 443);
  8477. cli.enable_server_certificate_verification(true);
  8478. cli.enable_server_hostname_verification(true);
  8479. auto res = cli.Get("/");
  8480. ASSERT_TRUE(!res);
  8481. // The error type depends on when hostname verification occurs:
  8482. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8483. // - Mbed TLS: SSLServerVerification (during handshake)
  8484. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8485. res.error() == Error::SSLServerVerification);
  8486. // Verify backend error is captured for hostname verification failure
  8487. EXPECT_NE(0UL, res.ssl_backend_error());
  8488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8489. // For OpenSSL, ssl_error is 0 for verification errors
  8490. EXPECT_EQ(0, res.ssl_error());
  8491. #if !defined(_WIN32) || \
  8492. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8493. // On non-Windows or when Windows Schannel is disabled, the error comes
  8494. // from OpenSSL's hostname verification
  8495. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8496. res.ssl_backend_error());
  8497. #endif
  8498. #endif
  8499. }
  8500. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8501. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8502. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8503. SSLClient cli("www.google.com", 443);
  8504. cli.enable_server_certificate_verification(true);
  8505. auto res = cli.Get("/");
  8506. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8507. }
  8508. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8509. SSLClient cli("www.google.com", 443);
  8510. cli.enable_server_certificate_verification(true);
  8511. cli.enable_windows_certificate_verification(false);
  8512. auto res = cli.Get("/");
  8513. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8514. }
  8515. #endif
  8516. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8517. Client cli("https://google.com");
  8518. auto res = cli.Get("/");
  8519. ASSERT_TRUE(res);
  8520. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8521. }
  8522. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8523. SSLClient cli("google.com");
  8524. cli.set_ca_cert_path(CA_CERT_FILE);
  8525. auto res = cli.Get("/");
  8526. ASSERT_TRUE(res);
  8527. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8528. }
  8529. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8530. SSLClient cli("google.com");
  8531. cli.enable_server_certificate_verification(true);
  8532. cli.set_ca_cert_path("hello");
  8533. auto res = cli.Get("/");
  8534. ASSERT_TRUE(!res);
  8535. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8536. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8537. // should be set
  8538. EXPECT_EQ(0, res.ssl_error());
  8539. // Verify backend error is captured for SSLLoadingCerts
  8540. // This error occurs when loading CA certificates fails
  8541. EXPECT_NE(0UL, res.ssl_backend_error());
  8542. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8543. // OpenSSL specific error codes:
  8544. // > openssl errstr 0x80000002
  8545. // error:80000002:system library::No such file or directory
  8546. // > openssl errstr 0xA000126
  8547. // error:0A000126:SSL routines::unexpected eof while reading
  8548. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8549. res.ssl_backend_error() == 0xA000126);
  8550. #endif
  8551. }
  8552. TEST(SSLClientTest, ServerCertificateVerification4) {
  8553. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8554. ASSERT_TRUE(svr.is_valid());
  8555. svr.Get("/test", [&](const Request &, Response &res) {
  8556. res.set_content("test", "text/plain");
  8557. svr.stop();
  8558. ASSERT_TRUE(true);
  8559. });
  8560. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8561. auto se = detail::scope_exit([&] {
  8562. t.join();
  8563. ASSERT_FALSE(svr.is_running());
  8564. });
  8565. svr.wait_until_ready();
  8566. SSLClient cli("127.0.0.1", PORT);
  8567. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8568. cli.enable_server_certificate_verification(true);
  8569. cli.set_connection_timeout(30);
  8570. auto res = cli.Get("/test");
  8571. ASSERT_TRUE(res);
  8572. ASSERT_EQ(StatusCode::OK_200, res->status);
  8573. }
  8574. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8575. std::string cert;
  8576. read_file(CA_CERT_FILE, cert);
  8577. SSLClient cli("google.com");
  8578. cli.load_ca_cert_store(cert.data(), cert.size());
  8579. const auto res = cli.Get("/");
  8580. ASSERT_TRUE(res);
  8581. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8582. }
  8583. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8584. // clang-format off
  8585. static constexpr char cert[] =
  8586. "GlobalSign Root CA\n"
  8587. "==================\n"
  8588. "-----BEGIN CERTIFICATE-----\n"
  8589. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8590. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8591. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8592. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8593. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8594. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8595. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8596. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8597. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8598. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8599. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8600. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8601. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8602. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8603. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8604. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8605. "-----END CERTIFICATE-----\n";
  8606. // clang-format on
  8607. SSLClient cli("google.com");
  8608. cli.load_ca_cert_store(cert, sizeof(cert));
  8609. const auto res = cli.Get("/");
  8610. ASSERT_TRUE(res);
  8611. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8612. }
  8613. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8614. SSLClient cli("www.youtube.com");
  8615. cli.set_ca_cert_path(CA_CERT_FILE);
  8616. cli.enable_server_certificate_verification(true);
  8617. cli.set_follow_location(true);
  8618. auto res = cli.Get("/");
  8619. ASSERT_TRUE(res);
  8620. ASSERT_EQ(StatusCode::OK_200, res->status);
  8621. }
  8622. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8623. SSLClient cli("wWw.YouTube.Com");
  8624. cli.set_ca_cert_path(CA_CERT_FILE);
  8625. cli.enable_server_certificate_verification(true);
  8626. cli.enable_server_hostname_verification(true);
  8627. cli.set_follow_location(true);
  8628. auto res = cli.Get("/");
  8629. ASSERT_TRUE(res);
  8630. ASSERT_EQ(StatusCode::OK_200, res->status);
  8631. }
  8632. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8633. SSLClient cli("gOoGlE.COm");
  8634. cli.enable_server_certificate_verification(true);
  8635. cli.enable_server_hostname_verification(true);
  8636. cli.set_follow_location(true);
  8637. auto res = cli.Get("/");
  8638. ASSERT_TRUE(res);
  8639. ASSERT_EQ(StatusCode::OK_200, res->status);
  8640. }
  8641. TEST(SSLClientTest, Issue2004_Online) {
  8642. Client client("https://google.com");
  8643. client.set_follow_location(true);
  8644. auto res = client.Get("/");
  8645. ASSERT_TRUE(res);
  8646. ASSERT_EQ(StatusCode::OK_200, res->status);
  8647. auto body = res->body;
  8648. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8649. }
  8650. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8651. // Create SSLClient with invalid cert/key to make is_valid() return false
  8652. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8653. "nonexistent_key.pem");
  8654. // is_valid() should be false due to cert loading failure
  8655. ASSERT_FALSE(cli.is_valid());
  8656. auto res = cli.Get("/");
  8657. ASSERT_FALSE(res);
  8658. EXPECT_EQ(Error::SSLConnection, res.error());
  8659. }
  8660. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8661. // Test for Issue #2251: SSL error not properly reported when client cert
  8662. // and key paths are swapped or mismatched
  8663. // This simulates the scenario where user accidentally swaps the cert and key
  8664. // files
  8665. // Using client cert file as private key and vice versa (completely wrong)
  8666. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8667. // Should fail validation due to cert/key mismatch
  8668. ASSERT_FALSE(cli.is_valid());
  8669. // Attempt to make a request should fail with proper error
  8670. auto res = cli.Get("/");
  8671. ASSERT_FALSE(res);
  8672. EXPECT_EQ(Error::SSLConnection, res.error());
  8673. // SSL error should be recorded in the Result object (this is the key fix for
  8674. // Issue #2251)
  8675. auto backend_error = res.ssl_backend_error();
  8676. EXPECT_NE(0u, backend_error);
  8677. }
  8678. // Tests cert/key mismatch detection at the TLS context level
  8679. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8680. // Test that using mismatched cert/key causes connection failure.
  8681. // We verify this at the SSLClient level rather than through internal
  8682. // TLS API functions.
  8683. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8684. cli.enable_server_certificate_verification(false);
  8685. cli.set_connection_timeout(2);
  8686. // The mismatch should cause a connection or handshake error
  8687. auto res = cli.Get("/test");
  8688. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8689. // Either way, the request should fail
  8690. EXPECT_FALSE(res);
  8691. }
  8692. #endif
  8693. #if 0
  8694. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8695. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8696. ASSERT_TRUE(cli != nullptr);
  8697. cli->set_address_family(AF_INET6);
  8698. cli->set_interface("en0");
  8699. auto res = cli->Get("/get");
  8700. ASSERT_TRUE(res);
  8701. ASSERT_EQ(StatusCode::OK_200, res->status);
  8702. }
  8703. #endif
  8704. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8705. #ifdef CPPHTTPLIB_SSL_ENABLED
  8706. void ClientCertPresent(
  8707. const std::string &client_cert_file,
  8708. const std::string &client_private_key_file,
  8709. const std::string &client_encrypted_private_key_pass = std::string()) {
  8710. using namespace httplib::tls;
  8711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8712. CLIENT_CA_CERT_DIR);
  8713. ASSERT_TRUE(svr.is_valid());
  8714. svr.Get("/test", [&](const Request &req, Response &res) {
  8715. res.set_content("test", "text/plain");
  8716. auto cert = req.peer_cert();
  8717. ASSERT_TRUE(static_cast<bool>(cert));
  8718. std::string common_name = cert.subject_cn();
  8719. EXPECT_EQ("Common Name", common_name);
  8720. });
  8721. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8722. auto se = detail::scope_exit([&] {
  8723. svr.stop();
  8724. t.join();
  8725. ASSERT_FALSE(svr.is_running());
  8726. });
  8727. svr.wait_until_ready();
  8728. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8729. client_encrypted_private_key_pass);
  8730. cli.enable_server_certificate_verification(false);
  8731. cli.set_connection_timeout(30);
  8732. auto res = cli.Get("/test");
  8733. ASSERT_TRUE(res);
  8734. ASSERT_EQ(StatusCode::OK_200, res->status);
  8735. }
  8736. TEST(SSLClientServerTest, ClientCertPresent) {
  8737. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8738. }
  8739. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8740. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8741. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8742. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8743. }
  8744. // PEM memory-based constructor tests (works with all TLS backends)
  8745. void PemMemoryClientCertPresent(
  8746. const std::string &client_cert_file,
  8747. const std::string &client_private_key_file,
  8748. const std::string &client_encrypted_private_key_pass = std::string()) {
  8749. // Read PEM files into memory
  8750. std::string server_cert_pem, server_key_pem;
  8751. std::string client_ca_pem;
  8752. std::string client_cert_pem, client_key_pem;
  8753. read_file(SERVER_CERT_FILE, server_cert_pem);
  8754. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8755. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8756. read_file(client_cert_file, client_cert_pem);
  8757. read_file(client_private_key_file, client_key_pem);
  8758. // Create server with PEM memory
  8759. SSLServer::PemMemory server_pem = {
  8760. server_cert_pem.c_str(),
  8761. server_cert_pem.size(),
  8762. server_key_pem.c_str(),
  8763. server_key_pem.size(),
  8764. client_ca_pem.c_str(),
  8765. client_ca_pem.size(),
  8766. nullptr // no password for server key
  8767. };
  8768. SSLServer svr(server_pem);
  8769. ASSERT_TRUE(svr.is_valid());
  8770. svr.Get("/test", [&](const Request &, Response &res) {
  8771. res.set_content("test", "text/plain");
  8772. });
  8773. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8774. auto se = detail::scope_exit([&] {
  8775. svr.stop();
  8776. t.join();
  8777. ASSERT_FALSE(svr.is_running());
  8778. });
  8779. svr.wait_until_ready();
  8780. // Create client with PEM memory
  8781. const char *password = client_encrypted_private_key_pass.empty()
  8782. ? nullptr
  8783. : client_encrypted_private_key_pass.c_str();
  8784. SSLClient::PemMemory client_pem = {
  8785. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8786. client_key_pem.size(), password};
  8787. SSLClient cli(HOST, PORT, client_pem);
  8788. cli.enable_server_certificate_verification(false);
  8789. cli.set_connection_timeout(30);
  8790. auto res = cli.Get("/test");
  8791. ASSERT_TRUE(res);
  8792. ASSERT_EQ(StatusCode::OK_200, res->status);
  8793. }
  8794. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8795. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8796. }
  8797. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8798. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8799. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8800. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8801. }
  8802. TEST(SSLClientServerTest, ClientCertMissing) {
  8803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8804. CLIENT_CA_CERT_DIR);
  8805. ASSERT_TRUE(svr.is_valid());
  8806. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8808. auto se = detail::scope_exit([&] {
  8809. svr.stop();
  8810. t.join();
  8811. ASSERT_FALSE(svr.is_running());
  8812. });
  8813. svr.wait_until_ready();
  8814. SSLClient cli(HOST, PORT);
  8815. cli.set_connection_timeout(30);
  8816. auto res = cli.Get("/test");
  8817. ASSERT_TRUE(!res);
  8818. // When client cert is missing and server requires it, connection fails
  8819. // Error type depends on backend implementation
  8820. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8821. res.error() == Error::SSLConnection);
  8822. // Verify backend error is captured
  8823. // Note: This test may have different error codes depending on the exact
  8824. // verification failure
  8825. EXPECT_NE(0UL, res.ssl_backend_error());
  8826. }
  8827. TEST(SSLClientServerTest, TrustDirOptional) {
  8828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8829. ASSERT_TRUE(svr.is_valid());
  8830. svr.Get("/test", [&](const Request &, Response &res) {
  8831. res.set_content("test", "text/plain");
  8832. });
  8833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8834. auto se = detail::scope_exit([&] {
  8835. svr.stop();
  8836. t.join();
  8837. ASSERT_FALSE(svr.is_running());
  8838. });
  8839. svr.wait_until_ready();
  8840. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8841. cli.enable_server_certificate_verification(false);
  8842. cli.set_connection_timeout(30);
  8843. auto res = cli.Get("/test");
  8844. ASSERT_TRUE(res);
  8845. ASSERT_EQ(StatusCode::OK_200, res->status);
  8846. }
  8847. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8848. class NoListenSSLServer : public SSLServer {
  8849. public:
  8850. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8851. const char *client_ca_cert_file_path,
  8852. const char *client_ca_cert_dir_path = nullptr)
  8853. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8854. client_ca_cert_dir_path),
  8855. stop_(false) {}
  8856. std::atomic_bool stop_;
  8857. private:
  8858. bool process_and_close_socket(socket_t /*sock*/) override {
  8859. // Don't create SSL context
  8860. while (!stop_.load()) {
  8861. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8862. }
  8863. return true;
  8864. }
  8865. };
  8866. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8867. CLIENT_CA_CERT_FILE);
  8868. ASSERT_TRUE(svr.is_valid());
  8869. svr.Get("/test", [&](const Request &, Response &res) {
  8870. res.set_content("test", "text/plain");
  8871. });
  8872. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8873. auto se = detail::scope_exit([&] {
  8874. svr.stop_ = true;
  8875. svr.stop();
  8876. t.join();
  8877. ASSERT_FALSE(svr.is_running());
  8878. });
  8879. svr.wait_until_ready();
  8880. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8881. cli.enable_server_certificate_verification(false);
  8882. cli.set_connection_timeout(1);
  8883. auto res = cli.Get("/test");
  8884. ASSERT_TRUE(!res);
  8885. EXPECT_EQ(Error::SSLConnection, res.error());
  8886. // Timeout results in WantRead error code (maps to backend-specific value)
  8887. EXPECT_NE(0, res.ssl_error());
  8888. }
  8889. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8890. // Test SSLServer with client certificate verification using the standard
  8891. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8893. CLIENT_CA_CERT_DIR);
  8894. ASSERT_TRUE(svr.is_valid());
  8895. svr.Get("/test", [&](const Request &req, Response &res) {
  8896. res.set_content("test", "text/plain");
  8897. auto cert = req.peer_cert();
  8898. ASSERT_TRUE(static_cast<bool>(cert));
  8899. auto common_name = cert.subject_cn();
  8900. EXPECT_EQ("Common Name", common_name);
  8901. });
  8902. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. t.join();
  8906. ASSERT_FALSE(svr.is_running());
  8907. });
  8908. svr.wait_until_ready();
  8909. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8910. cli.enable_server_certificate_verification(false);
  8911. cli.set_connection_timeout(30);
  8912. auto res = cli.Get("/test");
  8913. ASSERT_TRUE(res);
  8914. ASSERT_EQ(StatusCode::OK_200, res->status);
  8915. }
  8916. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8917. // Verifies that wildcard matching and exact matching work consistently
  8918. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8919. using namespace httplib::tls;
  8920. // We need a running server to test against
  8921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8922. ASSERT_TRUE(svr.is_valid());
  8923. svr.Get("/test", [](const Request &, Response &res) {
  8924. res.set_content("ok", "text/plain");
  8925. });
  8926. thread t([&]() { svr.listen(HOST, PORT); });
  8927. auto se = detail::scope_exit([&] {
  8928. svr.stop();
  8929. t.join();
  8930. });
  8931. svr.wait_until_ready();
  8932. bool verify_callback_called = false;
  8933. bool verify_result_wrong = false;
  8934. SSLClient cli(HOST, PORT);
  8935. cli.enable_server_certificate_verification(true);
  8936. cli.set_ca_cert_path(CA_CERT_FILE);
  8937. cli.set_connection_timeout(5);
  8938. // Note: Test certificate has CN="Common Name", not "localhost"
  8939. bool verify_result_cn = false;
  8940. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8941. verify_callback_called = true;
  8942. if (!ctx.cert) return false;
  8943. // Test 1: "Common Name" should match (our test server cert CN)
  8944. verify_result_cn = ctx.check_hostname("Common Name");
  8945. // Test 2: wrong hostname should not match
  8946. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8947. return true; // Accept for the purpose of this test
  8948. });
  8949. auto res = cli.Get("/test");
  8950. // The request may succeed or fail depending on cert configuration
  8951. // but the callback should have been called
  8952. ASSERT_TRUE(verify_callback_called)
  8953. << "Verify callback should have been called";
  8954. // CN="Common Name" should match our test certificate
  8955. EXPECT_TRUE(verify_result_cn)
  8956. << "verify_hostname should match 'Common Name' (certificate CN)";
  8957. // Wrong hostname should not match
  8958. EXPECT_FALSE(verify_result_wrong)
  8959. << "verify_hostname should not match 'wronghost.example.com'";
  8960. }
  8961. #endif
  8962. // mbedTLS-specific callback constructor test
  8963. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8964. #ifdef CPPHTTPLIB_SSL_ENABLED
  8965. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8967. ASSERT_TRUE(svr.is_valid());
  8968. // Set up a handler to verify client certificate is present
  8969. bool client_cert_verified = false;
  8970. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8971. // Verify that client certificate was provided
  8972. client_cert_verified = true;
  8973. res.set_content("success", "text/plain");
  8974. });
  8975. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8976. auto se = detail::scope_exit([&] {
  8977. svr.stop();
  8978. t.join();
  8979. ASSERT_FALSE(svr.is_running());
  8980. });
  8981. svr.wait_until_ready();
  8982. // Client with certificate
  8983. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8984. cli.enable_server_certificate_verification(false);
  8985. cli.set_connection_timeout(30);
  8986. auto res = cli.Get("/test");
  8987. ASSERT_TRUE(res);
  8988. ASSERT_EQ(StatusCode::OK_200, res->status);
  8989. ASSERT_TRUE(client_cert_verified);
  8990. EXPECT_EQ("success", res->body);
  8991. }
  8992. #endif
  8993. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8994. // backends
  8995. #ifdef CPPHTTPLIB_SSL_ENABLED
  8996. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8997. using namespace httplib::tls;
  8998. // Test that when client CA cert file is provided,
  8999. // the server properly requests and validates client certificates
  9000. // Create a server with client authentication
  9001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9002. ASSERT_TRUE(svr.is_valid());
  9003. bool handler_called = false;
  9004. svr.Get("/test", [&](const Request &req, Response &res) {
  9005. handler_called = true;
  9006. // Verify that a client certificate was provided
  9007. auto cert = req.peer_cert();
  9008. ASSERT_TRUE(static_cast<bool>(cert));
  9009. // Get the issuer name
  9010. std::string issuer_str = cert.issuer_name();
  9011. ASSERT_FALSE(issuer_str.empty());
  9012. // The client certificate should be issued by our test CA
  9013. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9014. res.set_content("authenticated", "text/plain");
  9015. });
  9016. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9017. auto se = detail::scope_exit([&] {
  9018. svr.stop();
  9019. t.join();
  9020. ASSERT_FALSE(svr.is_running());
  9021. });
  9022. svr.wait_until_ready();
  9023. // Connect with a client certificate issued by the CA
  9024. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9025. cli.enable_server_certificate_verification(false);
  9026. cli.set_connection_timeout(30);
  9027. auto res = cli.Get("/test");
  9028. ASSERT_TRUE(res);
  9029. ASSERT_EQ(StatusCode::OK_200, res->status);
  9030. ASSERT_TRUE(handler_called);
  9031. EXPECT_EQ("authenticated", res->body);
  9032. }
  9033. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9034. using namespace httplib::tls;
  9035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9036. ASSERT_TRUE(svr.is_valid());
  9037. svr.Get("/test", [](const Request &, Response &res) {
  9038. res.set_content("ok", "text/plain");
  9039. });
  9040. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9041. auto se = detail::scope_exit([&] {
  9042. svr.stop();
  9043. t.join();
  9044. });
  9045. svr.wait_until_ready();
  9046. SSLClient cli(HOST, PORT);
  9047. cli.enable_server_certificate_verification(false);
  9048. cli.set_connection_timeout(30);
  9049. bool cert_checked = false;
  9050. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9051. if (ctx.cert) {
  9052. auto sans = ctx.sans();
  9053. // Test certificate may or may not have SANs - just verify the API
  9054. // works If SANs exist, verify the types are valid
  9055. for (const auto &san : sans) {
  9056. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9057. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9058. san.type == SanType::OTHER);
  9059. EXPECT_FALSE(san.value.empty());
  9060. }
  9061. cert_checked = true;
  9062. }
  9063. return true;
  9064. });
  9065. auto res = cli.Get("/test");
  9066. ASSERT_TRUE(res);
  9067. EXPECT_TRUE(cert_checked);
  9068. }
  9069. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9070. using namespace httplib::tls;
  9071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9072. ASSERT_TRUE(svr.is_valid());
  9073. svr.Get("/test", [](const Request &, Response &res) {
  9074. res.set_content("ok", "text/plain");
  9075. });
  9076. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9077. auto se = detail::scope_exit([&] {
  9078. svr.stop();
  9079. t.join();
  9080. });
  9081. svr.wait_until_ready();
  9082. SSLClient cli(HOST, PORT);
  9083. cli.enable_server_certificate_verification(false);
  9084. cli.set_connection_timeout(30);
  9085. bool validity_checked = false;
  9086. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9087. if (ctx.cert) {
  9088. time_t not_before = 0, not_after = 0;
  9089. bool result = ctx.validity(not_before, not_after);
  9090. EXPECT_TRUE(result);
  9091. // Verify that not_before < now < not_after for a valid cert
  9092. time_t now = time(nullptr);
  9093. EXPECT_LT(not_before, now);
  9094. EXPECT_GT(not_after, now);
  9095. validity_checked = true;
  9096. }
  9097. return true;
  9098. });
  9099. auto res = cli.Get("/test");
  9100. ASSERT_TRUE(res);
  9101. EXPECT_TRUE(validity_checked);
  9102. }
  9103. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9104. using namespace httplib::tls;
  9105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9106. ASSERT_TRUE(svr.is_valid());
  9107. svr.Get("/test", [](const Request &, Response &res) {
  9108. res.set_content("ok", "text/plain");
  9109. });
  9110. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9111. auto se = detail::scope_exit([&] {
  9112. svr.stop();
  9113. t.join();
  9114. });
  9115. svr.wait_until_ready();
  9116. SSLClient cli(HOST, PORT);
  9117. cli.enable_server_certificate_verification(false);
  9118. cli.set_connection_timeout(30);
  9119. bool serial_checked = false;
  9120. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9121. if (ctx.cert) {
  9122. std::string serial = ctx.serial();
  9123. EXPECT_FALSE(serial.empty());
  9124. // Serial should be a hex string
  9125. for (char c : serial) {
  9126. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9127. (c >= 'a' && c <= 'f'));
  9128. }
  9129. serial_checked = true;
  9130. }
  9131. return true;
  9132. });
  9133. auto res = cli.Get("/test");
  9134. ASSERT_TRUE(res);
  9135. EXPECT_TRUE(serial_checked);
  9136. }
  9137. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9138. // Test 1: Valid CA file - no error should be recorded
  9139. {
  9140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9141. CLIENT_CA_CERT_FILE);
  9142. ASSERT_TRUE(svr.is_valid());
  9143. // With valid setup, last_ssl_error should be 0
  9144. EXPECT_EQ(0, svr.ssl_last_error());
  9145. }
  9146. // Test 2: Invalid CA file content
  9147. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9148. {
  9149. // Create a temporary file with completely invalid content
  9150. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9151. {
  9152. std::ofstream ofs(temp_invalid_ca);
  9153. ofs << "This is not a certificate file at all\n";
  9154. ofs << "Just plain text content\n";
  9155. }
  9156. // Create server with invalid CA file
  9157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9158. // Clean up temporary file
  9159. std::remove(temp_invalid_ca);
  9160. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9161. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9162. // Note: SSL_CTX_load_verify_locations typically fails first,
  9163. // but our error handling code path is still exercised
  9164. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9165. }
  9166. }
  9167. TEST(VerifyCallbackTest, VerifyContextFields) {
  9168. using namespace httplib::tls;
  9169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9170. ASSERT_TRUE(svr.is_valid());
  9171. svr.Get("/test", [](const Request &, Response &res) {
  9172. res.set_content("ok", "text/plain");
  9173. });
  9174. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9175. auto se = detail::scope_exit([&] {
  9176. svr.stop();
  9177. t.join();
  9178. });
  9179. svr.wait_until_ready();
  9180. SSLClient cli(HOST, PORT);
  9181. cli.enable_server_certificate_verification(false);
  9182. cli.set_connection_timeout(30);
  9183. int callback_count = 0;
  9184. bool saw_leaf_cert = false;
  9185. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9186. if (ctx.cert) {
  9187. callback_count++;
  9188. // We should see at least one certificate (the leaf)
  9189. std::string cn = ctx.subject_cn();
  9190. if (!cn.empty()) { saw_leaf_cert = true; }
  9191. // Verify context fields are populated
  9192. EXPECT_NE(ctx.session, nullptr);
  9193. EXPECT_GE(ctx.depth, 0);
  9194. }
  9195. return true;
  9196. });
  9197. auto res = cli.Get("/test");
  9198. ASSERT_TRUE(res);
  9199. EXPECT_GT(callback_count, 0);
  9200. EXPECT_TRUE(saw_leaf_cert);
  9201. }
  9202. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9203. using httplib::tls::TlsError;
  9204. // Test that verify_error_to_string returns empty for success
  9205. std::string success_str = TlsError::verify_error_to_string(0);
  9206. EXPECT_TRUE(success_str.empty());
  9207. // Test that verify_error_to_string returns non-empty for error codes
  9208. // Using a common error code (certificate expired)
  9209. std::string error_str =
  9210. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9211. EXPECT_FALSE(error_str.empty());
  9212. }
  9213. TEST(SessionVerifierTest, CertificateAccepted) {
  9214. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9215. ASSERT_TRUE(svr.is_valid());
  9216. svr.Get("/test", [](const Request &, Response &res) {
  9217. res.set_content("ok", "text/plain");
  9218. });
  9219. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9220. auto se = detail::scope_exit([&] {
  9221. svr.stop();
  9222. t.join();
  9223. });
  9224. svr.wait_until_ready();
  9225. SSLClient cli(HOST, PORT);
  9226. cli.enable_server_certificate_verification(false);
  9227. cli.set_connection_timeout(30);
  9228. bool callback_called = false;
  9229. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9230. EXPECT_NE(session, nullptr);
  9231. callback_called = true;
  9232. return SSLVerifierResponse::CertificateAccepted;
  9233. });
  9234. auto res = cli.Get("/test");
  9235. ASSERT_TRUE(res);
  9236. EXPECT_EQ(200, res->status);
  9237. EXPECT_TRUE(callback_called);
  9238. }
  9239. TEST(SessionVerifierTest, CertificateRejected) {
  9240. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9241. ASSERT_TRUE(svr.is_valid());
  9242. svr.Get("/test", [](const Request &, Response &res) {
  9243. res.set_content("ok", "text/plain");
  9244. });
  9245. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9246. auto se = detail::scope_exit([&] {
  9247. svr.stop();
  9248. t.join();
  9249. });
  9250. svr.wait_until_ready();
  9251. SSLClient cli(HOST, PORT);
  9252. cli.enable_server_certificate_verification(false);
  9253. cli.set_connection_timeout(30);
  9254. bool callback_called = false;
  9255. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9256. EXPECT_NE(session, nullptr);
  9257. callback_called = true;
  9258. return SSLVerifierResponse::CertificateRejected;
  9259. });
  9260. auto res = cli.Get("/test");
  9261. EXPECT_FALSE(res);
  9262. EXPECT_TRUE(callback_called);
  9263. }
  9264. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9265. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9266. ASSERT_TRUE(svr.is_valid());
  9267. svr.Get("/test", [](const Request &, Response &res) {
  9268. res.set_content("ok", "text/plain");
  9269. });
  9270. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9271. auto se = detail::scope_exit([&] {
  9272. svr.stop();
  9273. t.join();
  9274. });
  9275. svr.wait_until_ready();
  9276. // NoDecisionMade with verification disabled should succeed (no default check)
  9277. SSLClient cli(HOST, PORT);
  9278. cli.enable_server_certificate_verification(false);
  9279. cli.set_connection_timeout(30);
  9280. bool callback_called = false;
  9281. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9282. EXPECT_NE(session, nullptr);
  9283. callback_called = true;
  9284. return SSLVerifierResponse::NoDecisionMade;
  9285. });
  9286. auto res = cli.Get("/test");
  9287. ASSERT_TRUE(res);
  9288. EXPECT_EQ(200, res->status);
  9289. EXPECT_TRUE(callback_called);
  9290. }
  9291. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9293. ASSERT_TRUE(svr.is_valid());
  9294. svr.Get("/test", [](const Request &, Response &res) {
  9295. res.set_content("ok", "text/plain");
  9296. });
  9297. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9298. auto se = detail::scope_exit([&] {
  9299. svr.stop();
  9300. t.join();
  9301. });
  9302. svr.wait_until_ready();
  9303. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9304. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9305. // so we only check that the request fails, not whether the callback was
  9306. // called.
  9307. SSLClient cli(HOST, PORT);
  9308. cli.enable_server_certificate_verification(true);
  9309. cli.set_connection_timeout(30);
  9310. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9311. EXPECT_NE(session, nullptr);
  9312. return SSLVerifierResponse::NoDecisionMade;
  9313. });
  9314. auto res = cli.Get("/test");
  9315. EXPECT_FALSE(res);
  9316. }
  9317. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9318. // Test SSL server using PemMemory constructor with client CA certificates
  9319. // Read PEM files
  9320. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9321. read_file(SERVER_CERT_FILE, server_cert_pem);
  9322. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9323. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9324. // Create SSLServer with PemMemory constructor including client CA
  9325. SSLServer::PemMemory server_pem = {
  9326. server_cert_pem.c_str(),
  9327. server_cert_pem.size(),
  9328. server_key_pem.c_str(),
  9329. server_key_pem.size(),
  9330. client_ca_pem.c_str(),
  9331. client_ca_pem.size(),
  9332. nullptr // no password for server key
  9333. };
  9334. SSLServer svr(server_pem);
  9335. ASSERT_TRUE(svr.is_valid());
  9336. // No SSL error should be recorded for valid setup
  9337. EXPECT_EQ(0, svr.ssl_last_error());
  9338. // Set up server endpoints
  9339. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9340. res.set_content("ok", "text/plain");
  9341. });
  9342. // Start server in a thread
  9343. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9344. svr.wait_until_ready();
  9345. // Connect with client certificate (using constructor with paths)
  9346. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9347. cli.enable_server_certificate_verification(false);
  9348. auto res = cli.Get("/test-pem-ca");
  9349. ASSERT_TRUE(res);
  9350. EXPECT_EQ(200, res->status);
  9351. EXPECT_EQ("ok", res->body);
  9352. svr.stop();
  9353. server_thread.join();
  9354. }
  9355. #endif
  9356. #ifdef _WIN32
  9357. TEST(CleanupTest, WSACleanup) {
  9358. int ret = WSACleanup();
  9359. ASSERT_EQ(0, ret);
  9360. }
  9361. #endif
  9362. #ifndef CPPHTTPLIB_SSL_ENABLED
  9363. TEST(NoSSLSupport, SimpleInterface) {
  9364. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9365. }
  9366. #endif
  9367. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9368. TEST(InvalidScheme, SimpleInterface) {
  9369. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9370. }
  9371. #endif
  9372. TEST(NoScheme, SimpleInterface) {
  9373. Client cli("yahoo.com:80");
  9374. ASSERT_TRUE(cli.is_valid());
  9375. }
  9376. TEST(SendAPI, SimpleInterface_Online) {
  9377. Client cli("http://yahoo.com");
  9378. Request req;
  9379. req.method = "GET";
  9380. req.path = "/";
  9381. auto res = cli.send(req);
  9382. ASSERT_TRUE(res);
  9383. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9384. }
  9385. TEST(SendAPI, WithParamsInRequest) {
  9386. Server svr;
  9387. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9388. EXPECT_TRUE(req.has_param("test"));
  9389. EXPECT_EQ("test_value", req.get_param_value("test"));
  9390. });
  9391. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9392. auto se = detail::scope_exit([&] {
  9393. svr.stop();
  9394. t.join();
  9395. ASSERT_FALSE(svr.is_running());
  9396. });
  9397. svr.wait_until_ready();
  9398. Client cli(HOST, PORT);
  9399. {
  9400. Request req;
  9401. req.method = "GET";
  9402. req.path = "/";
  9403. req.params.emplace("test", "test_value");
  9404. auto res = cli.send(req);
  9405. ASSERT_TRUE(res);
  9406. }
  9407. {
  9408. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9409. ASSERT_TRUE(res);
  9410. }
  9411. }
  9412. TEST(ClientImplMethods, GetSocketTest) {
  9413. httplib::Server svr;
  9414. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9415. res.status = StatusCode::OK_200;
  9416. });
  9417. auto port = svr.bind_to_any_port("127.0.0.1");
  9418. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9419. auto se = detail::scope_exit([&] {
  9420. svr.stop();
  9421. thread.join();
  9422. ASSERT_FALSE(svr.is_running());
  9423. });
  9424. svr.wait_until_ready();
  9425. {
  9426. httplib::Client cli("127.0.0.1", port);
  9427. cli.set_keep_alive(true);
  9428. // Use the behavior of cpp-httplib of opening the connection
  9429. // only when the first request happens. If that changes,
  9430. // this test would be obsolete.
  9431. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9432. // This also implicitly tests the server. But other tests would fail much
  9433. // earlier than this one to be considered.
  9434. auto res = cli.Get("/");
  9435. ASSERT_TRUE(res);
  9436. EXPECT_EQ(StatusCode::OK_200, res->status);
  9437. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9438. }
  9439. }
  9440. #ifdef CPPHTTPLIB_SSL_ENABLED
  9441. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9442. Client cli("http://yahoo.com");
  9443. auto res = cli.Get("/");
  9444. ASSERT_TRUE(res);
  9445. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9446. cli.set_follow_location(true);
  9447. res = cli.Get("/");
  9448. ASSERT_TRUE(res);
  9449. EXPECT_EQ(StatusCode::OK_200, res->status);
  9450. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9451. }
  9452. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9453. Client cli("https://yahoo.com");
  9454. auto res = cli.Get("/");
  9455. ASSERT_TRUE(res);
  9456. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9457. cli.set_follow_location(true);
  9458. res = cli.Get("/");
  9459. ASSERT_TRUE(res);
  9460. EXPECT_EQ(StatusCode::OK_200, res->status);
  9461. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9462. }
  9463. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9464. Client cli("https://yahoo.com");
  9465. auto res = cli.Get("/");
  9466. ASSERT_TRUE(res);
  9467. ASSERT_FALSE(!res);
  9468. ASSERT_TRUE(res);
  9469. ASSERT_FALSE(res == nullptr);
  9470. ASSERT_TRUE(res != nullptr);
  9471. EXPECT_EQ(Error::Success, res.error());
  9472. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9473. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9474. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9475. cli.set_follow_location(true);
  9476. res = cli.Get("/");
  9477. ASSERT_TRUE(res);
  9478. EXPECT_EQ(Error::Success, res.error());
  9479. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9480. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9481. EXPECT_EQ(StatusCode::OK_200, res->status);
  9482. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9483. }
  9484. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9485. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9486. Client cli("https://cdnjs.cloudflare.com");
  9487. auto res =
  9488. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9489. ASSERT_TRUE(res);
  9490. EXPECT_EQ(StatusCode::OK_200, res->status);
  9491. EXPECT_EQ(287630U, res->body.size());
  9492. EXPECT_EQ("application/javascript; charset=utf-8",
  9493. res->get_header_value("Content-Type"));
  9494. }
  9495. #endif
  9496. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9497. #undef REDIR_HOST // Silence compiler warning
  9498. #define REDIR_HOST "https://httpbingo.org"
  9499. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9500. Client cli(REDIR_HOST);
  9501. cli.set_follow_location(true);
  9502. auto res =
  9503. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9504. ASSERT_TRUE(res);
  9505. EXPECT_EQ(StatusCode::OK_200, res->status);
  9506. }
  9507. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9508. Client cli(REDIR_HOST);
  9509. cli.set_follow_location(true);
  9510. Params params;
  9511. params.emplace("url", "http://example.com");
  9512. params.emplace("status_code", "302");
  9513. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9514. ASSERT_TRUE(res);
  9515. EXPECT_EQ(StatusCode::OK_200, res->status);
  9516. }
  9517. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9518. Client cli(REDIR_HOST);
  9519. cli.set_follow_location(true);
  9520. Params params;
  9521. params.emplace("url", "http://example.com");
  9522. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9523. ASSERT_TRUE(res);
  9524. EXPECT_EQ(StatusCode::OK_200, res->status);
  9525. }
  9526. TEST(HttpToHttpsRedirectTest, CertFile) {
  9527. auto ssl_port = PORT + 1;
  9528. Server svr;
  9529. ASSERT_TRUE(svr.is_valid());
  9530. svr.Get("/index", [&](const Request &, Response &res) {
  9531. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9532. "/index");
  9533. svr.stop();
  9534. });
  9535. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9536. ASSERT_TRUE(ssl_svr.is_valid());
  9537. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9538. res.set_content("test", "text/plain");
  9539. ssl_svr.stop();
  9540. });
  9541. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9542. thread t2 =
  9543. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9544. auto se = detail::scope_exit([&] {
  9545. t2.join();
  9546. t.join();
  9547. ASSERT_FALSE(svr.is_running());
  9548. });
  9549. svr.wait_until_ready();
  9550. ssl_svr.wait_until_ready();
  9551. Client cli("127.0.0.1", PORT);
  9552. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9553. cli.enable_server_certificate_verification(true);
  9554. cli.set_follow_location(true);
  9555. cli.set_connection_timeout(30);
  9556. auto res = cli.Get("/index");
  9557. ASSERT_TRUE(res);
  9558. ASSERT_EQ(StatusCode::OK_200, res->status);
  9559. }
  9560. TEST(SSLClientRedirectTest, CertFile) {
  9561. auto ssl_port = PORT + 1;
  9562. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9563. ASSERT_TRUE(ssl_svr1.is_valid());
  9564. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9565. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9566. "/index");
  9567. ssl_svr1.stop();
  9568. });
  9569. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9570. ASSERT_TRUE(ssl_svr2.is_valid());
  9571. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9572. res.set_content("test", "text/plain");
  9573. ssl_svr2.stop();
  9574. });
  9575. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9576. thread t2 =
  9577. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9578. auto se = detail::scope_exit([&] {
  9579. t2.join();
  9580. t.join();
  9581. ASSERT_FALSE(ssl_svr1.is_running());
  9582. });
  9583. ssl_svr1.wait_until_ready();
  9584. ssl_svr2.wait_until_ready();
  9585. SSLClient cli("127.0.0.1", PORT);
  9586. std::string cert;
  9587. read_file(SERVER_CERT2_FILE, cert);
  9588. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9589. cli.enable_server_certificate_verification(true);
  9590. cli.set_follow_location(true);
  9591. cli.set_connection_timeout(30);
  9592. auto res = cli.Get("/index");
  9593. ASSERT_TRUE(res);
  9594. ASSERT_EQ(StatusCode::OK_200, res->status);
  9595. }
  9596. #endif
  9597. #ifdef CPPHTTPLIB_SSL_ENABLED
  9598. // Test that set_ca_cert_store() skips system certs (consistent with
  9599. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9600. // should be trusted - system certs should NOT be loaded.
  9601. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9602. // Load a specific cert that is NOT a system CA cert
  9603. std::string cert;
  9604. read_file(SERVER_CERT2_FILE, cert);
  9605. SSLClient cli("google.com");
  9606. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9607. cli.enable_server_certificate_verification(true);
  9608. // This should FAIL because:
  9609. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9610. // 2. System certs should NOT be loaded when custom store is set
  9611. // If system certs WERE loaded, this would succeed
  9612. auto res = cli.Get("/");
  9613. ASSERT_FALSE(res);
  9614. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9615. }
  9616. TEST(MultipartFormDataTest, LargeData) {
  9617. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9618. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9619. const ContentReader &content_reader) {
  9620. if (req.is_multipart_form_data()) {
  9621. std::vector<FormData> items;
  9622. content_reader(
  9623. [&](const FormData &file) {
  9624. items.push_back(file);
  9625. return true;
  9626. },
  9627. [&](const char *data, size_t data_length) {
  9628. items.back().content.append(data, data_length);
  9629. return true;
  9630. });
  9631. EXPECT_TRUE(std::string(items[0].name) == "document");
  9632. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9633. EXPECT_TRUE(items[0].filename == "2MB_data");
  9634. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9635. EXPECT_TRUE(items[1].name == "hello");
  9636. EXPECT_TRUE(items[1].content == "world");
  9637. EXPECT_TRUE(items[1].filename == "");
  9638. EXPECT_TRUE(items[1].content_type == "");
  9639. } else {
  9640. std::string body;
  9641. content_reader([&](const char *data, size_t data_length) {
  9642. body.append(data, data_length);
  9643. return true;
  9644. });
  9645. }
  9646. });
  9647. auto port = svr.bind_to_any_port(HOST);
  9648. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9649. auto se = detail::scope_exit([&] {
  9650. svr.stop();
  9651. t.join();
  9652. ASSERT_FALSE(svr.is_running());
  9653. });
  9654. svr.wait_until_ready();
  9655. {
  9656. std::string data(1024 * 1024 * 2, '.');
  9657. std::stringstream buffer;
  9658. buffer << data;
  9659. SSLClient cli(HOST, port);
  9660. cli.enable_server_certificate_verification(false);
  9661. UploadFormDataItems items{
  9662. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9663. {"hello", "world", "", ""},
  9664. };
  9665. auto res = cli.Post("/post", items);
  9666. ASSERT_TRUE(res);
  9667. ASSERT_EQ(StatusCode::OK_200, res->status);
  9668. }
  9669. }
  9670. TEST(MultipartFormDataTest, DataProviderItems) {
  9671. std::random_device seed_gen;
  9672. std::mt19937 random(seed_gen());
  9673. std::string rand1;
  9674. rand1.resize(1000);
  9675. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9676. std::string rand2;
  9677. rand2.resize(3000);
  9678. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9680. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9681. const ContentReader &content_reader) {
  9682. ASSERT_FALSE(req.is_multipart_form_data());
  9683. std::string body;
  9684. content_reader([&](const char *data, size_t data_length) {
  9685. body.append(data, data_length);
  9686. return true;
  9687. });
  9688. EXPECT_EQ(body, "");
  9689. });
  9690. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9691. const ContentReader &content_reader) {
  9692. ASSERT_TRUE(req.is_multipart_form_data());
  9693. std::vector<FormData> items;
  9694. content_reader(
  9695. [&](const FormData &file) {
  9696. items.push_back(file);
  9697. return true;
  9698. },
  9699. [&](const char *data, size_t data_length) {
  9700. items.back().content.append(data, data_length);
  9701. return true;
  9702. });
  9703. ASSERT_TRUE(items.size() == 2);
  9704. EXPECT_EQ(std::string(items[0].name), "name1");
  9705. EXPECT_EQ(items[0].content, "Testing123");
  9706. EXPECT_EQ(items[0].filename, "filename1");
  9707. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9708. EXPECT_EQ(items[1].name, "name2");
  9709. EXPECT_EQ(items[1].content, "Testing456");
  9710. EXPECT_EQ(items[1].filename, "");
  9711. EXPECT_EQ(items[1].content_type, "");
  9712. });
  9713. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9714. const ContentReader &content_reader) {
  9715. ASSERT_TRUE(req.is_multipart_form_data());
  9716. std::vector<FormData> items;
  9717. content_reader(
  9718. [&](const FormData &file) {
  9719. items.push_back(file);
  9720. return true;
  9721. },
  9722. [&](const char *data, size_t data_length) {
  9723. items.back().content.append(data, data_length);
  9724. return true;
  9725. });
  9726. ASSERT_TRUE(items.size() == 2);
  9727. EXPECT_EQ(items[0].name, "name3");
  9728. EXPECT_EQ(items[0].content, rand1);
  9729. EXPECT_EQ(items[0].filename, "filename3");
  9730. EXPECT_EQ(items[0].content_type, "");
  9731. EXPECT_EQ(items[1].name, "name4");
  9732. EXPECT_EQ(items[1].content, rand2);
  9733. EXPECT_EQ(items[1].filename, "filename4");
  9734. EXPECT_EQ(items[1].content_type, "");
  9735. });
  9736. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9737. const ContentReader &content_reader) {
  9738. ASSERT_TRUE(req.is_multipart_form_data());
  9739. std::vector<FormData> items;
  9740. content_reader(
  9741. [&](const FormData &file) {
  9742. items.push_back(file);
  9743. return true;
  9744. },
  9745. [&](const char *data, size_t data_length) {
  9746. items.back().content.append(data, data_length);
  9747. return true;
  9748. });
  9749. ASSERT_TRUE(items.size() == 4);
  9750. EXPECT_EQ(std::string(items[0].name), "name1");
  9751. EXPECT_EQ(items[0].content, "Testing123");
  9752. EXPECT_EQ(items[0].filename, "filename1");
  9753. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9754. EXPECT_EQ(items[1].name, "name2");
  9755. EXPECT_EQ(items[1].content, "Testing456");
  9756. EXPECT_EQ(items[1].filename, "");
  9757. EXPECT_EQ(items[1].content_type, "");
  9758. EXPECT_EQ(items[2].name, "name3");
  9759. EXPECT_EQ(items[2].content, rand1);
  9760. EXPECT_EQ(items[2].filename, "filename3");
  9761. EXPECT_EQ(items[2].content_type, "");
  9762. EXPECT_EQ(items[3].name, "name4");
  9763. EXPECT_EQ(items[3].content, rand2);
  9764. EXPECT_EQ(items[3].filename, "filename4");
  9765. EXPECT_EQ(items[3].content_type, "");
  9766. });
  9767. auto port = svr.bind_to_any_port("localhost");
  9768. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9769. auto se = detail::scope_exit([&] {
  9770. svr.stop();
  9771. t.join();
  9772. ASSERT_FALSE(svr.is_running());
  9773. });
  9774. svr.wait_until_ready();
  9775. {
  9776. SSLClient cli("localhost", port);
  9777. cli.enable_server_certificate_verification(false);
  9778. UploadFormDataItems items{
  9779. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9780. {"name2", "Testing456", "", ""}, // not a file
  9781. };
  9782. {
  9783. auto res = cli.Post("/post-none", {}, {}, {});
  9784. ASSERT_TRUE(res);
  9785. ASSERT_EQ(StatusCode::OK_200, res->status);
  9786. }
  9787. FormDataProviderItems providers;
  9788. {
  9789. auto res =
  9790. cli.Post("/post-items", {}, items, providers); // empty providers
  9791. ASSERT_TRUE(res);
  9792. ASSERT_EQ(StatusCode::OK_200, res->status);
  9793. }
  9794. providers.push_back({"name3",
  9795. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9796. // test the offset is given correctly at each step
  9797. if (!offset)
  9798. sink.os.write(rand1.data(), 30);
  9799. else if (offset == 30)
  9800. sink.os.write(rand1.data() + 30, 300);
  9801. else if (offset == 330)
  9802. sink.os.write(rand1.data() + 330, 670);
  9803. else if (offset == rand1.size())
  9804. sink.done();
  9805. return true;
  9806. },
  9807. "filename3",
  9808. {}});
  9809. providers.push_back({"name4",
  9810. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9811. // test the offset is given correctly at each step
  9812. if (!offset)
  9813. sink.os.write(rand2.data(), 2000);
  9814. else if (offset == 2000)
  9815. sink.os.write(rand2.data() + 2000, 1);
  9816. else if (offset == 2001)
  9817. sink.os.write(rand2.data() + 2001, 999);
  9818. else if (offset == rand2.size())
  9819. sink.done();
  9820. return true;
  9821. },
  9822. "filename4",
  9823. {}});
  9824. {
  9825. auto res = cli.Post("/post-providers", {}, {}, providers);
  9826. ASSERT_TRUE(res);
  9827. ASSERT_EQ(StatusCode::OK_200, res->status);
  9828. }
  9829. {
  9830. auto res = cli.Post("/post-both", {}, items, providers);
  9831. ASSERT_TRUE(res);
  9832. ASSERT_EQ(StatusCode::OK_200, res->status);
  9833. }
  9834. }
  9835. }
  9836. TEST(MultipartFormDataTest, BadHeader) {
  9837. Server svr;
  9838. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9839. res.set_content("ok", "text/plain");
  9840. });
  9841. thread t = thread([&] { svr.listen(HOST, PORT); });
  9842. auto se = detail::scope_exit([&] {
  9843. svr.stop();
  9844. t.join();
  9845. ASSERT_FALSE(svr.is_running());
  9846. });
  9847. svr.wait_until_ready();
  9848. const std::string body =
  9849. "This is the preamble. It is to be ignored, though it\r\n"
  9850. "is a handy place for composition agents to include an\r\n"
  9851. "explanatory note to non-MIME conformant readers.\r\n"
  9852. "\r\n"
  9853. "\r\n"
  9854. "--simple boundary\r\n"
  9855. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9856. ": BAD...\r\n"
  9857. "\r\n"
  9858. "value1\r\n"
  9859. "--simple boundary\r\n"
  9860. "Content-Disposition: form-data; name=\"field2\"; "
  9861. "filename=\"example.txt\"\r\n"
  9862. "\r\n"
  9863. "value2\r\n"
  9864. "--simple boundary--\r\n"
  9865. "This is the epilogue. It is also to be ignored.\r\n";
  9866. std::string content_type =
  9867. R"(multipart/form-data; boundary="simple boundary")";
  9868. Client cli(HOST, PORT);
  9869. auto res = cli.Post("/post", body, content_type.c_str());
  9870. ASSERT_TRUE(res);
  9871. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9872. }
  9873. TEST(MultipartFormDataTest, WithPreamble) {
  9874. Server svr;
  9875. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9876. res.set_content("ok", "text/plain");
  9877. });
  9878. thread t = thread([&] { svr.listen(HOST, PORT); });
  9879. auto se = detail::scope_exit([&] {
  9880. svr.stop();
  9881. t.join();
  9882. ASSERT_FALSE(svr.is_running());
  9883. });
  9884. svr.wait_until_ready();
  9885. const std::string body =
  9886. "This is the preamble. It is to be ignored, though it\r\n"
  9887. "is a handy place for composition agents to include an\r\n"
  9888. "explanatory note to non-MIME conformant readers.\r\n"
  9889. "\r\n"
  9890. "\r\n"
  9891. "--simple boundary\r\n"
  9892. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9893. "\r\n"
  9894. "value1\r\n"
  9895. "--simple boundary\r\n"
  9896. "Content-Disposition: form-data; name=\"field2\"; "
  9897. "filename=\"example.txt\"\r\n"
  9898. "\r\n"
  9899. "value2\r\n"
  9900. "--simple boundary--\r\n"
  9901. "This is the epilogue. It is also to be ignored.\r\n";
  9902. std::string content_type =
  9903. R"(multipart/form-data; boundary="simple boundary")";
  9904. Client cli(HOST, PORT);
  9905. auto res = cli.Post("/post", body, content_type.c_str());
  9906. ASSERT_TRUE(res);
  9907. EXPECT_EQ(StatusCode::OK_200, res->status);
  9908. }
  9909. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9911. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9912. const ContentReader &content_reader) {
  9913. if (req.is_multipart_form_data()) {
  9914. std::vector<FormData> items;
  9915. content_reader(
  9916. [&](const FormData &file) {
  9917. items.push_back(file);
  9918. return true;
  9919. },
  9920. [&](const char *data, size_t data_length) {
  9921. items.back().content.append(data, data_length);
  9922. return true;
  9923. });
  9924. EXPECT_TRUE(std::string(items[0].name) == "document");
  9925. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9926. EXPECT_TRUE(items[0].filename == "2MB_data");
  9927. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9928. EXPECT_TRUE(items[1].name == "hello");
  9929. EXPECT_TRUE(items[1].content == "world");
  9930. EXPECT_TRUE(items[1].filename == "");
  9931. EXPECT_TRUE(items[1].content_type == "");
  9932. } else {
  9933. std::string body;
  9934. content_reader([&](const char *data, size_t data_length) {
  9935. body.append(data, data_length);
  9936. return true;
  9937. });
  9938. }
  9939. });
  9940. auto port = svr.bind_to_any_port("localhost");
  9941. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. t.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. {
  9949. std::string data(1024 * 1024 * 2, '.');
  9950. std::stringstream buffer;
  9951. buffer << data;
  9952. SSLClient cli("localhost", port);
  9953. cli.enable_server_certificate_verification(false);
  9954. UploadFormDataItems items{
  9955. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9956. {"hello", "world", "", ""},
  9957. };
  9958. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9959. ASSERT_TRUE(res);
  9960. ASSERT_EQ(StatusCode::OK_200, res->status);
  9961. }
  9962. }
  9963. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9964. std::string data(1024 * 1024 * 2, '&');
  9965. std::stringstream buffer;
  9966. buffer << data;
  9967. Client cli("https://localhost:8080");
  9968. UploadFormDataItems items{
  9969. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9970. {"hello", "world", "", ""},
  9971. };
  9972. for (const char &c : " \t\r\n") {
  9973. auto res =
  9974. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9975. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9976. ASSERT_FALSE(res);
  9977. }
  9978. }
  9979. TEST(MultipartFormDataTest, PutFormData) {
  9980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9981. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9982. const ContentReader &content_reader) {
  9983. if (req.is_multipart_form_data()) {
  9984. std::vector<FormData> items;
  9985. content_reader(
  9986. [&](const FormData &file) {
  9987. items.push_back(file);
  9988. return true;
  9989. },
  9990. [&](const char *data, size_t data_length) {
  9991. items.back().content.append(data, data_length);
  9992. return true;
  9993. });
  9994. EXPECT_TRUE(std::string(items[0].name) == "document");
  9995. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9996. EXPECT_TRUE(items[0].filename == "2MB_data");
  9997. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9998. EXPECT_TRUE(items[1].name == "hello");
  9999. EXPECT_TRUE(items[1].content == "world");
  10000. EXPECT_TRUE(items[1].filename == "");
  10001. EXPECT_TRUE(items[1].content_type == "");
  10002. } else {
  10003. std::string body;
  10004. content_reader([&](const char *data, size_t data_length) {
  10005. body.append(data, data_length);
  10006. return true;
  10007. });
  10008. }
  10009. });
  10010. auto port = svr.bind_to_any_port("localhost");
  10011. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10012. auto se = detail::scope_exit([&] {
  10013. svr.stop();
  10014. t.join();
  10015. ASSERT_FALSE(svr.is_running());
  10016. });
  10017. svr.wait_until_ready();
  10018. {
  10019. std::string data(1024 * 1024 * 2, '&');
  10020. std::stringstream buffer;
  10021. buffer << data;
  10022. SSLClient cli("localhost", port);
  10023. cli.enable_server_certificate_verification(false);
  10024. UploadFormDataItems items{
  10025. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10026. {"hello", "world", "", ""},
  10027. };
  10028. auto res = cli.Put("/put", items);
  10029. ASSERT_TRUE(res);
  10030. ASSERT_EQ(StatusCode::OK_200, res->status);
  10031. }
  10032. }
  10033. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10035. svr.Put("/put_customboundary",
  10036. [&](const Request &req, const Response & /*res*/,
  10037. const ContentReader &content_reader) {
  10038. if (req.is_multipart_form_data()) {
  10039. std::vector<FormData> items;
  10040. content_reader(
  10041. [&](const FormData &file) {
  10042. items.push_back(file);
  10043. return true;
  10044. },
  10045. [&](const char *data, size_t data_length) {
  10046. items.back().content.append(data, data_length);
  10047. return true;
  10048. });
  10049. EXPECT_TRUE(std::string(items[0].name) == "document");
  10050. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10051. EXPECT_TRUE(items[0].filename == "2MB_data");
  10052. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10053. EXPECT_TRUE(items[1].name == "hello");
  10054. EXPECT_TRUE(items[1].content == "world");
  10055. EXPECT_TRUE(items[1].filename == "");
  10056. EXPECT_TRUE(items[1].content_type == "");
  10057. } else {
  10058. std::string body;
  10059. content_reader([&](const char *data, size_t data_length) {
  10060. body.append(data, data_length);
  10061. return true;
  10062. });
  10063. }
  10064. });
  10065. auto port = svr.bind_to_any_port("localhost");
  10066. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10067. auto se = detail::scope_exit([&] {
  10068. svr.stop();
  10069. t.join();
  10070. ASSERT_FALSE(svr.is_running());
  10071. });
  10072. svr.wait_until_ready();
  10073. {
  10074. std::string data(1024 * 1024 * 2, '&');
  10075. std::stringstream buffer;
  10076. buffer << data;
  10077. SSLClient cli("localhost", port);
  10078. cli.enable_server_certificate_verification(false);
  10079. UploadFormDataItems items{
  10080. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10081. {"hello", "world", "", ""},
  10082. };
  10083. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10084. ASSERT_TRUE(res);
  10085. ASSERT_EQ(StatusCode::OK_200, res->status);
  10086. }
  10087. }
  10088. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10089. std::string data(1024 * 1024 * 2, '&');
  10090. std::stringstream buffer;
  10091. buffer << data;
  10092. Client cli("https://localhost:8080");
  10093. cli.enable_server_certificate_verification(false);
  10094. UploadFormDataItems items{
  10095. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10096. {"hello", "world", "", ""},
  10097. };
  10098. for (const char &c : " \t\r\n") {
  10099. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10100. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10101. ASSERT_FALSE(res);
  10102. }
  10103. }
  10104. TEST(MultipartFormDataTest, AlternateFilename) {
  10105. auto handled = false;
  10106. Server svr;
  10107. svr.Post("/test", [&](const Request &req, Response &res) {
  10108. ASSERT_EQ(2u, req.form.files.size());
  10109. ASSERT_EQ(1u, req.form.fields.size());
  10110. // Test files
  10111. const auto &file1 = req.form.get_file("file1");
  10112. ASSERT_EQ("file1", file1.name);
  10113. ASSERT_EQ("A.txt", file1.filename);
  10114. ASSERT_EQ("text/plain", file1.content_type);
  10115. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10116. const auto &file2 = req.form.get_file("file2");
  10117. ASSERT_EQ("file2", file2.name);
  10118. ASSERT_EQ("a.html", file2.filename);
  10119. ASSERT_EQ("text/html", file2.content_type);
  10120. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10121. file2.content);
  10122. // Test text field
  10123. const auto &text = req.form.get_field("text");
  10124. ASSERT_EQ("text default", text);
  10125. res.set_content("ok", "text/plain");
  10126. handled = true;
  10127. });
  10128. thread t = thread([&] { svr.listen(HOST, PORT); });
  10129. auto se = detail::scope_exit([&] {
  10130. svr.stop();
  10131. t.join();
  10132. ASSERT_FALSE(svr.is_running());
  10133. ASSERT_TRUE(handled);
  10134. });
  10135. svr.wait_until_ready();
  10136. auto req = "POST /test HTTP/1.1\r\n"
  10137. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10138. "Content-Length: 399\r\n"
  10139. "\r\n"
  10140. "----------\r\n"
  10141. "Content-Disposition: form-data; name=\"text\"\r\n"
  10142. "\r\n"
  10143. "text default\r\n"
  10144. "----------\r\n"
  10145. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10146. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10147. "Content-Type: text/plain\r\n"
  10148. "\r\n"
  10149. "Content of a.txt.\r\n"
  10150. "\r\n"
  10151. "----------\r\n"
  10152. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10153. "\"a.html\"\r\n"
  10154. "Content-Type: text/html\r\n"
  10155. "\r\n"
  10156. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10157. "\r\n"
  10158. "------------\r\n";
  10159. ASSERT_TRUE(send_request(1, req));
  10160. }
  10161. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10162. auto handled = false;
  10163. Server svr;
  10164. svr.Post("/test", [&](const Request &req, Response &res) {
  10165. // Case-insensitive "utf-8''" prefix with a long value
  10166. const auto &file = req.form.get_file("file1");
  10167. ASSERT_EQ("file1", file.name);
  10168. // 8000 chars exercises both the Content-Disposition parser and the
  10169. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10170. // Prior to the fix, std::regex_match on this header would cause O(N)
  10171. // stack recursion in libstdc++, leading to SIGSEGV.
  10172. std::string expected_filename(8000, 'A');
  10173. ASSERT_EQ(expected_filename, file.filename);
  10174. res.set_content("ok", "text/plain");
  10175. handled = true;
  10176. });
  10177. thread t = thread([&] { svr.listen(HOST, PORT); });
  10178. auto se = detail::scope_exit([&] {
  10179. svr.stop();
  10180. t.join();
  10181. ASSERT_FALSE(svr.is_running());
  10182. ASSERT_TRUE(handled);
  10183. });
  10184. svr.wait_until_ready();
  10185. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10186. // Regression test for GHSA-qq6v-r583-3h69
  10187. std::string long_filename(8000, 'A');
  10188. std::string body = "----------\r\n"
  10189. "Content-Disposition: form-data; name=\"file1\"; "
  10190. "filename*=\"Utf-8''" +
  10191. long_filename +
  10192. "\"\r\n"
  10193. "\r\n"
  10194. "hello\r\n"
  10195. "------------\r\n";
  10196. auto req = "POST /test HTTP/1.1\r\n"
  10197. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10198. "Content-Length: " +
  10199. std::to_string(body.size()) + "\r\n\r\n" + body;
  10200. ASSERT_TRUE(send_request(1, req));
  10201. }
  10202. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10203. auto handled = false;
  10204. Server svr;
  10205. svr.Post("/test", [&](const Request &req, Response &) {
  10206. ASSERT_EQ(2u, req.form.fields.size());
  10207. const auto &text1 = req.form.get_field("text1");
  10208. ASSERT_EQ("text1", text1);
  10209. const auto &text2 = req.form.get_field("text2");
  10210. ASSERT_EQ("text2", text2);
  10211. handled = true;
  10212. });
  10213. thread t = thread([&] { svr.listen(HOST, PORT); });
  10214. auto se = detail::scope_exit([&] {
  10215. svr.stop();
  10216. t.join();
  10217. ASSERT_FALSE(svr.is_running());
  10218. ASSERT_TRUE(handled);
  10219. });
  10220. svr.wait_until_ready();
  10221. auto req = "POST /test HTTP/1.1\r\n"
  10222. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10223. "Content-Length: 146\r\n"
  10224. "\r\n----------\r\n"
  10225. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10226. "\r\n"
  10227. "text1"
  10228. "\r\n----------\r\n"
  10229. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10230. "\r\n"
  10231. "text2"
  10232. "\r\n------------";
  10233. std::string response;
  10234. ASSERT_TRUE(send_request(1, req, &response));
  10235. ASSERT_EQ("200", response.substr(9, 3));
  10236. }
  10237. TEST(MultipartFormDataTest, ContentLength) {
  10238. auto handled = false;
  10239. Server svr;
  10240. svr.Post("/test", [&](const Request &req, Response &) {
  10241. ASSERT_EQ(2u, req.form.fields.size());
  10242. const auto &text1 = req.form.get_field("text1");
  10243. ASSERT_EQ("text1", text1);
  10244. const auto &text2 = req.form.get_field("text2");
  10245. ASSERT_EQ("text2", text2);
  10246. handled = true;
  10247. });
  10248. thread t = thread([&] { svr.listen(HOST, PORT); });
  10249. auto se = detail::scope_exit([&] {
  10250. svr.stop();
  10251. t.join();
  10252. ASSERT_FALSE(svr.is_running());
  10253. ASSERT_TRUE(handled);
  10254. });
  10255. svr.wait_until_ready();
  10256. auto req = "POST /test HTTP/1.1\r\n"
  10257. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10258. "Content-Length: 167\r\n"
  10259. "\r\n----------\r\n"
  10260. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10261. "Content-Length: 5\r\n"
  10262. "\r\n"
  10263. "text1"
  10264. "\r\n----------\r\n"
  10265. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10266. "\r\n"
  10267. "text2"
  10268. "\r\n------------\r\n";
  10269. std::string response;
  10270. ASSERT_TRUE(send_request(1, req, &response));
  10271. ASSERT_EQ("200", response.substr(9, 3));
  10272. }
  10273. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10274. auto handled = false;
  10275. Server svr;
  10276. svr.Post("/test", [&](const Request &req, Response &) {
  10277. ASSERT_EQ(2u, req.form.fields.size());
  10278. const auto &text1 = req.form.get_field("text1");
  10279. ASSERT_EQ("text1", text1);
  10280. // TODO: Add header access for text fields if needed
  10281. const auto &text2 = req.form.get_field("text2");
  10282. ASSERT_EQ("text2", text2);
  10283. // TODO: Header access for text fields needs to be implemented
  10284. // auto &headers = it->second.headers;
  10285. // ASSERT_EQ(3U, headers.size());
  10286. // auto custom_header = headers.find("x-whatever");
  10287. // ASSERT_TRUE(custom_header != headers.end());
  10288. // ASSERT_NE("customvalue", custom_header->second);
  10289. // ASSERT_EQ("CustomValue", custom_header->second);
  10290. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10291. handled = true;
  10292. });
  10293. thread t = thread([&] { svr.listen(HOST, PORT); });
  10294. auto se = detail::scope_exit([&] {
  10295. svr.stop();
  10296. t.join();
  10297. ASSERT_FALSE(svr.is_running());
  10298. ASSERT_TRUE(handled);
  10299. });
  10300. svr.wait_until_ready();
  10301. auto req = "POST /test HTTP/1.1\r\n"
  10302. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10303. "Content-Length: 232\r\n"
  10304. "\r\n----------\r\n"
  10305. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10306. "Content-Length: 5\r\n"
  10307. "X-Test: 1\r\n"
  10308. "\r\n"
  10309. "text1"
  10310. "\r\n----------\r\n"
  10311. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10312. "Content-Type: text/plain\r\n"
  10313. "X-Whatever: CustomValue\r\n"
  10314. "\r\n"
  10315. "text2"
  10316. "\r\n------------\r\n"
  10317. "That should be disregarded. Not even read";
  10318. std::string response;
  10319. ASSERT_TRUE(send_request(1, req, &response));
  10320. ASSERT_EQ("200", response.substr(9, 3));
  10321. }
  10322. TEST(MultipartFormDataTest, LargeHeader) {
  10323. auto handled = false;
  10324. Server svr;
  10325. svr.Post("/test", [&](const Request &req, Response &) {
  10326. ASSERT_EQ(1u, req.form.fields.size());
  10327. const auto &text = req.form.get_field("name1");
  10328. ASSERT_EQ("text1", text);
  10329. handled = true;
  10330. });
  10331. thread t = thread([&] { svr.listen(HOST, PORT); });
  10332. auto se = detail::scope_exit([&] {
  10333. svr.stop();
  10334. t.join();
  10335. ASSERT_FALSE(svr.is_running());
  10336. ASSERT_TRUE(handled);
  10337. });
  10338. svr.wait_until_ready();
  10339. auto boundary = std::string("cpp-httplib-multipart-data");
  10340. std::string content = "--" + boundary +
  10341. "\r\n"
  10342. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10343. "\r\n"
  10344. "text1\r\n"
  10345. "--" +
  10346. boundary + "--\r\n";
  10347. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10348. "Content-Type: multipart/form-data;boundary=" +
  10349. boundary +
  10350. "\r\n"
  10351. "Content-Length: " +
  10352. std::to_string(content.size()) +
  10353. "\r\n"
  10354. "Dummy-Header: ";
  10355. std::string header_suffix = "\r\n"
  10356. "\r\n";
  10357. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10358. size_t header_dummy_size =
  10359. read_buff_size -
  10360. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10361. auto header_dummy = std::string(header_dummy_size, '@');
  10362. auto req = header_prefix + header_dummy + header_suffix + content;
  10363. std::string response;
  10364. ASSERT_TRUE(send_request(1, req, &response));
  10365. ASSERT_EQ("200", response.substr(9, 3));
  10366. }
  10367. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10368. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10369. // (not chunked Transfer-Encoding) after the streaming refactor.
  10370. auto handled = false;
  10371. Server svr;
  10372. svr.Post("/upload", [&](const Request &req, Response &res) {
  10373. auto cl_it = req.headers.find("Content-Length");
  10374. EXPECT_TRUE(cl_it != req.headers.end());
  10375. auto te_it = req.headers.find("Transfer-Encoding");
  10376. EXPECT_TRUE(te_it == req.headers.end());
  10377. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10378. res.set_content("ok", "text/plain");
  10379. handled = true;
  10380. });
  10381. auto port = svr.bind_to_any_port(HOST);
  10382. auto t = thread([&] { svr.listen_after_bind(); });
  10383. auto se = detail::scope_exit([&] {
  10384. svr.stop();
  10385. t.join();
  10386. ASSERT_FALSE(svr.is_running());
  10387. ASSERT_TRUE(handled);
  10388. });
  10389. svr.wait_until_ready();
  10390. UploadFormDataItems items = {
  10391. {"field1", "hello", "", "text/plain"},
  10392. {"file1", "world", "test.txt", "application/octet-stream"},
  10393. };
  10394. Client cli(HOST, port);
  10395. auto res = cli.Post("/upload", {}, items);
  10396. ASSERT_TRUE(res);
  10397. EXPECT_EQ(StatusCode::OK_200, res->status);
  10398. }
  10399. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10400. // Verify that make_multipart_content_provider coalesces many small segments
  10401. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10402. constexpr size_t kItemCount = 1000;
  10403. UploadFormDataItems items;
  10404. items.reserve(kItemCount);
  10405. for (size_t i = 0; i < kItemCount; i++) {
  10406. items.push_back(
  10407. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10408. }
  10409. const std::string boundary = "----test-boundary";
  10410. auto content_length = detail::get_multipart_content_length(items, boundary);
  10411. auto provider = detail::make_multipart_content_provider(items, boundary);
  10412. // Drive the provider the same way write_content_with_progress does
  10413. size_t write_count = 0;
  10414. size_t total_bytes = 0;
  10415. DataSink sink;
  10416. size_t offset = 0;
  10417. sink.write = [&](const char *d, size_t l) -> bool {
  10418. (void)d;
  10419. write_count++;
  10420. total_bytes += l;
  10421. offset += l;
  10422. return true;
  10423. };
  10424. sink.is_writable = []() -> bool { return true; };
  10425. while (offset < content_length) {
  10426. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10427. }
  10428. EXPECT_EQ(content_length, total_bytes);
  10429. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10430. // With buffering into 64KB blocks, write_count should be much smaller.
  10431. auto segment_count = 3 * kItemCount + 1;
  10432. EXPECT_LT(write_count, segment_count / 10);
  10433. }
  10434. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10435. // Integration test: send many UploadFormDataItems and verify the server
  10436. // receives all of them correctly (#2410).
  10437. constexpr size_t kItemCount = 500;
  10438. auto handled = false;
  10439. Server svr;
  10440. svr.Post("/upload", [&](const Request &req, Response &res) {
  10441. EXPECT_EQ(kItemCount, req.form.fields.size());
  10442. for (size_t i = 0; i < kItemCount; i++) {
  10443. auto key = "field" + std::to_string(i);
  10444. auto val = "value" + std::to_string(i);
  10445. auto it = req.form.fields.find(key);
  10446. if (it != req.form.fields.end()) {
  10447. EXPECT_EQ(val, it->second.content);
  10448. } else {
  10449. ADD_FAILURE() << "Missing field: " << key;
  10450. }
  10451. }
  10452. res.set_content("ok", "text/plain");
  10453. handled = true;
  10454. });
  10455. auto port = svr.bind_to_any_port(HOST);
  10456. auto t = thread([&] { svr.listen_after_bind(); });
  10457. auto se = detail::scope_exit([&] {
  10458. svr.stop();
  10459. t.join();
  10460. ASSERT_FALSE(svr.is_running());
  10461. ASSERT_TRUE(handled);
  10462. });
  10463. svr.wait_until_ready();
  10464. UploadFormDataItems items;
  10465. items.reserve(kItemCount);
  10466. for (size_t i = 0; i < kItemCount; i++) {
  10467. items.push_back(
  10468. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10469. }
  10470. Client cli(HOST, port);
  10471. auto res = cli.Post("/upload", items);
  10472. ASSERT_TRUE(res);
  10473. EXPECT_EQ(StatusCode::OK_200, res->status);
  10474. }
  10475. TEST(MultipartFormDataTest, MakeFileProvider) {
  10476. // Verify make_file_provider sends a file's contents correctly.
  10477. const std::string file_content(4096, 'Z');
  10478. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10479. {
  10480. std::ofstream ofs(tmp_path, std::ios::binary);
  10481. ofs.write(file_content.data(),
  10482. static_cast<std::streamsize>(file_content.size()));
  10483. }
  10484. auto handled = false;
  10485. Server svr;
  10486. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10487. const ContentReader &content_reader) {
  10488. ASSERT_TRUE(req.is_multipart_form_data());
  10489. std::vector<FormData> items;
  10490. content_reader(
  10491. [&](const FormData &file) {
  10492. items.push_back(file);
  10493. return true;
  10494. },
  10495. [&](const char *data, size_t data_length) {
  10496. items.back().content.append(data, data_length);
  10497. return true;
  10498. });
  10499. ASSERT_EQ(1u, items.size());
  10500. EXPECT_EQ("myfile", items[0].name);
  10501. EXPECT_EQ("data.bin", items[0].filename);
  10502. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10503. EXPECT_EQ(file_content, items[0].content);
  10504. handled = true;
  10505. });
  10506. auto port = svr.bind_to_any_port(HOST);
  10507. auto t = thread([&] { svr.listen_after_bind(); });
  10508. auto se = detail::scope_exit([&] {
  10509. svr.stop();
  10510. t.join();
  10511. ASSERT_FALSE(svr.is_running());
  10512. ASSERT_TRUE(handled);
  10513. std::remove(tmp_path.c_str());
  10514. });
  10515. svr.wait_until_ready();
  10516. FormDataProviderItems providers;
  10517. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10518. "application/octet-stream"));
  10519. Client cli(HOST, port);
  10520. auto res = cli.Post("/upload", {}, {}, providers);
  10521. ASSERT_TRUE(res);
  10522. EXPECT_EQ(StatusCode::OK_200, res->status);
  10523. }
  10524. TEST(MakeFileBodyTest, Basic) {
  10525. const std::string file_content(4096, 'Z');
  10526. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10527. {
  10528. std::ofstream ofs(tmp_path, std::ios::binary);
  10529. ofs.write(file_content.data(),
  10530. static_cast<std::streamsize>(file_content.size()));
  10531. }
  10532. auto handled = false;
  10533. Server svr;
  10534. svr.Post("/upload", [&](const Request &req, Response &res) {
  10535. EXPECT_EQ(file_content, req.body);
  10536. handled = true;
  10537. res.status = StatusCode::OK_200;
  10538. });
  10539. auto port = svr.bind_to_any_port(HOST);
  10540. auto t = thread([&] { svr.listen_after_bind(); });
  10541. auto se = detail::scope_exit([&] {
  10542. svr.stop();
  10543. t.join();
  10544. ASSERT_FALSE(svr.is_running());
  10545. ASSERT_TRUE(handled);
  10546. std::remove(tmp_path.c_str());
  10547. });
  10548. svr.wait_until_ready();
  10549. auto fb = make_file_body(tmp_path);
  10550. ASSERT_GT(fb.first, 0u);
  10551. Client cli(HOST, port);
  10552. auto res =
  10553. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10554. ASSERT_TRUE(res);
  10555. EXPECT_EQ(StatusCode::OK_200, res->status);
  10556. }
  10557. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10558. static constexpr unsigned int number_of_tasks{1000000};
  10559. std::atomic_uint count{0};
  10560. std::unique_ptr<TaskQueue> task_queue{
  10561. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10562. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10563. auto queued = task_queue->enqueue(
  10564. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10565. EXPECT_TRUE(queued);
  10566. }
  10567. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10568. task_queue->shutdown();
  10569. #else
  10570. EXPECT_NO_THROW(task_queue->shutdown());
  10571. #endif
  10572. EXPECT_EQ(number_of_tasks, count.load());
  10573. }
  10574. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10575. static constexpr unsigned int number_of_tasks{1000000};
  10576. static constexpr unsigned int qlimit{2};
  10577. unsigned int queued_count{0};
  10578. std::atomic_uint count{0};
  10579. std::unique_ptr<TaskQueue> task_queue{
  10580. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10581. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10582. if (task_queue->enqueue(
  10583. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10584. queued_count++;
  10585. }
  10586. }
  10587. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10588. task_queue->shutdown();
  10589. #else
  10590. EXPECT_NO_THROW(task_queue->shutdown());
  10591. #endif
  10592. EXPECT_EQ(queued_count, count.load());
  10593. EXPECT_TRUE(queued_count <= number_of_tasks);
  10594. EXPECT_TRUE(queued_count >= qlimit);
  10595. }
  10596. TEST(TaskQueueTest, MaxQueuedRequests) {
  10597. static constexpr unsigned int qlimit{3};
  10598. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10599. std::condition_variable sem_cv;
  10600. std::mutex sem_mtx;
  10601. int credits = 0;
  10602. bool queued;
  10603. /* Fill up the queue with tasks that will block until we give them credits to
  10604. * complete. */
  10605. for (unsigned int n = 0; n <= qlimit;) {
  10606. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10607. std::unique_lock<std::mutex> lock(sem_mtx);
  10608. while (credits <= 0) {
  10609. sem_cv.wait(lock);
  10610. }
  10611. /* Consume the credit and signal the test code if they are all gone. */
  10612. if (--credits == 0) { sem_cv.notify_one(); }
  10613. });
  10614. if (n < qlimit) {
  10615. /* The first qlimit enqueues must succeed. */
  10616. EXPECT_TRUE(queued);
  10617. } else {
  10618. /* The last one will succeed only when the worker thread
  10619. * starts and dequeues the first blocking task. Although
  10620. * not necessary for the correctness of this test, we sleep for
  10621. * a short while to avoid busy waiting. */
  10622. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10623. }
  10624. if (queued) { n++; }
  10625. }
  10626. /* Further enqueues must fail since the queue is full. */
  10627. for (auto i = 0; i < 4; i++) {
  10628. queued = task_queue->enqueue([] {});
  10629. EXPECT_FALSE(queued);
  10630. }
  10631. /* Give the credits to allow the previous tasks to complete. */
  10632. {
  10633. std::unique_lock<std::mutex> lock(sem_mtx);
  10634. credits += qlimit + 1;
  10635. }
  10636. sem_cv.notify_all();
  10637. /* Wait for all the credits to be consumed. */
  10638. {
  10639. std::unique_lock<std::mutex> lock(sem_mtx);
  10640. while (credits > 0) {
  10641. sem_cv.wait(lock);
  10642. }
  10643. }
  10644. /* Check that we are able again to enqueue at least qlimit tasks. */
  10645. for (unsigned int i = 0; i < qlimit; i++) {
  10646. queued = task_queue->enqueue([] {});
  10647. EXPECT_TRUE(queued);
  10648. }
  10649. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10650. task_queue->shutdown();
  10651. #else
  10652. EXPECT_NO_THROW(task_queue->shutdown());
  10653. #endif
  10654. }
  10655. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10656. Server svr;
  10657. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10658. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10659. });
  10660. svr.Get("/hello", [](const Request &req, Response &res) {
  10661. res.set_content(req.get_param_value("key"), "text/plain");
  10662. });
  10663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10664. auto se = detail::scope_exit([&] {
  10665. svr.stop();
  10666. thread.join();
  10667. ASSERT_FALSE(svr.is_running());
  10668. });
  10669. svr.wait_until_ready();
  10670. {
  10671. Client cli(HOST, PORT);
  10672. cli.set_follow_location(true);
  10673. auto res = cli.Get("/");
  10674. ASSERT_TRUE(res);
  10675. EXPECT_EQ(StatusCode::OK_200, res->status);
  10676. EXPECT_EQ("val&key2=val2", res->body);
  10677. }
  10678. }
  10679. #endif
  10680. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10681. Server svr;
  10682. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10683. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10684. });
  10685. svr.Get("/hello", [](const Request &req, Response &res) {
  10686. res.set_content(req.get_param_value("key"), "text/plain");
  10687. });
  10688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10689. auto se = detail::scope_exit([&] {
  10690. svr.stop();
  10691. thread.join();
  10692. ASSERT_FALSE(svr.is_running());
  10693. });
  10694. svr.wait_until_ready();
  10695. {
  10696. Client cli(HOST, PORT);
  10697. cli.set_follow_location(true);
  10698. auto res = cli.Get("/");
  10699. ASSERT_TRUE(res);
  10700. EXPECT_EQ(StatusCode::OK_200, res->status);
  10701. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10702. }
  10703. }
  10704. TEST(RedirectTest, RedirectWithPlusInPath) {
  10705. Server svr;
  10706. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10707. res.set_redirect("/a+b");
  10708. });
  10709. // Route pattern uses regex; escape + as \\+
  10710. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10711. res.set_content(req.path, "text/plain");
  10712. });
  10713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10714. auto se = detail::scope_exit([&] {
  10715. svr.stop();
  10716. thread.join();
  10717. ASSERT_FALSE(svr.is_running());
  10718. });
  10719. svr.wait_until_ready();
  10720. {
  10721. Client cli(HOST, PORT);
  10722. cli.set_follow_location(true);
  10723. auto res = cli.Get("/");
  10724. ASSERT_TRUE(res);
  10725. EXPECT_EQ(StatusCode::OK_200, res->status);
  10726. EXPECT_EQ("/a+b", res->body);
  10727. }
  10728. }
  10729. #ifdef CPPHTTPLIB_SSL_ENABLED
  10730. TEST(RedirectTest, Issue2185_Online) {
  10731. SSLClient client("github.com");
  10732. client.set_follow_location(true);
  10733. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10734. "Coollab-Windows.zip");
  10735. ASSERT_TRUE(res);
  10736. EXPECT_EQ(StatusCode::OK_200, res->status);
  10737. EXPECT_EQ(9920427U, res->body.size());
  10738. }
  10739. #endif
  10740. TEST(VulnerabilityTest, CRLFInjection) {
  10741. Server svr;
  10742. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10743. res.set_content("Hello 1", "text/plain");
  10744. });
  10745. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10746. res.set_content("Hello 2", "text/plain");
  10747. });
  10748. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10749. res.set_content("Hello 3", "text/plain");
  10750. });
  10751. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10752. res.set_content("Hello 4", "text/plain");
  10753. });
  10754. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10755. for (const auto &x : req.headers) {
  10756. auto key = x.first;
  10757. EXPECT_STRNE("evil", key.c_str());
  10758. }
  10759. });
  10760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10761. auto se = detail::scope_exit([&] {
  10762. svr.stop();
  10763. thread.join();
  10764. ASSERT_FALSE(svr.is_running());
  10765. });
  10766. svr.wait_until_ready();
  10767. {
  10768. Client cli(HOST, PORT);
  10769. cli.Post("/test1", "A=B",
  10770. "application/x-www-form-urlencoded\r\nevil: hello1");
  10771. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10772. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10773. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10774. }
  10775. }
  10776. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10777. auto server_thread = std::thread([] {
  10778. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10779. default_socket_options(srv);
  10780. sockaddr_in addr{};
  10781. addr.sin_family = AF_INET;
  10782. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10783. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10784. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10785. ::listen(srv, 1);
  10786. sockaddr_in cli_addr{};
  10787. socklen_t cli_len = sizeof(cli_addr);
  10788. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10789. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10790. std::string buf_all;
  10791. char buf[2048];
  10792. ssize_t n;
  10793. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10794. buf_all.append(buf, static_cast<size_t>(n));
  10795. size_t pos;
  10796. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10797. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10798. auto e = request_block.find("\r\n");
  10799. if (e != std::string::npos) {
  10800. auto request_line = request_block.substr(0, e);
  10801. std::string msg =
  10802. "CRLF injection detected in request line: '" + request_line + "'";
  10803. EXPECT_FALSE(true) << msg;
  10804. }
  10805. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10806. ::send(cli,
  10807. #ifdef _WIN32
  10808. static_cast<const char *>(resp.c_str()),
  10809. static_cast<int>(resp.size()),
  10810. #else
  10811. resp.c_str(), resp.size(),
  10812. #endif
  10813. 0);
  10814. buf_all.erase(0, pos + 4);
  10815. }
  10816. }
  10817. detail::close_socket(cli);
  10818. detail::close_socket(srv);
  10819. });
  10820. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10821. auto cli = Client("127.0.0.1", PORT + 1);
  10822. auto headers = Headers{
  10823. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10824. {"Connection", "keep-alive"}};
  10825. auto res = cli.Get("/hi", headers);
  10826. EXPECT_FALSE(res);
  10827. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10828. server_thread.join();
  10829. }
  10830. TEST(PathParamsTest, StaticMatch) {
  10831. const auto pattern = "/users/all";
  10832. detail::PathParamsMatcher matcher(pattern);
  10833. Request request;
  10834. request.path = "/users/all";
  10835. ASSERT_TRUE(matcher.match(request));
  10836. std::unordered_map<std::string, std::string> expected_params = {};
  10837. EXPECT_EQ(request.path_params, expected_params);
  10838. }
  10839. TEST(PathParamsTest, StaticMismatch) {
  10840. const auto pattern = "/users/all";
  10841. detail::PathParamsMatcher matcher(pattern);
  10842. Request request;
  10843. request.path = "/users/1";
  10844. ASSERT_FALSE(matcher.match(request));
  10845. }
  10846. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10847. const auto pattern = "/users/:id/subscriptions";
  10848. detail::PathParamsMatcher matcher(pattern);
  10849. Request request;
  10850. request.path = "/users/42/subscriptions";
  10851. ASSERT_TRUE(matcher.match(request));
  10852. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10853. EXPECT_EQ(request.path_params, expected_params);
  10854. }
  10855. TEST(PathParamsTest, SingleParamInTheEnd) {
  10856. const auto pattern = "/users/:id";
  10857. detail::PathParamsMatcher matcher(pattern);
  10858. Request request;
  10859. request.path = "/users/24";
  10860. ASSERT_TRUE(matcher.match(request));
  10861. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10862. EXPECT_EQ(request.path_params, expected_params);
  10863. }
  10864. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10865. const auto pattern = "/users/:id/";
  10866. detail::PathParamsMatcher matcher(pattern);
  10867. Request request;
  10868. request.path = "/users/42/";
  10869. ASSERT_TRUE(matcher.match(request));
  10870. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10871. EXPECT_EQ(request.path_params, expected_params);
  10872. }
  10873. TEST(PathParamsTest, EmptyParam) {
  10874. const auto pattern = "/users/:id/";
  10875. detail::PathParamsMatcher matcher(pattern);
  10876. Request request;
  10877. request.path = "/users//";
  10878. ASSERT_TRUE(matcher.match(request));
  10879. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10880. EXPECT_EQ(request.path_params, expected_params);
  10881. }
  10882. TEST(PathParamsTest, FragmentMismatch) {
  10883. const auto pattern = "/users/:id/";
  10884. detail::PathParamsMatcher matcher(pattern);
  10885. Request request;
  10886. request.path = "/admins/24/";
  10887. ASSERT_FALSE(matcher.match(request));
  10888. }
  10889. TEST(PathParamsTest, ExtraFragments) {
  10890. const auto pattern = "/users/:id";
  10891. detail::PathParamsMatcher matcher(pattern);
  10892. Request request;
  10893. request.path = "/users/42/subscriptions";
  10894. ASSERT_FALSE(matcher.match(request));
  10895. }
  10896. TEST(PathParamsTest, MissingTrailingParam) {
  10897. const auto pattern = "/users/:id";
  10898. detail::PathParamsMatcher matcher(pattern);
  10899. Request request;
  10900. request.path = "/users";
  10901. ASSERT_FALSE(matcher.match(request));
  10902. }
  10903. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10904. const auto pattern = "/users/:id/subscriptions";
  10905. detail::PathParamsMatcher matcher(pattern);
  10906. Request request;
  10907. request.path = "/users/subscriptions";
  10908. ASSERT_FALSE(matcher.match(request));
  10909. }
  10910. TEST(PathParamsTest, MultipleParams) {
  10911. const auto pattern = "/users/:userid/subscriptions/:subid";
  10912. detail::PathParamsMatcher matcher(pattern);
  10913. Request request;
  10914. request.path = "/users/42/subscriptions/2";
  10915. ASSERT_TRUE(matcher.match(request));
  10916. std::unordered_map<std::string, std::string> expected_params = {
  10917. {"userid", "42"}, {"subid", "2"}};
  10918. EXPECT_EQ(request.path_params, expected_params);
  10919. }
  10920. TEST(PathParamsTest, SequenceOfParams) {
  10921. const auto pattern = "/values/:x/:y/:z";
  10922. detail::PathParamsMatcher matcher(pattern);
  10923. Request request;
  10924. request.path = "/values/1/2/3";
  10925. ASSERT_TRUE(matcher.match(request));
  10926. std::unordered_map<std::string, std::string> expected_params = {
  10927. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10928. EXPECT_EQ(request.path_params, expected_params);
  10929. }
  10930. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10931. const auto pattern = "/prefix:suffix";
  10932. detail::PathParamsMatcher matcher(pattern);
  10933. Request request;
  10934. request.path = "/prefix:suffix";
  10935. ASSERT_TRUE(matcher.match(request));
  10936. const std::unordered_map<std::string, std::string> expected_params = {};
  10937. EXPECT_EQ(request.path_params, expected_params);
  10938. }
  10939. TEST(ParseUrlTest, VariousPatterns) {
  10940. {
  10941. detail::UrlComponents uc;
  10942. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10943. EXPECT_EQ("http", uc.scheme);
  10944. EXPECT_EQ("example.com", uc.host);
  10945. EXPECT_EQ("8080", uc.port);
  10946. EXPECT_EQ("/path", uc.path);
  10947. EXPECT_EQ("?q=1", uc.query);
  10948. }
  10949. {
  10950. detail::UrlComponents uc;
  10951. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10952. EXPECT_EQ("https", uc.scheme);
  10953. EXPECT_EQ("example.com", uc.host);
  10954. EXPECT_TRUE(uc.port.empty());
  10955. EXPECT_EQ("/path", uc.path);
  10956. }
  10957. {
  10958. detail::UrlComponents uc;
  10959. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10960. EXPECT_EQ("::1", uc.host);
  10961. EXPECT_EQ("8080", uc.port);
  10962. EXPECT_EQ("/path", uc.path);
  10963. }
  10964. {
  10965. detail::UrlComponents uc;
  10966. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10967. }
  10968. {
  10969. detail::UrlComponents uc;
  10970. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10971. EXPECT_TRUE(uc.scheme.empty());
  10972. EXPECT_EQ("example.com", uc.host);
  10973. EXPECT_EQ("/path", uc.path);
  10974. EXPECT_EQ("?q=1", uc.query);
  10975. }
  10976. {
  10977. detail::UrlComponents uc;
  10978. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10979. EXPECT_TRUE(uc.host.empty());
  10980. EXPECT_EQ("/path", uc.path);
  10981. EXPECT_EQ("?q=1", uc.query);
  10982. }
  10983. {
  10984. detail::UrlComponents uc;
  10985. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10986. EXPECT_EQ("example.com", uc.host);
  10987. EXPECT_EQ("8080", uc.port);
  10988. }
  10989. {
  10990. // Unix socket path — must not be parsed as host
  10991. detail::UrlComponents uc;
  10992. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  10993. EXPECT_TRUE(uc.host.empty());
  10994. }
  10995. {
  10996. detail::UrlComponents uc;
  10997. ASSERT_TRUE(detail::parse_url("", uc));
  10998. EXPECT_TRUE(uc.host.empty());
  10999. EXPECT_TRUE(uc.path.empty());
  11000. }
  11001. {
  11002. detail::UrlComponents uc;
  11003. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11004. }
  11005. {
  11006. detail::UrlComponents uc;
  11007. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11008. }
  11009. {
  11010. // Accepted by parse_url; callers restrict to http/https
  11011. detail::UrlComponents uc;
  11012. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11013. EXPECT_EQ("ftp", uc.scheme);
  11014. }
  11015. {
  11016. detail::UrlComponents uc;
  11017. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11018. }
  11019. {
  11020. detail::UrlComponents uc;
  11021. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11022. }
  11023. }
  11024. TEST(ParseUrlTest, FragmentHandling) {
  11025. {
  11026. detail::UrlComponents uc;
  11027. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11028. EXPECT_EQ("/path", uc.path);
  11029. EXPECT_TRUE(uc.query.empty());
  11030. }
  11031. {
  11032. detail::UrlComponents uc;
  11033. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11034. EXPECT_TRUE(uc.path.empty());
  11035. EXPECT_TRUE(uc.query.empty());
  11036. }
  11037. }
  11038. TEST(ParseUrlTest, UserinfoHandling) {
  11039. // Userinfo with @ but no colon — host includes @
  11040. detail::UrlComponents uc;
  11041. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11042. EXPECT_EQ("user@host.com", uc.host);
  11043. EXPECT_EQ("/path", uc.path);
  11044. }
  11045. TEST(ParseUrlTest, IPv6EdgeCases) {
  11046. {
  11047. detail::UrlComponents uc;
  11048. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11049. EXPECT_TRUE(uc.scheme.empty());
  11050. EXPECT_EQ("::1", uc.host);
  11051. EXPECT_EQ("8080", uc.port);
  11052. }
  11053. {
  11054. // Zone ID '%25' is not in [a-fA-F0-9:]
  11055. detail::UrlComponents uc;
  11056. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11057. }
  11058. }
  11059. TEST(ParseUrlTest, SchemeEdgeCases) {
  11060. {
  11061. detail::UrlComponents uc;
  11062. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11063. }
  11064. {
  11065. detail::UrlComponents uc;
  11066. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11067. }
  11068. {
  11069. detail::UrlComponents uc;
  11070. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11071. }
  11072. }
  11073. TEST(ParseUrlTest, PortEdgeCases) {
  11074. {
  11075. detail::UrlComponents uc;
  11076. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11077. EXPECT_TRUE(uc.port.empty());
  11078. EXPECT_EQ("/path", uc.path);
  11079. }
  11080. {
  11081. // parse_url accepts any port string; validation is done by parse_port
  11082. detail::UrlComponents uc;
  11083. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11084. EXPECT_EQ("abc", uc.port);
  11085. }
  11086. }
  11087. TEST(ParseUrlTest, WebSocketPatterns) {
  11088. {
  11089. detail::UrlComponents uc;
  11090. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11091. EXPECT_EQ("ws", uc.scheme);
  11092. EXPECT_EQ("echo.example.com", uc.host);
  11093. EXPECT_EQ("8080", uc.port);
  11094. EXPECT_EQ("/ws", uc.path);
  11095. }
  11096. {
  11097. detail::UrlComponents uc;
  11098. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11099. EXPECT_EQ("wss", uc.scheme);
  11100. EXPECT_EQ("echo.example.com", uc.host);
  11101. EXPECT_TRUE(uc.port.empty());
  11102. EXPECT_EQ("/ws", uc.path);
  11103. }
  11104. }
  11105. TEST(ParseUrlTest, QueryOnly) {
  11106. detail::UrlComponents uc;
  11107. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11108. EXPECT_TRUE(uc.host.empty());
  11109. EXPECT_TRUE(uc.path.empty());
  11110. EXPECT_EQ("?q=1&r=2", uc.query);
  11111. }
  11112. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11113. detail::UrlComponents uc;
  11114. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11115. EXPECT_TRUE(uc.scheme.empty());
  11116. EXPECT_EQ("example.com", uc.host);
  11117. EXPECT_EQ("443", uc.port);
  11118. EXPECT_EQ("/path", uc.path);
  11119. }
  11120. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11121. // If ipv6 regex working, regex match codepath is taken.
  11122. // else port will default to 80 in Client impl
  11123. int clientImplMagicPort = 80;
  11124. int port = 4321;
  11125. // above ports must be different to avoid false negative
  11126. EXPECT_NE(clientImplMagicPort, port);
  11127. std::string ipV6TestURL = "http://[ff06::c3]";
  11128. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11129. CLIENT_PRIVATE_KEY_FILE);
  11130. EXPECT_EQ(cli.port(), port);
  11131. }
  11132. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11133. auto file_path = "./www/dir/index.html";
  11134. auto dir_path = "./www/dir";
  11135. detail::FileStat stat_file(file_path);
  11136. EXPECT_TRUE(stat_file.is_file());
  11137. EXPECT_FALSE(stat_file.is_dir());
  11138. detail::FileStat stat_dir(dir_path);
  11139. EXPECT_FALSE(stat_dir.is_file());
  11140. EXPECT_TRUE(stat_dir.is_dir());
  11141. }
  11142. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11143. // IPv4 with default HTTP port (80)
  11144. EXPECT_EQ("example.com",
  11145. detail::make_host_and_port_string("example.com", 80, false));
  11146. // IPv4 with default HTTPS port (443)
  11147. EXPECT_EQ("example.com",
  11148. detail::make_host_and_port_string("example.com", 443, true));
  11149. // IPv4 with non-default HTTP port
  11150. EXPECT_EQ("example.com:8080",
  11151. detail::make_host_and_port_string("example.com", 8080, false));
  11152. // IPv4 with non-default HTTPS port
  11153. EXPECT_EQ("example.com:8443",
  11154. detail::make_host_and_port_string("example.com", 8443, true));
  11155. // IPv6 with default HTTP port (80)
  11156. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11157. // IPv6 with default HTTPS port (443)
  11158. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11159. // IPv6 with non-default HTTP port
  11160. EXPECT_EQ("[::1]:8080",
  11161. detail::make_host_and_port_string("::1", 8080, false));
  11162. // IPv6 with non-default HTTPS port
  11163. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11164. // IPv6 full address with default port
  11165. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11166. detail::make_host_and_port_string(
  11167. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11168. // IPv6 full address with non-default port
  11169. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11170. detail::make_host_and_port_string(
  11171. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11172. // IPv6 localhost with non-default port
  11173. EXPECT_EQ("[::1]:3000",
  11174. detail::make_host_and_port_string("::1", 3000, false));
  11175. // IPv6 with zone ID (link-local address) with default port
  11176. EXPECT_EQ("[fe80::1%eth0]",
  11177. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11178. // IPv6 with zone ID (link-local address) with non-default port
  11179. EXPECT_EQ("[fe80::1%eth0]:8080",
  11180. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11181. // Edge case: Port 443 with is_ssl=false (should add port)
  11182. EXPECT_EQ("example.com:443",
  11183. detail::make_host_and_port_string("example.com", 443, false));
  11184. // Edge case: Port 80 with is_ssl=true (should add port)
  11185. EXPECT_EQ("example.com:80",
  11186. detail::make_host_and_port_string("example.com", 80, true));
  11187. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11188. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11189. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11190. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11191. // Security fix: Already bracketed IPv6 should not get double brackets
  11192. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11193. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11194. EXPECT_EQ("[::1]:8080",
  11195. detail::make_host_and_port_string("[::1]", 8080, false));
  11196. EXPECT_EQ("[2001:db8::1]:8080",
  11197. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11198. EXPECT_EQ("[fe80::1%eth0]",
  11199. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11200. EXPECT_EQ("[fe80::1%eth0]:8080",
  11201. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11202. // Edge case: Empty host (should return as-is)
  11203. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11204. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11205. // This is a known limitation but shouldn't crash
  11206. EXPECT_EQ("[host:name]",
  11207. detail::make_host_and_port_string("host:name", 80, false));
  11208. // Port number edge cases (no validation, but should not crash)
  11209. EXPECT_EQ("example.com:0",
  11210. detail::make_host_and_port_string("example.com", 0, false));
  11211. EXPECT_EQ("example.com:-1",
  11212. detail::make_host_and_port_string("example.com", -1, false));
  11213. EXPECT_EQ("example.com:65535",
  11214. detail::make_host_and_port_string("example.com", 65535, false));
  11215. EXPECT_EQ("example.com:65536",
  11216. detail::make_host_and_port_string("example.com", 65536, false));
  11217. }
  11218. #ifdef CPPHTTPLIB_SSL_ENABLED
  11219. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11220. httplib::SSLClient cli("roblox.com", 443);
  11221. cli.set_follow_location(true);
  11222. auto res = cli.Get("/");
  11223. ASSERT_TRUE(res);
  11224. EXPECT_EQ(StatusCode::OK_200, res->status);
  11225. }
  11226. #endif
  11227. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11228. Server svr;
  11229. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11230. EXPECT_EQ(res.status, 400);
  11231. });
  11232. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11233. auto se = detail::scope_exit([&] {
  11234. svr.stop();
  11235. thread.join();
  11236. ASSERT_FALSE(svr.is_running());
  11237. });
  11238. svr.wait_until_ready();
  11239. Client cli(HOST, PORT);
  11240. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11241. }
  11242. TEST(InvalidHeaderCharsTest, is_field_name) {
  11243. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11244. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11245. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11246. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11247. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11248. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11249. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11250. EXPECT_FALSE(detail::fields::is_field_name(""));
  11251. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11252. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11253. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11254. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11255. }
  11256. TEST(InvalidHeaderCharsTest, is_field_value) {
  11257. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11258. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11259. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11260. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11261. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11262. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11263. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11264. EXPECT_TRUE(detail::fields::is_field_value(""));
  11265. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11266. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11267. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11268. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11269. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11270. }
  11271. TEST(InvalidHeaderCharsTest, OnServer) {
  11272. Server svr;
  11273. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11274. std::string header = "Not Set";
  11275. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11276. res.set_header(header, "value");
  11277. res.set_content("Page Content Page Content", "text/plain");
  11278. });
  11279. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11280. std::string header = "Not Set";
  11281. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11282. res.set_header("X-Test", header);
  11283. res.set_content("Page Content Page Content", "text/plain");
  11284. });
  11285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11286. auto se = detail::scope_exit([&] {
  11287. svr.stop();
  11288. thread.join();
  11289. ASSERT_FALSE(svr.is_running());
  11290. });
  11291. svr.wait_until_ready();
  11292. Client cli(HOST, PORT);
  11293. {
  11294. auto res = cli.Get(
  11295. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11296. ASSERT_TRUE(res);
  11297. EXPECT_EQ("Page Content Page Content", res->body);
  11298. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11299. }
  11300. {
  11301. auto res = cli.Get(
  11302. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11303. ASSERT_TRUE(res);
  11304. EXPECT_EQ("Page Content Page Content", res->body);
  11305. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11306. }
  11307. }
  11308. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11309. auto handled = false;
  11310. Server svr;
  11311. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11312. thread t = thread([&] { svr.listen(HOST, PORT); });
  11313. auto se = detail::scope_exit([&] {
  11314. svr.stop();
  11315. t.join();
  11316. ASSERT_FALSE(svr.is_running());
  11317. ASSERT_FALSE(handled);
  11318. });
  11319. svr.wait_until_ready();
  11320. auto req = "POST /test HTTP/1.1\r\n"
  11321. "Content-Length: x\r\n"
  11322. "\r\n";
  11323. std::string response;
  11324. ASSERT_TRUE(send_request(1, req, &response));
  11325. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11326. response.substr(0, response.find("\r\n")));
  11327. }
  11328. #ifndef _WIN32
  11329. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11330. static constexpr char reject[] = "Unauthorized";
  11331. static constexpr char accept[] = "Upload accepted";
  11332. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11333. Server svr;
  11334. svr.set_expect_100_continue_handler(
  11335. [](const Request & /*req*/, Response &res) {
  11336. res.status = StatusCode::Unauthorized_401;
  11337. res.set_content(reject, "text/plain");
  11338. return res.status;
  11339. });
  11340. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11341. res.set_content(accept, "text/plain");
  11342. });
  11343. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11344. auto se = detail::scope_exit([&] {
  11345. svr.stop();
  11346. thread.join();
  11347. ASSERT_FALSE(svr.is_running());
  11348. });
  11349. svr.wait_until_ready();
  11350. {
  11351. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11352. curl_easy_init(), &curl_easy_cleanup};
  11353. ASSERT_NE(curl, nullptr);
  11354. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11355. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11356. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11357. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11358. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11359. &curl_slist_free_all};
  11360. ASSERT_NE(list, nullptr);
  11361. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11362. struct read_data {
  11363. size_t read_size;
  11364. size_t total_size;
  11365. } data = {0, total_size};
  11366. using read_callback_t =
  11367. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11368. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11369. void *userdata) -> size_t {
  11370. read_data *d = (read_data *)userdata;
  11371. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11372. std::fill_n(ptr, size * nmemb, 'A');
  11373. d->read_size += size * nmemb;
  11374. return size * nmemb;
  11375. };
  11376. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11377. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11378. std::vector<char> buffer;
  11379. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11380. using write_callback_t =
  11381. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11382. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11383. void *userdata) -> size_t {
  11384. std::vector<char> *buf = (std::vector<char> *)userdata;
  11385. buf->reserve(buf->size() + size * nmemb + 1);
  11386. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11387. return size * nmemb;
  11388. };
  11389. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11390. {
  11391. const auto res = curl_easy_perform(curl.get());
  11392. ASSERT_EQ(res, CURLE_OK);
  11393. }
  11394. {
  11395. auto response_code = long{};
  11396. const auto res =
  11397. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11398. ASSERT_EQ(res, CURLE_OK);
  11399. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11400. }
  11401. {
  11402. auto dl = curl_off_t{};
  11403. const auto res =
  11404. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11405. ASSERT_EQ(res, CURLE_OK);
  11406. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11407. }
  11408. {
  11409. buffer.push_back('\0');
  11410. ASSERT_STRCASEEQ(buffer.data(), reject);
  11411. }
  11412. }
  11413. }
  11414. #endif
  11415. template <typename S, typename C>
  11416. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11417. svr.Get("/stream", [&](const Request &, Response &res) {
  11418. auto data = new std::string("01234567890123456789");
  11419. res.set_content_provider(
  11420. data->size(), "text/plain",
  11421. [&, data](size_t offset, size_t length, DataSink &sink) {
  11422. const size_t DATA_CHUNK_SIZE = 4;
  11423. const auto &d = *data;
  11424. std::this_thread::sleep_for(std::chrono::seconds(1));
  11425. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11426. return true;
  11427. },
  11428. [data](bool success) {
  11429. EXPECT_FALSE(success);
  11430. delete data;
  11431. });
  11432. });
  11433. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11434. auto i = new size_t(0);
  11435. res.set_content_provider(
  11436. "text/plain",
  11437. [i](size_t, DataSink &sink) {
  11438. if (*i < 5) {
  11439. std::this_thread::sleep_for(std::chrono::seconds(1));
  11440. sink.write("abcd", 4);
  11441. (*i)++;
  11442. } else {
  11443. sink.done();
  11444. }
  11445. return true;
  11446. },
  11447. [i](bool success) {
  11448. EXPECT_FALSE(success);
  11449. delete i;
  11450. });
  11451. });
  11452. svr.Get("/chunked", [&](const Request &, Response &res) {
  11453. auto i = new size_t(0);
  11454. res.set_chunked_content_provider(
  11455. "text/plain",
  11456. [i](size_t, DataSink &sink) {
  11457. if (*i < 5) {
  11458. std::this_thread::sleep_for(std::chrono::seconds(1));
  11459. sink.os << "abcd";
  11460. (*i)++;
  11461. } else {
  11462. sink.done();
  11463. }
  11464. return true;
  11465. },
  11466. [i](bool success) {
  11467. EXPECT_FALSE(success);
  11468. delete i;
  11469. });
  11470. });
  11471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11472. auto se = detail::scope_exit([&] {
  11473. svr.stop();
  11474. listen_thread.join();
  11475. ASSERT_FALSE(svr.is_running());
  11476. });
  11477. svr.wait_until_ready();
  11478. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11479. {
  11480. auto start = std::chrono::steady_clock::now();
  11481. auto res = cli.Get("/stream");
  11482. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11483. std::chrono::steady_clock::now() - start)
  11484. .count();
  11485. ASSERT_FALSE(res);
  11486. EXPECT_EQ(Error::Read, res.error());
  11487. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11488. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11489. }
  11490. {
  11491. auto start = std::chrono::steady_clock::now();
  11492. auto res = cli.Get("/stream_without_length");
  11493. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11494. std::chrono::steady_clock::now() - start)
  11495. .count();
  11496. ASSERT_FALSE(res);
  11497. EXPECT_EQ(Error::Read, res.error());
  11498. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11499. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11500. }
  11501. {
  11502. auto start = std::chrono::steady_clock::now();
  11503. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11504. EXPECT_EQ("abcd", string(data, data_length));
  11505. return true;
  11506. });
  11507. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11508. std::chrono::steady_clock::now() - start)
  11509. .count();
  11510. ASSERT_FALSE(res);
  11511. EXPECT_EQ(Error::Read, res.error());
  11512. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11513. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11514. }
  11515. }
  11516. TEST(MaxTimeoutTest, ContentStream) {
  11517. time_t timeout = 2000;
  11518. time_t threshold = 200;
  11519. Server svr;
  11520. Client cli("localhost", PORT);
  11521. max_timeout_test(svr, cli, timeout, threshold);
  11522. }
  11523. #ifdef CPPHTTPLIB_SSL_ENABLED
  11524. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11525. time_t timeout = 2000;
  11526. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11528. SSLClient cli("localhost", PORT);
  11529. cli.enable_server_certificate_verification(false);
  11530. max_timeout_test(svr, cli, timeout, threshold);
  11531. }
  11532. #endif
  11533. class EventDispatcher {
  11534. public:
  11535. EventDispatcher() {}
  11536. bool wait_event(DataSink *sink) {
  11537. unique_lock<mutex> lk(m_);
  11538. int id = id_;
  11539. // Wait with timeout to prevent hanging if client disconnects
  11540. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11541. [&] { return cid_ == id; })) {
  11542. return false; // Timeout occurred
  11543. }
  11544. sink->write(message_.data(), message_.size());
  11545. return true;
  11546. }
  11547. void send_event(const string &message) {
  11548. lock_guard<mutex> lk(m_);
  11549. cid_ = id_++;
  11550. message_ = message;
  11551. cv_.notify_all();
  11552. }
  11553. private:
  11554. mutex m_;
  11555. condition_variable cv_;
  11556. atomic_int id_{0};
  11557. atomic_int cid_{-1};
  11558. string message_;
  11559. };
  11560. TEST(ClientInThreadTest, Issue2068) {
  11561. EventDispatcher ed;
  11562. Server svr;
  11563. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11564. res.set_chunked_content_provider("text/event-stream",
  11565. [&](size_t /*offset*/, DataSink &sink) {
  11566. return ed.wait_event(&sink);
  11567. });
  11568. });
  11569. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11570. svr.wait_until_ready();
  11571. thread event_thread([&] {
  11572. int id = 0;
  11573. while (svr.is_running()) {
  11574. this_thread::sleep_for(chrono::milliseconds(500));
  11575. std::stringstream ss;
  11576. ss << "data: " << id << "\n\n";
  11577. ed.send_event(ss.str());
  11578. id++;
  11579. }
  11580. });
  11581. auto se = detail::scope_exit([&] {
  11582. svr.stop();
  11583. listen_thread.join();
  11584. event_thread.join();
  11585. ASSERT_FALSE(svr.is_running());
  11586. });
  11587. {
  11588. auto client = detail::make_unique<Client>(HOST, PORT);
  11589. client->set_read_timeout(std::chrono::minutes(10));
  11590. std::atomic<bool> stop{false};
  11591. std::thread t([&] {
  11592. client->Get("/event1",
  11593. [&](const char *, size_t) -> bool { return !stop; });
  11594. });
  11595. std::this_thread::sleep_for(std::chrono::seconds(2));
  11596. stop = true;
  11597. client->stop();
  11598. t.join();
  11599. // Reset client after thread has finished
  11600. client.reset();
  11601. }
  11602. }
  11603. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11604. auto handled = false;
  11605. Server svr;
  11606. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11608. auto se = detail::scope_exit([&] {
  11609. svr.stop();
  11610. t.join();
  11611. ASSERT_FALSE(svr.is_running());
  11612. ASSERT_FALSE(handled);
  11613. });
  11614. svr.wait_until_ready();
  11615. // Two Content-Length headers with different values — must be rejected
  11616. auto req = "POST /test HTTP/1.1\r\n"
  11617. "Content-Length: 5\r\n"
  11618. "Content-Length: 10\r\n"
  11619. "\r\n"
  11620. "hello";
  11621. std::string response;
  11622. ASSERT_TRUE(send_request(1, req, &response));
  11623. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11624. response.substr(0, response.find("\r\n")));
  11625. }
  11626. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11627. auto handled = false;
  11628. Server svr;
  11629. svr.Post("/test", [&](const Request &, Response &res) {
  11630. handled = true;
  11631. res.set_content("ok", "text/plain");
  11632. });
  11633. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11634. auto se = detail::scope_exit([&] {
  11635. svr.stop();
  11636. t.join();
  11637. ASSERT_FALSE(svr.is_running());
  11638. ASSERT_TRUE(handled);
  11639. });
  11640. svr.wait_until_ready();
  11641. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11642. auto req = "POST /test HTTP/1.1\r\n"
  11643. "Content-Length: 5\r\n"
  11644. "Content-Length: 5\r\n"
  11645. "\r\n"
  11646. "hello";
  11647. std::string response;
  11648. ASSERT_TRUE(send_request(1, req, &response));
  11649. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11650. }
  11651. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11652. Server svr;
  11653. svr.Get("/", [](const Request &req, Response &res) {
  11654. EXPECT_EQ(2U, req.trailers.size());
  11655. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11656. // Denied
  11657. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11658. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11659. // Accepted
  11660. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11661. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11662. EXPECT_TRUE(req.has_trailer("X-World"));
  11663. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11664. res.set_content("ok", "text/plain");
  11665. });
  11666. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11667. auto se = detail::scope_exit([&] {
  11668. svr.stop();
  11669. t.join();
  11670. ASSERT_FALSE(svr.is_running());
  11671. });
  11672. svr.wait_until_ready();
  11673. const std::string req = "GET / HTTP/1.1\r\n"
  11674. "Transfer-Encoding: chunked\r\n"
  11675. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11676. "\r\n"
  11677. "0\r\n"
  11678. "Content-Length: 10\r\n"
  11679. "Host: internal.local\r\n"
  11680. "Content-Type: malicious/content\r\n"
  11681. "Cookie: any\r\n"
  11682. "Set-Cookie: any\r\n"
  11683. "X-Forwarded-For: attacker.com\r\n"
  11684. "X-Real-Ip: 1.1.1.1\r\n"
  11685. "X-Hello: hello\r\n"
  11686. "X-World: world\r\n"
  11687. "\r\n";
  11688. std::string res;
  11689. ASSERT_TRUE(send_request(1, req, &res));
  11690. }
  11691. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11692. Server svr;
  11693. std::string observed_remote_addr;
  11694. std::string observed_xff;
  11695. svr.Get("/ip", [&](const Request &req, Response &res) {
  11696. observed_remote_addr = req.remote_addr;
  11697. observed_xff = req.get_header_value("X-Forwarded-For");
  11698. res.set_content("ok", "text/plain");
  11699. });
  11700. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11701. auto se = detail::scope_exit([&] {
  11702. svr.stop();
  11703. t.join();
  11704. ASSERT_FALSE(svr.is_running());
  11705. });
  11706. svr.wait_until_ready();
  11707. Client cli(HOST, PORT);
  11708. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11709. ASSERT_TRUE(res);
  11710. EXPECT_EQ(StatusCode::OK_200, res->status);
  11711. EXPECT_EQ(observed_xff, "203.0.113.66");
  11712. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11713. observed_remote_addr == "127.0.0.1");
  11714. }
  11715. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11716. Server svr;
  11717. svr.set_trusted_proxies({"203.0.113.66"});
  11718. std::string observed_remote_addr;
  11719. std::string observed_xff;
  11720. svr.Get("/ip", [&](const Request &req, Response &res) {
  11721. observed_remote_addr = req.remote_addr;
  11722. observed_xff = req.get_header_value("X-Forwarded-For");
  11723. res.set_content("ok", "text/plain");
  11724. });
  11725. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11726. auto se = detail::scope_exit([&] {
  11727. svr.stop();
  11728. t.join();
  11729. ASSERT_FALSE(svr.is_running());
  11730. });
  11731. svr.wait_until_ready();
  11732. Client cli(HOST, PORT);
  11733. auto res = cli.Get("/ip");
  11734. ASSERT_TRUE(res);
  11735. EXPECT_EQ(StatusCode::OK_200, res->status);
  11736. EXPECT_EQ(observed_xff, "");
  11737. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11738. observed_remote_addr == "127.0.0.1");
  11739. }
  11740. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11741. Server svr;
  11742. svr.set_trusted_proxies({"203.0.113.66"});
  11743. std::string observed_remote_addr;
  11744. std::string observed_xff;
  11745. svr.Get("/ip", [&](const Request &req, Response &res) {
  11746. observed_remote_addr = req.remote_addr;
  11747. observed_xff = req.get_header_value("X-Forwarded-For");
  11748. res.set_content("ok", "text/plain");
  11749. });
  11750. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11751. auto se = detail::scope_exit([&] {
  11752. svr.stop();
  11753. t.join();
  11754. ASSERT_FALSE(svr.is_running());
  11755. });
  11756. svr.wait_until_ready();
  11757. Client cli(HOST, PORT);
  11758. auto res =
  11759. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11760. ASSERT_TRUE(res);
  11761. EXPECT_EQ(StatusCode::OK_200, res->status);
  11762. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11763. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11764. }
  11765. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11766. Server svr;
  11767. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11768. std::string observed_remote_addr;
  11769. std::string observed_xff;
  11770. svr.Get("/ip", [&](const Request &req, Response &res) {
  11771. observed_remote_addr = req.remote_addr;
  11772. observed_xff = req.get_header_value("X-Forwarded-For");
  11773. res.set_content("ok", "text/plain");
  11774. });
  11775. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11776. auto se = detail::scope_exit([&] {
  11777. svr.stop();
  11778. t.join();
  11779. ASSERT_FALSE(svr.is_running());
  11780. });
  11781. svr.wait_until_ready();
  11782. Client cli(HOST, PORT);
  11783. auto res = cli.Get(
  11784. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11785. ASSERT_TRUE(res);
  11786. EXPECT_EQ(StatusCode::OK_200, res->status);
  11787. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11788. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11789. }
  11790. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11791. Server svr;
  11792. svr.set_trusted_proxies({"192.0.2.45"});
  11793. std::string observed_remote_addr;
  11794. std::string observed_xff;
  11795. svr.Get("/ip", [&](const Request &req, Response &res) {
  11796. observed_remote_addr = req.remote_addr;
  11797. observed_xff = req.get_header_value("X-Forwarded-For");
  11798. res.set_content("ok", "text/plain");
  11799. });
  11800. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11801. auto se = detail::scope_exit([&] {
  11802. svr.stop();
  11803. t.join();
  11804. ASSERT_FALSE(svr.is_running());
  11805. });
  11806. svr.wait_until_ready();
  11807. Client cli(HOST, PORT);
  11808. auto res =
  11809. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11810. ASSERT_TRUE(res);
  11811. EXPECT_EQ(StatusCode::OK_200, res->status);
  11812. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11813. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11814. }
  11815. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11816. Server svr;
  11817. svr.set_trusted_proxies({"192.0.2.45"});
  11818. std::string observed_remote_addr;
  11819. std::string observed_xff;
  11820. svr.Get("/ip", [&](const Request &req, Response &res) {
  11821. observed_remote_addr = req.remote_addr;
  11822. observed_xff = req.get_header_value("X-Forwarded-For");
  11823. res.set_content("ok", "text/plain");
  11824. });
  11825. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11826. auto se = detail::scope_exit([&] {
  11827. svr.stop();
  11828. t.join();
  11829. ASSERT_FALSE(svr.is_running());
  11830. });
  11831. svr.wait_until_ready();
  11832. Client cli(HOST, PORT);
  11833. auto res = cli.Get(
  11834. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11835. ASSERT_TRUE(res);
  11836. EXPECT_EQ(StatusCode::OK_200, res->status);
  11837. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11838. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11839. }
  11840. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11841. Server svr;
  11842. svr.set_trusted_proxies({"192.0.2.45"});
  11843. std::string observed_remote_addr;
  11844. std::string observed_xff;
  11845. svr.Get("/ip", [&](const Request &req, Response &res) {
  11846. observed_remote_addr = req.remote_addr;
  11847. observed_xff = req.get_header_value("X-Forwarded-For");
  11848. res.set_content("ok", "text/plain");
  11849. });
  11850. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11851. auto se = detail::scope_exit([&] {
  11852. svr.stop();
  11853. t.join();
  11854. ASSERT_FALSE(svr.is_running());
  11855. });
  11856. svr.wait_until_ready();
  11857. std::string raw_req =
  11858. "GET /ip HTTP/1.1\r\n"
  11859. "Host: localhost\r\n"
  11860. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11861. "Connection: close\r\n"
  11862. "\r\n";
  11863. std::string out;
  11864. ASSERT_TRUE(send_request(5, raw_req, &out));
  11865. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11866. // Header parser trims surrounding whitespace of the header value
  11867. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11868. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11869. }
  11870. // An X-Forwarded-For header whose value parses to zero IP segments must not
  11871. // crash the server (it used to call front() on an empty vector inside
  11872. // get_client_ip). The connection-level remote address must be retained instead.
  11873. static void run_malformed_xff_test(const std::string &xff_value) {
  11874. Server svr;
  11875. svr.set_trusted_proxies({"192.0.2.45"});
  11876. std::string observed_remote_addr;
  11877. svr.Get("/ip", [&](const Request &req, Response &res) {
  11878. observed_remote_addr = req.remote_addr;
  11879. res.set_content("ok", "text/plain");
  11880. });
  11881. int port = 0;
  11882. thread t = thread([&]() {
  11883. port = svr.bind_to_any_port(HOST);
  11884. svr.listen_after_bind();
  11885. });
  11886. auto se = detail::scope_exit([&] {
  11887. svr.stop();
  11888. t.join();
  11889. ASSERT_FALSE(svr.is_running());
  11890. });
  11891. svr.wait_until_ready();
  11892. Client cli(HOST, port);
  11893. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  11894. ASSERT_TRUE(res);
  11895. EXPECT_EQ(StatusCode::OK_200, res->status);
  11896. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11897. observed_remote_addr == "127.0.0.1");
  11898. }
  11899. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  11900. run_malformed_xff_test("");
  11901. }
  11902. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  11903. run_malformed_xff_test(",");
  11904. }
  11905. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  11906. run_malformed_xff_test(", , ,");
  11907. }
  11908. #ifndef _WIN32
  11909. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11910. Server svr;
  11911. svr.Post("/post", [&](const Request &req, Response &res) {
  11912. res.set_content(req.body, "text/plain");
  11913. });
  11914. svr.Put("/put", [&](const Request &req, Response &res) {
  11915. res.set_content(req.body, "text/plain");
  11916. });
  11917. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11918. res.set_content(req.body, "text/plain");
  11919. });
  11920. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11921. res.set_content(req.body, "text/plain");
  11922. });
  11923. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11924. auto se = detail::scope_exit([&] {
  11925. svr.stop();
  11926. t.join();
  11927. ASSERT_FALSE(svr.is_running());
  11928. });
  11929. svr.wait_until_ready();
  11930. std::string resp;
  11931. // POST without Content-Length
  11932. ASSERT_TRUE(send_request(5,
  11933. "POST /post HTTP/1.1\r\n"
  11934. "Host: localhost\r\n"
  11935. "Connection: close\r\n"
  11936. "\r\n",
  11937. &resp));
  11938. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11939. // PUT without Content-Length
  11940. resp.clear();
  11941. ASSERT_TRUE(send_request(5,
  11942. "PUT /put HTTP/1.1\r\n"
  11943. "Host: localhost\r\n"
  11944. "Connection: close\r\n"
  11945. "\r\n",
  11946. &resp));
  11947. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11948. // PATCH without Content-Length
  11949. resp.clear();
  11950. ASSERT_TRUE(send_request(5,
  11951. "PATCH /patch HTTP/1.1\r\n"
  11952. "Host: localhost\r\n"
  11953. "Connection: close\r\n"
  11954. "\r\n",
  11955. &resp));
  11956. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11957. // DELETE without Content-Length
  11958. resp.clear();
  11959. ASSERT_TRUE(send_request(5,
  11960. "DELETE /delete HTTP/1.1\r\n"
  11961. "Host: localhost\r\n"
  11962. "Connection: close\r\n"
  11963. "\r\n",
  11964. &resp));
  11965. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11966. }
  11967. #endif
  11968. //==============================================================================
  11969. // open_stream() Tests
  11970. //==============================================================================
  11971. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11972. std::string result;
  11973. char buf[8192];
  11974. ssize_t n;
  11975. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11976. result.append(buf, static_cast<size_t>(n));
  11977. }
  11978. return result;
  11979. }
  11980. // Mock stream for unit tests
  11981. class MockStream : public Stream {
  11982. public:
  11983. std::string data;
  11984. size_t pos = 0;
  11985. ssize_t error_after = -1; // -1 = no error
  11986. explicit MockStream(const std::string &d, ssize_t err = -1)
  11987. : data(d), error_after(err) {}
  11988. bool is_readable() const override { return true; }
  11989. bool wait_readable() const override { return true; }
  11990. bool wait_writable() const override { return true; }
  11991. ssize_t read(char *ptr, size_t size) override {
  11992. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11993. if (pos >= data.size()) return 0;
  11994. size_t limit =
  11995. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11996. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11997. std::memcpy(ptr, data.data() + pos, to_read);
  11998. pos += to_read;
  11999. return static_cast<ssize_t>(to_read);
  12000. }
  12001. ssize_t write(const char *, size_t) override { return -1; }
  12002. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12003. ip = "127.0.0.1";
  12004. port = 0;
  12005. }
  12006. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12007. ip = "127.0.0.1";
  12008. port = 0;
  12009. }
  12010. socket_t socket() const override { return INVALID_SOCKET; }
  12011. time_t duration() const override { return 0; }
  12012. };
  12013. TEST(StreamHandleTest, Basic) {
  12014. ClientImpl::StreamHandle handle;
  12015. EXPECT_FALSE(handle.is_valid());
  12016. handle.response = detail::make_unique<Response>();
  12017. handle.error = Error::Connection;
  12018. EXPECT_FALSE(handle.is_valid());
  12019. handle.error = Error::Success;
  12020. EXPECT_TRUE(handle.is_valid());
  12021. }
  12022. TEST(BodyReaderTest, Basic) {
  12023. MockStream stream("Hello, World!");
  12024. detail::BodyReader reader;
  12025. reader.stream = &stream;
  12026. reader.content_length = 13;
  12027. char buf[32];
  12028. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12029. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12030. EXPECT_TRUE(reader.eof);
  12031. }
  12032. TEST(BodyReaderTest, NoStream) {
  12033. detail::BodyReader reader;
  12034. char buf[32];
  12035. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12036. EXPECT_EQ(Error::Connection, reader.last_error);
  12037. }
  12038. TEST(BodyReaderTest, Error) {
  12039. MockStream stream("Hello, World!", 5);
  12040. detail::BodyReader reader;
  12041. reader.stream = &stream;
  12042. reader.content_length = 13;
  12043. char buf[32];
  12044. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12045. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12046. EXPECT_EQ(Error::Read, reader.last_error);
  12047. }
  12048. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12049. // Mock-based StreamHandle tests relying on private internals are removed.
  12050. class OpenStreamTest : public ::testing::Test {
  12051. protected:
  12052. void SetUp() override {
  12053. svr_.Get("/hello", [](const Request &, Response &res) {
  12054. res.set_content("Hello World!", "text/plain");
  12055. });
  12056. svr_.Get("/large", [](const Request &, Response &res) {
  12057. res.set_content(std::string(10000, 'X'), "text/plain");
  12058. });
  12059. svr_.Get("/chunked", [](const Request &, Response &res) {
  12060. res.set_chunked_content_provider("text/plain",
  12061. [](size_t offset, DataSink &sink) {
  12062. if (offset < 15) {
  12063. sink.write("chunk", 5);
  12064. return true;
  12065. }
  12066. sink.done();
  12067. return true;
  12068. });
  12069. });
  12070. svr_.Get("/compressible", [](const Request &, Response &res) {
  12071. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12072. DataSink &sink) {
  12073. if (offset < 100 * 1024) {
  12074. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12075. sink.write(chunk.data(), chunk.size());
  12076. return true;
  12077. }
  12078. sink.done();
  12079. return true;
  12080. });
  12081. });
  12082. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12083. [](const Request & /*req*/, Response &res) {
  12084. auto i = new int(0);
  12085. res.set_header("Trailer", "Content-Length, X-Allowed");
  12086. res.set_chunked_content_provider(
  12087. "text/plain",
  12088. [i](size_t /*offset*/, DataSink &sink) {
  12089. switch (*i) {
  12090. case 0: sink.os << "123"; break;
  12091. case 1: sink.os << "456"; break;
  12092. case 2: sink.os << "789"; break;
  12093. case 3: {
  12094. sink.done_with_trailer(
  12095. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12096. } break;
  12097. }
  12098. (*i)++;
  12099. return true;
  12100. },
  12101. [i](bool success) {
  12102. EXPECT_TRUE(success);
  12103. delete i;
  12104. });
  12105. });
  12106. // Echo headers endpoint for header-related tests
  12107. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12108. std::string body;
  12109. for (const auto &h : req.headers) {
  12110. body.append(h.first);
  12111. body.push_back(':');
  12112. body.append(h.second);
  12113. body.push_back('\n');
  12114. }
  12115. res.set_content(body, "text/plain");
  12116. });
  12117. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12118. std::string body;
  12119. for (const auto &h : req.headers) {
  12120. body.append(h.first);
  12121. body.push_back(':');
  12122. body.append(h.second);
  12123. body.push_back('\n');
  12124. }
  12125. res.set_content(body, "text/plain");
  12126. });
  12127. port_ = svr_.bind_to_any_port("127.0.0.1");
  12128. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12129. svr_.wait_until_ready();
  12130. }
  12131. void TearDown() override {
  12132. svr_.stop();
  12133. if (thread_.joinable()) thread_.join();
  12134. }
  12135. Server svr_;
  12136. std::thread thread_;
  12137. int port_ = 0;
  12138. };
  12139. TEST_F(OpenStreamTest, Basic) {
  12140. Client cli("127.0.0.1", port_);
  12141. auto handle = cli.open_stream("GET", "/hello");
  12142. EXPECT_TRUE(handle.is_valid());
  12143. EXPECT_EQ("Hello World!", read_all(handle));
  12144. }
  12145. TEST_F(OpenStreamTest, SmallBuffer) {
  12146. Client cli("127.0.0.1", port_);
  12147. auto handle = cli.open_stream("GET", "/hello");
  12148. std::string result;
  12149. char buf[4];
  12150. ssize_t n;
  12151. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12152. result.append(buf, static_cast<size_t>(n));
  12153. EXPECT_EQ("Hello World!", result);
  12154. }
  12155. TEST_F(OpenStreamTest, DefaultHeaders) {
  12156. Client cli("127.0.0.1", port_);
  12157. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12158. {
  12159. auto handle = cli.open_stream("GET", "/echo-headers");
  12160. ASSERT_TRUE(handle.is_valid());
  12161. auto body = read_all(handle);
  12162. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12163. std::string::npos);
  12164. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12165. std::string::npos);
  12166. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12167. }
  12168. // open_stream POST with body and no explicit content_type should NOT add
  12169. // text/plain Content-Type (behavior differs from non-streaming path), but
  12170. // should include Content-Length
  12171. {
  12172. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12173. ASSERT_TRUE(handle.is_valid());
  12174. auto body = read_all(handle);
  12175. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12176. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12177. }
  12178. // open_stream POST with explicit Content-Type should preserve it
  12179. {
  12180. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12181. {{"Content-Type", "application/custom"}},
  12182. "{}", "application/custom");
  12183. ASSERT_TRUE(handle.is_valid());
  12184. auto body = read_all(handle);
  12185. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12186. }
  12187. // User-specified User-Agent must not be overwritten for stream API
  12188. {
  12189. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12190. {{"User-Agent", "MyAgent/1.2"}});
  12191. ASSERT_TRUE(handle.is_valid());
  12192. auto body = read_all(handle);
  12193. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12194. }
  12195. }
  12196. TEST_F(OpenStreamTest, Large) {
  12197. Client cli("127.0.0.1", port_);
  12198. auto handle = cli.open_stream("GET", "/large");
  12199. EXPECT_EQ(10000u, read_all(handle).size());
  12200. }
  12201. TEST_F(OpenStreamTest, ConnectionError) {
  12202. Client cli("127.0.0.1", 9999);
  12203. auto handle = cli.open_stream("GET", "/hello");
  12204. EXPECT_FALSE(handle.is_valid());
  12205. }
  12206. TEST_F(OpenStreamTest, Chunked) {
  12207. Client cli("127.0.0.1", port_);
  12208. auto handle = cli.open_stream("GET", "/chunked");
  12209. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12210. "Transfer-Encoding") == "chunked");
  12211. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12212. }
  12213. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12214. Client cli("127.0.0.1", port_);
  12215. auto handle =
  12216. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12217. ASSERT_TRUE(handle.is_valid());
  12218. // Consume body to allow trailers to be received/parsed
  12219. auto body = read_all(handle);
  12220. // Explicitly parse trailers (ensure trailers are available for assertion)
  12221. handle.parse_trailers_if_needed();
  12222. EXPECT_EQ(std::string("123456789"), body);
  12223. // The response should include a Trailer header declaring both names
  12224. ASSERT_TRUE(handle.response);
  12225. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12226. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12227. handle.response->get_header_value("Trailer"));
  12228. // Prohibited trailer must not be present
  12229. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12230. // Allowed trailer should be present
  12231. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12232. EXPECT_EQ(std::string("yes"),
  12233. handle.response->get_trailer_value("X-Allowed"));
  12234. // Verify trailers are NOT present as regular headers
  12235. EXPECT_EQ(std::string(""),
  12236. handle.response->get_header_value("Content-Length"));
  12237. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12238. }
  12239. static std::thread serve_single_response(std::promise<int> &port_promise,
  12240. const std::string &response) {
  12241. return std::thread([&port_promise, response] {
  12242. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12243. default_socket_options(srv);
  12244. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12245. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12246. sockaddr_in addr{};
  12247. addr.sin_family = AF_INET;
  12248. addr.sin_port = htons(0); // Let OS assign a free port
  12249. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12250. int opt = 1;
  12251. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12252. #ifdef _WIN32
  12253. reinterpret_cast<const char *>(&opt),
  12254. #else
  12255. &opt,
  12256. #endif
  12257. sizeof(opt));
  12258. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12259. ::listen(srv, 1) != 0) {
  12260. port_promise.set_value(-1);
  12261. detail::close_socket(srv);
  12262. return;
  12263. }
  12264. socklen_t addr_len = sizeof(addr);
  12265. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12266. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12267. sockaddr_in cli_addr{};
  12268. socklen_t cli_len = sizeof(cli_addr);
  12269. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12270. if (cli != INVALID_SOCKET) {
  12271. // Read the complete HTTP request (until the blank line that terminates
  12272. // headers) before sending the response. If the server closes the socket
  12273. // while the client's request data is still unread in the kernel receive
  12274. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12275. // connection on both sides: it discards the client's receive buffer
  12276. // (which already holds our response) and causes any in-progress write on
  12277. // the client to fail with ECONNRESET. Reading all request data first
  12278. // ensures close() emits a graceful FIN.
  12279. {
  12280. char rbuf[256];
  12281. std::string req;
  12282. while (req.find("\r\n\r\n") == std::string::npos) {
  12283. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12284. if (n <= 0) { break; }
  12285. req.append(rbuf, static_cast<size_t>(n));
  12286. }
  12287. }
  12288. ::send(cli,
  12289. #ifdef _WIN32
  12290. static_cast<const char *>(response.c_str()),
  12291. static_cast<int>(response.size()),
  12292. #else
  12293. response.c_str(), response.size(),
  12294. #endif
  12295. 0);
  12296. detail::close_socket(cli);
  12297. }
  12298. detail::close_socket(srv);
  12299. });
  12300. }
  12301. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12302. #ifndef _WIN32
  12303. signal(SIGPIPE, SIG_IGN);
  12304. #endif
  12305. std::promise<int> port_promise;
  12306. auto port_future = port_promise.get_future();
  12307. auto server_thread =
  12308. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12309. "Content-Type: text/plain\r\n"
  12310. "Content-Length: not-a-number\r\n"
  12311. "Connection: close\r\n"
  12312. "\r\n"
  12313. "hello");
  12314. auto port = port_future.get();
  12315. ASSERT_GT(port, 0);
  12316. Client cli("127.0.0.1", port);
  12317. auto handle = cli.open_stream("GET", "/");
  12318. EXPECT_FALSE(handle.is_valid());
  12319. server_thread.join();
  12320. }
  12321. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12322. #ifndef _WIN32
  12323. signal(SIGPIPE, SIG_IGN);
  12324. #endif
  12325. std::promise<int> port_promise;
  12326. auto port_future = port_promise.get_future();
  12327. auto server_thread = serve_single_response(
  12328. port_promise, "HTTP/1.1 200 OK\r\n"
  12329. "Content-Type: text/plain\r\n"
  12330. "Content-Length: 99999999999999999999999999\r\n"
  12331. "Connection: close\r\n"
  12332. "\r\n"
  12333. "hello");
  12334. auto port = port_future.get();
  12335. ASSERT_GT(port, 0);
  12336. // Before the fix, std::stoull would throw std::out_of_range here and
  12337. // crash the process. After the fix, strtoull silently clamps to
  12338. // ULLONG_MAX so the stream opens without crashing. The important thing
  12339. // is that the process does NOT terminate.
  12340. Client cli("127.0.0.1", port);
  12341. auto handle = cli.open_stream("GET", "/");
  12342. EXPECT_TRUE(handle.is_valid());
  12343. server_thread.join();
  12344. }
  12345. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12346. TEST_F(OpenStreamTest, Gzip) {
  12347. Client cli("127.0.0.1", port_);
  12348. auto handle = cli.open_stream("GET", "/compressible", {},
  12349. {{"Accept-Encoding", "gzip"}});
  12350. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12351. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12352. }
  12353. #endif
  12354. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12355. TEST_F(OpenStreamTest, Brotli) {
  12356. Client cli("127.0.0.1", port_);
  12357. auto handle =
  12358. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12359. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12360. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12361. }
  12362. #endif
  12363. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12364. TEST_F(OpenStreamTest, Zstd) {
  12365. Client cli("127.0.0.1", port_);
  12366. auto handle = cli.open_stream("GET", "/compressible", {},
  12367. {{"Accept-Encoding", "zstd"}});
  12368. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12369. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12370. }
  12371. #endif
  12372. #ifdef CPPHTTPLIB_SSL_ENABLED
  12373. class SSLOpenStreamTest : public ::testing::Test {
  12374. protected:
  12375. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12376. void SetUp() override {
  12377. svr_.Get("/hello", [](const Request &, Response &res) {
  12378. res.set_content("Hello SSL World!", "text/plain");
  12379. });
  12380. svr_.Get("/chunked", [](const Request &, Response &res) {
  12381. res.set_chunked_content_provider("text/plain",
  12382. [](size_t offset, DataSink &sink) {
  12383. if (offset < 15) {
  12384. sink.write("chunk", 5);
  12385. return true;
  12386. }
  12387. sink.done();
  12388. return true;
  12389. });
  12390. });
  12391. svr_.Post("/echo", [](const Request &req, Response &res) {
  12392. res.set_content(req.body, req.get_header_value("Content-Type"));
  12393. });
  12394. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12395. std::string body = req.body;
  12396. res.set_chunked_content_provider(
  12397. "text/plain", [body](size_t offset, DataSink &sink) {
  12398. if (offset < body.size()) {
  12399. sink.write(body.data() + offset, body.size() - offset);
  12400. }
  12401. sink.done();
  12402. return true;
  12403. });
  12404. });
  12405. port_ = svr_.bind_to_any_port("127.0.0.1");
  12406. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12407. svr_.wait_until_ready();
  12408. }
  12409. void TearDown() override {
  12410. svr_.stop();
  12411. if (thread_.joinable()) thread_.join();
  12412. }
  12413. SSLServer svr_;
  12414. std::thread thread_;
  12415. int port_ = 0;
  12416. };
  12417. TEST_F(SSLOpenStreamTest, Basic) {
  12418. SSLClient cli("127.0.0.1", port_);
  12419. cli.enable_server_certificate_verification(false);
  12420. auto handle = cli.open_stream("GET", "/hello");
  12421. ASSERT_TRUE(handle.is_valid());
  12422. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12423. }
  12424. TEST_F(SSLOpenStreamTest, Chunked) {
  12425. SSLClient cli("127.0.0.1", port_);
  12426. cli.enable_server_certificate_verification(false);
  12427. auto handle = cli.open_stream("GET", "/chunked");
  12428. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12429. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12430. "Transfer-Encoding") == "chunked");
  12431. auto body = read_all(handle);
  12432. EXPECT_EQ("chunkchunkchunk", body);
  12433. }
  12434. TEST_F(SSLOpenStreamTest, Post) {
  12435. SSLClient cli("127.0.0.1", port_);
  12436. cli.enable_server_certificate_verification(false);
  12437. auto handle =
  12438. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12439. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12440. EXPECT_EQ(200, handle.response->status);
  12441. auto body = read_all(handle);
  12442. EXPECT_EQ("Hello SSL POST", body);
  12443. }
  12444. TEST_F(SSLOpenStreamTest, PostChunked) {
  12445. SSLClient cli("127.0.0.1", port_);
  12446. cli.enable_server_certificate_verification(false);
  12447. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12448. "Chunked SSL Data", "text/plain");
  12449. ASSERT_TRUE(handle.is_valid());
  12450. EXPECT_EQ(200, handle.response->status);
  12451. auto body = read_all(handle);
  12452. EXPECT_EQ("Chunked SSL Data", body);
  12453. }
  12454. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12455. // Content-Length is terminated by the server closing the connection. When the
  12456. // SSL peer sends a close_notify after the body, the client must treat it as a
  12457. // clean EOF and return a successful response rather than an error.
  12458. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12460. ASSERT_TRUE(svr.is_valid());
  12461. svr.set_keep_alive_max_count(1);
  12462. const std::string expected_body = "Hello from connection-close response!";
  12463. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12464. res.set_content_provider("text/plain",
  12465. [&](size_t offset, DataSink &sink) -> bool {
  12466. if (offset < expected_body.size()) {
  12467. sink.write(expected_body.data() + offset,
  12468. expected_body.size() - offset);
  12469. }
  12470. sink.done();
  12471. return true;
  12472. });
  12473. });
  12474. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12475. auto se = detail::scope_exit([&] {
  12476. svr.stop();
  12477. listen_thread.join();
  12478. ASSERT_FALSE(svr.is_running());
  12479. });
  12480. svr.wait_until_ready();
  12481. SSLClient cli(HOST, PORT);
  12482. cli.enable_server_certificate_verification(false);
  12483. auto res = cli.Get("/no-content-length");
  12484. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12485. EXPECT_EQ(StatusCode::OK_200, res->status);
  12486. EXPECT_EQ(expected_body, res->body);
  12487. }
  12488. #endif // CPPHTTPLIB_SSL_ENABLED
  12489. //==============================================================================
  12490. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12491. // results for various scenarios.
  12492. //==============================================================================
  12493. TEST(ParityTest, GetVsOpenStream) {
  12494. Server svr;
  12495. const std::string path = "/parity";
  12496. const std::string content = "Parity test content: hello world";
  12497. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12498. res.set_content(content, "text/plain");
  12499. });
  12500. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12501. auto se = detail::scope_exit([&] {
  12502. svr.stop();
  12503. t.join();
  12504. ASSERT_FALSE(svr.is_running());
  12505. });
  12506. svr.wait_until_ready();
  12507. Client cli(HOST, PORT);
  12508. // Non-stream path
  12509. auto r1 = cli.Get(path);
  12510. ASSERT_TRUE(r1);
  12511. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12512. // Stream path
  12513. auto h = cli.open_stream("GET", path);
  12514. ASSERT_TRUE(h.is_valid());
  12515. EXPECT_EQ(r1->body, read_all(h));
  12516. }
  12517. // Helper to compress data with provided compressor type T
  12518. template <typename Compressor>
  12519. static std::string compress_payload_for_parity(const std::string &in) {
  12520. std::string out;
  12521. Compressor compressor;
  12522. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12523. [&](const char *data, size_t n) {
  12524. out.append(data, n);
  12525. return true;
  12526. });
  12527. EXPECT_TRUE(ok);
  12528. return out;
  12529. }
  12530. // Helper function for compression parity tests
  12531. template <typename Compressor>
  12532. static void test_compression_parity(const std::string &original,
  12533. const std::string &path,
  12534. const std::string &encoding) {
  12535. const std::string compressed =
  12536. compress_payload_for_parity<Compressor>(original);
  12537. Server svr;
  12538. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12539. res.set_content(compressed, "application/octet-stream");
  12540. res.set_header("Content-Encoding", encoding);
  12541. });
  12542. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12543. auto se = detail::scope_exit([&] {
  12544. svr.stop();
  12545. t.join();
  12546. ASSERT_FALSE(svr.is_running());
  12547. });
  12548. svr.wait_until_ready();
  12549. Client cli(HOST, PORT);
  12550. // Non-streaming
  12551. {
  12552. auto res = cli.Get(path);
  12553. ASSERT_TRUE(res);
  12554. EXPECT_EQ(StatusCode::OK_200, res->status);
  12555. EXPECT_EQ(original, res->body);
  12556. }
  12557. // Streaming
  12558. {
  12559. auto h = cli.open_stream("GET", path);
  12560. ASSERT_TRUE(h.is_valid());
  12561. EXPECT_EQ(original, read_all(h));
  12562. }
  12563. }
  12564. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12565. TEST(ParityTest, Gzip) {
  12566. test_compression_parity<detail::gzip_compressor>(
  12567. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12568. }
  12569. #endif
  12570. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12571. TEST(ParityTest, Brotli) {
  12572. test_compression_parity<detail::brotli_compressor>(
  12573. "Hello, brotli parity test payload", "/parity-br", "br");
  12574. }
  12575. #endif
  12576. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12577. TEST(ParityTest, Zstd) {
  12578. test_compression_parity<detail::zstd_compressor>(
  12579. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12580. }
  12581. #endif
  12582. //==============================================================================
  12583. // New Stream API Tests
  12584. //==============================================================================
  12585. inline std::string read_body(httplib::stream::Result &result) {
  12586. std::string body;
  12587. while (result.next()) {
  12588. body.append(result.data(), result.size());
  12589. }
  12590. return body;
  12591. }
  12592. TEST(ClientConnectionTest, Basic) {
  12593. httplib::ClientConnection conn;
  12594. EXPECT_FALSE(conn.is_open());
  12595. conn.sock = 1;
  12596. EXPECT_TRUE(conn.is_open());
  12597. httplib::ClientConnection conn2(std::move(conn));
  12598. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12599. conn2.sock = INVALID_SOCKET;
  12600. }
  12601. // Unified test server for all stream::* tests
  12602. class StreamApiTest : public ::testing::Test {
  12603. protected:
  12604. void SetUp() override {
  12605. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12606. res.set_content("Hello World!", "text/plain");
  12607. });
  12608. svr_.Get("/echo-params",
  12609. [](const httplib::Request &req, httplib::Response &res) {
  12610. std::string r;
  12611. for (const auto &p : req.params) {
  12612. if (!r.empty()) r += "&";
  12613. r += p.first + "=" + p.second;
  12614. }
  12615. res.set_content(r, "text/plain");
  12616. });
  12617. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12618. res.set_content(req.body, req.get_header_value("Content-Type"));
  12619. });
  12620. svr_.Post("/echo-headers",
  12621. [](const httplib::Request &req, httplib::Response &res) {
  12622. std::string r;
  12623. for (const auto &h : req.headers)
  12624. r += h.first + ": " + h.second + "\n";
  12625. res.set_content(r, "text/plain");
  12626. });
  12627. svr_.Post("/echo-params",
  12628. [](const httplib::Request &req, httplib::Response &res) {
  12629. std::string r = "params:";
  12630. for (const auto &p : req.params)
  12631. r += p.first + "=" + p.second + ";";
  12632. res.set_content(r + " body:" + req.body, "text/plain");
  12633. });
  12634. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12635. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12636. });
  12637. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12638. res.set_content("PUT:" + req.body, "text/plain");
  12639. });
  12640. svr_.Patch("/echo",
  12641. [](const httplib::Request &req, httplib::Response &res) {
  12642. res.set_content("PATCH:" + req.body, "text/plain");
  12643. });
  12644. svr_.Delete(
  12645. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12646. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12647. "text/plain");
  12648. });
  12649. svr_.Get("/head-test",
  12650. [](const httplib::Request &, httplib::Response &res) {
  12651. res.set_content("body for HEAD", "text/plain");
  12652. });
  12653. svr_.Options("/options",
  12654. [](const httplib::Request &, httplib::Response &res) {
  12655. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12656. });
  12657. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12658. svr_.wait_until_ready();
  12659. }
  12660. void TearDown() override {
  12661. svr_.stop();
  12662. if (thread_.joinable()) thread_.join();
  12663. }
  12664. httplib::Server svr_;
  12665. std::thread thread_;
  12666. };
  12667. // stream::Get tests
  12668. TEST_F(StreamApiTest, GetBasic) {
  12669. httplib::Client cli(HOST, PORT);
  12670. auto result = httplib::stream::Get(cli, "/hello");
  12671. ASSERT_TRUE(result.is_valid());
  12672. EXPECT_EQ(200, result.status());
  12673. EXPECT_EQ("Hello World!", read_body(result));
  12674. }
  12675. TEST_F(StreamApiTest, GetWithParams) {
  12676. httplib::Client cli(HOST, PORT);
  12677. httplib::Params params{{"foo", "bar"}};
  12678. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12679. ASSERT_TRUE(result.is_valid());
  12680. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12681. }
  12682. TEST_F(StreamApiTest, GetConnectionError) {
  12683. httplib::Client cli(HOST, 9999);
  12684. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12685. }
  12686. TEST_F(StreamApiTest, Get404) {
  12687. httplib::Client cli(HOST, PORT);
  12688. auto result = httplib::stream::Get(cli, "/nonexistent");
  12689. EXPECT_TRUE(result.is_valid());
  12690. EXPECT_EQ(404, result.status());
  12691. }
  12692. // stream::Post tests
  12693. TEST_F(StreamApiTest, PostBasic) {
  12694. httplib::Client cli(HOST, PORT);
  12695. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12696. "application/json");
  12697. ASSERT_TRUE(result.is_valid());
  12698. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12699. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12700. }
  12701. TEST_F(StreamApiTest, PostWithHeaders) {
  12702. httplib::Client cli(HOST, PORT);
  12703. httplib::Headers headers{{"X-Custom", "value"}};
  12704. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12705. "text/plain");
  12706. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12707. }
  12708. TEST_F(StreamApiTest, PostWithParams) {
  12709. httplib::Client cli(HOST, PORT);
  12710. httplib::Params params{{"k", "v"}};
  12711. auto result =
  12712. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12713. auto body = read_body(result);
  12714. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12715. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12716. }
  12717. TEST_F(StreamApiTest, PostLarge) {
  12718. httplib::Client cli(HOST, PORT);
  12719. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12720. size_t total = 0;
  12721. while (result.next()) {
  12722. total += result.size();
  12723. }
  12724. EXPECT_EQ(100u * 1024u, total);
  12725. }
  12726. // stream::Put/Patch tests
  12727. TEST_F(StreamApiTest, PutAndPatch) {
  12728. httplib::Client cli(HOST, PORT);
  12729. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12730. EXPECT_EQ("PUT:test", read_body(put));
  12731. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12732. EXPECT_EQ("PATCH:test", read_body(patch));
  12733. }
  12734. // stream::Delete tests
  12735. TEST_F(StreamApiTest, Delete) {
  12736. httplib::Client cli(HOST, PORT);
  12737. auto del1 = httplib::stream::Delete(cli, "/resource");
  12738. EXPECT_EQ("Deleted", read_body(del1));
  12739. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12740. EXPECT_EQ("Deleted:data", read_body(del2));
  12741. }
  12742. // stream::Head/Options tests
  12743. TEST_F(StreamApiTest, HeadAndOptions) {
  12744. httplib::Client cli(HOST, PORT);
  12745. auto head = httplib::stream::Head(cli, "/head-test");
  12746. EXPECT_TRUE(head.is_valid());
  12747. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12748. auto opts = httplib::stream::Options(cli, "/options");
  12749. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12750. }
  12751. // SSL stream::* tests
  12752. #ifdef CPPHTTPLIB_SSL_ENABLED
  12753. class SSLStreamApiTest : public ::testing::Test {
  12754. protected:
  12755. void SetUp() override {
  12756. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12757. res.set_content("Hello SSL!", "text/plain");
  12758. });
  12759. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12760. res.set_content(req.body, "text/plain");
  12761. });
  12762. port_ = svr_.bind_to_any_port("127.0.0.1");
  12763. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12764. svr_.wait_until_ready();
  12765. }
  12766. void TearDown() override {
  12767. svr_.stop();
  12768. if (thread_.joinable()) thread_.join();
  12769. }
  12770. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12771. std::thread thread_;
  12772. int port_ = 0;
  12773. };
  12774. TEST_F(SSLStreamApiTest, GetAndPost) {
  12775. httplib::SSLClient cli("127.0.0.1", port_);
  12776. cli.enable_server_certificate_verification(false);
  12777. auto get = httplib::stream::Get(cli, "/hello");
  12778. EXPECT_EQ("Hello SSL!", read_body(get));
  12779. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12780. EXPECT_EQ("test", read_body(post));
  12781. }
  12782. #endif
  12783. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12784. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12785. // BodyReader
  12786. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12787. // Test that read timeout during streaming is detected
  12788. // Use a large content-length response where server delays mid-stream
  12789. Server svr;
  12790. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12791. // Send a large response with delay in the middle
  12792. res.set_content_provider(
  12793. 1000, // content_length
  12794. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12795. if (offset < 100) {
  12796. // Send first 100 bytes immediately
  12797. std::string data(100, 'A');
  12798. sink.write(data.c_str(), data.size());
  12799. return true;
  12800. }
  12801. // Then delay longer than client timeout
  12802. std::this_thread::sleep_for(std::chrono::seconds(3));
  12803. std::string data(900, 'B');
  12804. sink.write(data.c_str(), data.size());
  12805. return true;
  12806. });
  12807. });
  12808. auto port = 8091;
  12809. std::thread t([&]() { svr.listen("localhost", port); });
  12810. svr.wait_until_ready();
  12811. Client cli("localhost", port);
  12812. cli.set_read_timeout(1, 0); // 1 second timeout
  12813. auto handle = cli.open_stream("GET", "/slow-stream");
  12814. ASSERT_TRUE(handle.is_valid());
  12815. char buf[256];
  12816. ssize_t total = 0;
  12817. ssize_t n;
  12818. bool got_error = false;
  12819. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12820. total += n;
  12821. }
  12822. if (n < 0) {
  12823. got_error = true;
  12824. // Should be timeout or read error
  12825. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12826. handle.get_read_error() == Error::Read)
  12827. << "Actual error: " << to_string(handle.get_read_error());
  12828. }
  12829. // Either we got an error, or we got less data than expected
  12830. EXPECT_TRUE(got_error || total < 1000)
  12831. << "Expected timeout but got all " << total << " bytes";
  12832. svr.stop();
  12833. t.join();
  12834. }
  12835. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12836. // Test connection closed detection via BodyReader
  12837. Server svr;
  12838. std::atomic<bool> close_now{false};
  12839. svr.Get("/will-close", [&](const Request &, Response &res) {
  12840. res.set_content_provider(
  12841. 10000, // Large content_length that we won't fully send
  12842. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12843. if (offset < 100) {
  12844. std::string data(100, 'X');
  12845. sink.write(data.c_str(), data.size());
  12846. return true;
  12847. }
  12848. // Wait for signal then abort
  12849. while (!close_now) {
  12850. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12851. }
  12852. return false; // Abort - server will close connection
  12853. });
  12854. });
  12855. auto port = 8092;
  12856. std::thread t([&]() { svr.listen("localhost", port); });
  12857. svr.wait_until_ready();
  12858. Client cli("localhost", port);
  12859. auto handle = cli.open_stream("GET", "/will-close");
  12860. ASSERT_TRUE(handle.is_valid());
  12861. char buf[256];
  12862. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12863. EXPECT_GT(n, 0) << "First read should succeed";
  12864. // Signal server to close
  12865. close_now = true;
  12866. // Keep reading until error or EOF
  12867. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12868. // Keep reading
  12869. }
  12870. // Should get an error since content_length wasn't satisfied
  12871. if (n < 0) {
  12872. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12873. handle.get_read_error() == Error::Read)
  12874. << "Actual error: " << to_string(handle.get_read_error());
  12875. }
  12876. svr.stop();
  12877. t.join();
  12878. }
  12879. #ifdef CPPHTTPLIB_SSL_ENABLED
  12880. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12881. // Test that read timeout during SSL streaming is detected
  12882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12883. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12884. res.set_content_provider(
  12885. 1000, "text/plain",
  12886. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12887. if (offset < 100) {
  12888. std::string data(100, 'A');
  12889. sink.write(data.c_str(), data.size());
  12890. return true;
  12891. }
  12892. std::this_thread::sleep_for(std::chrono::seconds(3));
  12893. std::string data(900, 'B');
  12894. sink.write(data.c_str(), data.size());
  12895. return true;
  12896. });
  12897. });
  12898. auto port = 8093;
  12899. std::thread t([&]() { svr.listen("localhost", port); });
  12900. svr.wait_until_ready();
  12901. SSLClient cli("localhost", port);
  12902. cli.enable_server_certificate_verification(false);
  12903. cli.set_read_timeout(1, 0); // 1 second timeout
  12904. auto handle = cli.open_stream("GET", "/slow-stream");
  12905. ASSERT_TRUE(handle.is_valid());
  12906. char buf[256];
  12907. ssize_t total = 0;
  12908. ssize_t n;
  12909. bool got_error = false;
  12910. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12911. total += n;
  12912. }
  12913. if (n < 0) {
  12914. got_error = true;
  12915. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12916. handle.get_read_error() == Error::Read)
  12917. << "Actual error: " << to_string(handle.get_read_error());
  12918. }
  12919. EXPECT_TRUE(got_error || total < 1000)
  12920. << "Expected timeout but got all " << total << " bytes";
  12921. svr.stop();
  12922. t.join();
  12923. }
  12924. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12925. // Test SSL connection closed detection
  12926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12927. std::atomic<bool> close_now{false};
  12928. svr.Get("/will-close", [&](const Request &, Response &res) {
  12929. res.set_content_provider(
  12930. 10000, "text/plain",
  12931. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12932. if (offset < 100) {
  12933. std::string data(100, 'X');
  12934. sink.write(data.c_str(), data.size());
  12935. return true;
  12936. }
  12937. while (!close_now) {
  12938. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12939. }
  12940. return false;
  12941. });
  12942. });
  12943. auto port = 8094;
  12944. std::thread t([&]() { svr.listen("localhost", port); });
  12945. svr.wait_until_ready();
  12946. SSLClient cli("localhost", port);
  12947. cli.enable_server_certificate_verification(false);
  12948. auto handle = cli.open_stream("GET", "/will-close");
  12949. ASSERT_TRUE(handle.is_valid());
  12950. char buf[256];
  12951. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12952. EXPECT_GT(n, 0);
  12953. // Signal server to close
  12954. close_now = true;
  12955. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12956. // Keep reading
  12957. }
  12958. if (n < 0) {
  12959. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12960. handle.get_read_error() == Error::Read)
  12961. << "Actual error: " << to_string(handle.get_read_error());
  12962. }
  12963. svr.stop();
  12964. t.join();
  12965. }
  12966. #endif
  12967. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12968. using namespace httplib;
  12969. // Create a test file
  12970. const char *fname = "etag_testfile.txt";
  12971. const char *content = "etag-content";
  12972. {
  12973. std::ofstream ofs(fname);
  12974. ofs << content;
  12975. ASSERT_TRUE(ofs.good());
  12976. }
  12977. Server svr;
  12978. svr.set_mount_point("/static", ".");
  12979. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12980. svr.wait_until_ready();
  12981. Client cli(HOST, PORT);
  12982. // First request: should get 200 with ETag header
  12983. auto res1 = cli.Get("/static/etag_testfile.txt");
  12984. ASSERT_TRUE(res1);
  12985. ASSERT_EQ(200, res1->status);
  12986. ASSERT_TRUE(res1->has_header("ETag"));
  12987. std::string etag = res1->get_header_value("ETag");
  12988. EXPECT_FALSE(etag.empty());
  12989. // Verify ETag format: W/"hex-hex"
  12990. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12991. EXPECT_EQ('W', etag[0]);
  12992. EXPECT_EQ('/', etag[1]);
  12993. EXPECT_EQ('"', etag[2]);
  12994. EXPECT_EQ('"', etag.back());
  12995. // Exact match: expect 304 Not Modified
  12996. Headers h2 = {{"If-None-Match", etag}};
  12997. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12998. ASSERT_TRUE(res2);
  12999. EXPECT_EQ(304, res2->status);
  13000. // Wildcard match: expect 304 Not Modified
  13001. Headers h3 = {{"If-None-Match", "*"}};
  13002. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13003. ASSERT_TRUE(res3);
  13004. EXPECT_EQ(304, res3->status);
  13005. // Non-matching ETag: expect 200
  13006. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13007. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13008. ASSERT_TRUE(res4);
  13009. EXPECT_EQ(200, res4->status);
  13010. // Multiple ETags with one matching: expect 304
  13011. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13012. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13013. ASSERT_TRUE(res5);
  13014. EXPECT_EQ(304, res5->status);
  13015. svr.stop();
  13016. t.join();
  13017. std::remove(fname);
  13018. }
  13019. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13020. using namespace httplib;
  13021. Server svr;
  13022. svr.set_mount_point("/static", ".");
  13023. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13024. svr.wait_until_ready();
  13025. Client cli(HOST, PORT);
  13026. // Send If-None-Match: * to a non-existent file
  13027. Headers h = {{"If-None-Match", "*"}};
  13028. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13029. ASSERT_TRUE(res);
  13030. EXPECT_EQ(404, res->status);
  13031. svr.stop();
  13032. t.join();
  13033. }
  13034. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13035. using namespace httplib;
  13036. // Create a test file
  13037. const char *fname = "etag_boundary_testfile.txt";
  13038. const char *content = "boundary-test";
  13039. {
  13040. std::ofstream ofs(fname);
  13041. ofs << content;
  13042. ASSERT_TRUE(ofs.good());
  13043. }
  13044. Server svr;
  13045. svr.set_mount_point("/static", ".");
  13046. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13047. svr.wait_until_ready();
  13048. Client cli(HOST, PORT);
  13049. // Get the actual ETag
  13050. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13051. ASSERT_TRUE(res1);
  13052. ASSERT_EQ(200, res1->status);
  13053. ASSERT_TRUE(res1->has_header("ETag"));
  13054. std::string etag = res1->get_header_value("ETag");
  13055. // Test 1: Very long ETag value (longer than actual ETag)
  13056. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13057. Headers h1 = {{"If-None-Match", "W/"
  13058. "\"very-long-etag-value-that-is-much-longer-"
  13059. "than-the-actual-etag-value\""}};
  13060. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13061. ASSERT_TRUE(res2);
  13062. EXPECT_EQ(200, res2->status); // Should not match
  13063. // Test 2: Long string followed by wildcard
  13064. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13065. // string)
  13066. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13067. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13068. ASSERT_TRUE(res3);
  13069. EXPECT_EQ(304, res3->status); // Should match on "*"
  13070. // Test 3: Wildcard followed by long string
  13071. // Should match on "*" immediately and return 304
  13072. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13073. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13074. ASSERT_TRUE(res4);
  13075. EXPECT_EQ(304, res4->status); // Should match on "*"
  13076. // Test 4: Multiple long non-matching values
  13077. // Should NOT match and return 200 (test that all comparisons are safe)
  13078. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13079. "W/\"second-long-non-matching-value\", "
  13080. "W/\"third-long-non-matching-value\""}};
  13081. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13082. ASSERT_TRUE(res5);
  13083. EXPECT_EQ(200, res5->status); // Should not match
  13084. // Test 5: Single character that is not "*" (edge case)
  13085. Headers h5 = {{"If-None-Match", "X"}};
  13086. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13087. ASSERT_TRUE(res6);
  13088. EXPECT_EQ(200, res6->status); // Should not match
  13089. svr.stop();
  13090. t.join();
  13091. std::remove(fname);
  13092. }
  13093. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13094. using namespace httplib;
  13095. // Create a test file
  13096. const char *fname = "ims_testfile.txt";
  13097. const char *content = "if-modified-since-test";
  13098. {
  13099. std::ofstream ofs(fname);
  13100. ofs << content;
  13101. ASSERT_TRUE(ofs.good());
  13102. }
  13103. Server svr;
  13104. svr.set_mount_point("/static", ".");
  13105. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13106. svr.wait_until_ready();
  13107. Client cli(HOST, PORT);
  13108. // First request: should get 200 with Last-Modified header
  13109. auto res1 = cli.Get("/static/ims_testfile.txt");
  13110. ASSERT_TRUE(res1);
  13111. ASSERT_EQ(200, res1->status);
  13112. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13113. std::string last_modified = res1->get_header_value("Last-Modified");
  13114. EXPECT_FALSE(last_modified.empty());
  13115. // If-Modified-Since with same time: expect 304
  13116. Headers h2 = {{"If-Modified-Since", last_modified}};
  13117. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13118. ASSERT_TRUE(res2);
  13119. EXPECT_EQ(304, res2->status);
  13120. // If-Modified-Since with future time: expect 304
  13121. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13122. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13123. ASSERT_TRUE(res3);
  13124. EXPECT_EQ(304, res3->status);
  13125. // If-Modified-Since with past time: expect 200
  13126. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13127. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13128. ASSERT_TRUE(res4);
  13129. EXPECT_EQ(200, res4->status);
  13130. // If-None-Match takes precedence over If-Modified-Since
  13131. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13132. ASSERT_TRUE(res1->has_header("ETag"));
  13133. std::string etag = res1->get_header_value("ETag");
  13134. Headers h5 = {{"If-None-Match", etag},
  13135. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13136. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13137. ASSERT_TRUE(res5);
  13138. EXPECT_EQ(304, res5->status);
  13139. svr.stop();
  13140. t.join();
  13141. std::remove(fname);
  13142. }
  13143. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13144. using namespace httplib;
  13145. Server svr;
  13146. // Endpoint that returns compressible content
  13147. svr.Get("/compressible", [](const Request &, Response &res) {
  13148. // Return a large enough body to trigger compression
  13149. std::string body(1000, 'a');
  13150. res.set_content(body, "text/plain");
  13151. });
  13152. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13153. svr.wait_until_ready();
  13154. Client cli(HOST, PORT);
  13155. // Request with gzip support: should get Vary header when compressed
  13156. cli.set_compress(true);
  13157. auto res1 = cli.Get("/compressible");
  13158. ASSERT_TRUE(res1);
  13159. EXPECT_EQ(200, res1->status);
  13160. // If Content-Encoding is set, Vary should also be set
  13161. if (res1->has_header("Content-Encoding")) {
  13162. EXPECT_TRUE(res1->has_header("Vary"));
  13163. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13164. }
  13165. // Request without Accept-Encoding header: should not have compression
  13166. Headers h_no_compress;
  13167. auto res2 = cli.Get("/compressible", h_no_compress);
  13168. ASSERT_TRUE(res2);
  13169. EXPECT_EQ(200, res2->status);
  13170. // Verify Vary header is present when compression is applied
  13171. // (the exact behavior depends on server configuration)
  13172. svr.stop();
  13173. t.join();
  13174. }
  13175. TEST(ETagTest, IfRangeWithETag) {
  13176. using namespace httplib;
  13177. // Create a test file with known content
  13178. const char *fname = "if_range_testfile.txt";
  13179. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13180. {
  13181. std::ofstream ofs(fname);
  13182. ofs << content;
  13183. ASSERT_TRUE(ofs.good());
  13184. }
  13185. Server svr;
  13186. svr.set_mount_point("/static", ".");
  13187. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13188. svr.wait_until_ready();
  13189. Client cli(HOST, PORT);
  13190. // First request: get ETag
  13191. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13192. ASSERT_TRUE(res1);
  13193. ASSERT_EQ(200, res1->status);
  13194. ASSERT_TRUE(res1->has_header("ETag"));
  13195. std::string etag = res1->get_header_value("ETag");
  13196. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13197. // Since our server generates weak ETags (W/"..."), If-Range with our
  13198. // ETag should NOT result in partial content - it should return full content.
  13199. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13200. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13201. ASSERT_TRUE(res2);
  13202. // Weak ETag in If-Range -> full content (200), not partial (206)
  13203. EXPECT_EQ(200, res2->status);
  13204. EXPECT_EQ(content, res2->body);
  13205. EXPECT_FALSE(res2->has_header("Content-Range"));
  13206. // Range request with non-matching If-Range (ETag): should get 200 (full
  13207. // content)
  13208. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13209. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13210. ASSERT_TRUE(res3);
  13211. EXPECT_EQ(200, res3->status);
  13212. EXPECT_EQ(content, res3->body);
  13213. EXPECT_FALSE(res3->has_header("Content-Range"));
  13214. // Range request with strong ETag (hypothetical - our server doesn't generate
  13215. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13216. // should return full content)
  13217. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13218. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13219. ASSERT_TRUE(res4);
  13220. EXPECT_EQ(200, res4->status);
  13221. EXPECT_EQ(content, res4->body);
  13222. EXPECT_FALSE(res4->has_header("Content-Range"));
  13223. svr.stop();
  13224. t.join();
  13225. std::remove(fname);
  13226. }
  13227. TEST(ETagTest, IfRangeWithDate) {
  13228. using namespace httplib;
  13229. // Create a test file
  13230. const char *fname = "if_range_date_testfile.txt";
  13231. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13232. {
  13233. std::ofstream ofs(fname);
  13234. ofs << content;
  13235. ASSERT_TRUE(ofs.good());
  13236. }
  13237. Server svr;
  13238. svr.set_mount_point("/static", ".");
  13239. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13240. svr.wait_until_ready();
  13241. Client cli(HOST, PORT);
  13242. // First request: get Last-Modified
  13243. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13244. ASSERT_TRUE(res1);
  13245. ASSERT_EQ(200, res1->status);
  13246. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13247. std::string last_modified = res1->get_header_value("Last-Modified");
  13248. // Range request with matching If-Range (date): should get 206
  13249. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13250. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13251. ASSERT_TRUE(res2);
  13252. EXPECT_EQ(206, res2->status);
  13253. EXPECT_EQ("FGHIJ", res2->body);
  13254. // Range request with old If-Range date: should get 200 (full content)
  13255. Headers h3 = {{"Range", "bytes=5-9"},
  13256. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13257. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13258. ASSERT_TRUE(res3);
  13259. EXPECT_EQ(200, res3->status);
  13260. EXPECT_EQ(content, res3->body);
  13261. // Range request with future If-Range date: should get 206
  13262. Headers h4 = {{"Range", "bytes=0-4"},
  13263. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13264. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13265. ASSERT_TRUE(res4);
  13266. EXPECT_EQ(206, res4->status);
  13267. EXPECT_EQ("ABCDE", res4->body);
  13268. svr.stop();
  13269. t.join();
  13270. std::remove(fname);
  13271. }
  13272. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13273. using namespace httplib;
  13274. const char *fname = "etag_malformed.txt";
  13275. const char *content = "malformed-etag";
  13276. {
  13277. std::ofstream ofs(fname);
  13278. ofs << content;
  13279. ASSERT_TRUE(ofs.good());
  13280. }
  13281. Server svr;
  13282. svr.set_mount_point("/static", ".");
  13283. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13284. svr.wait_until_ready();
  13285. Client cli(HOST, PORT);
  13286. // baseline: should get 200 and an ETag
  13287. auto res1 = cli.Get("/static/etag_malformed.txt");
  13288. ASSERT_TRUE(res1);
  13289. ASSERT_EQ(200, res1->status);
  13290. ASSERT_TRUE(res1->has_header("ETag"));
  13291. // Malformed ETag value (missing quotes) should be treated as non-matching
  13292. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13293. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13294. ASSERT_TRUE(res_bad);
  13295. EXPECT_EQ(200, res_bad->status);
  13296. // Whitespace-only header value should be considered invalid / non-matching
  13297. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13298. "Host: localhost\r\n"
  13299. "If-None-Match: \r\n"
  13300. "Connection: close\r\n"
  13301. "\r\n";
  13302. std::string out;
  13303. ASSERT_TRUE(send_request(5, raw_req, &out));
  13304. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13305. svr.stop();
  13306. t.join();
  13307. std::remove(fname);
  13308. }
  13309. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13310. using namespace httplib;
  13311. const char *fname = "ims_invalid_format.txt";
  13312. const char *content = "ims-bad-format";
  13313. {
  13314. std::ofstream ofs(fname);
  13315. ofs << content;
  13316. ASSERT_TRUE(ofs.good());
  13317. }
  13318. Server svr;
  13319. svr.set_mount_point("/static", ".");
  13320. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13321. svr.wait_until_ready();
  13322. Client cli(HOST, PORT);
  13323. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13324. ASSERT_TRUE(res1);
  13325. ASSERT_EQ(200, res1->status);
  13326. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13327. // If-Modified-Since with invalid format should not result in 304
  13328. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13329. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13330. ASSERT_TRUE(res_bad);
  13331. EXPECT_EQ(200, res_bad->status);
  13332. // If-Range with invalid date format should be treated as mismatch -> full
  13333. // content (200)
  13334. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13335. {"If-Range", "invalid-date"}};
  13336. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13337. ASSERT_TRUE(res_ifrange);
  13338. EXPECT_EQ(200, res_ifrange->status);
  13339. svr.stop();
  13340. t.join();
  13341. std::remove(fname);
  13342. }
  13343. TEST(ETagTest, IfRangeWithMalformedETag) {
  13344. using namespace httplib;
  13345. const char *fname = "ifrange_malformed.txt";
  13346. const std::string content = "0123456789";
  13347. {
  13348. std::ofstream ofs(fname);
  13349. ofs << content;
  13350. ASSERT_TRUE(ofs.good());
  13351. }
  13352. Server svr;
  13353. svr.set_mount_point("/static", ".");
  13354. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13355. svr.wait_until_ready();
  13356. Client cli(HOST, PORT);
  13357. // First request: get ETag
  13358. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13359. ASSERT_TRUE(res1);
  13360. ASSERT_EQ(200, res1->status);
  13361. ASSERT_TRUE(res1->has_header("ETag"));
  13362. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13363. // full content (200)
  13364. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13365. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13366. ASSERT_TRUE(res2);
  13367. EXPECT_EQ(200, res2->status);
  13368. EXPECT_EQ(content, res2->body);
  13369. svr.stop();
  13370. t.join();
  13371. std::remove(fname);
  13372. }
  13373. TEST(ETagTest, ExtremeLargeDateValues) {
  13374. using namespace httplib;
  13375. const char *fname = "ims_extreme_date.txt";
  13376. const char *content = "ims-extreme-date";
  13377. {
  13378. std::ofstream ofs(fname);
  13379. ofs << content;
  13380. ASSERT_TRUE(ofs.good());
  13381. }
  13382. Server svr;
  13383. svr.set_mount_point("/static", ".");
  13384. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13385. svr.wait_until_ready();
  13386. Client cli(HOST, PORT);
  13387. auto res1 = cli.Get(std::string("/static/") + fname);
  13388. ASSERT_TRUE(res1);
  13389. ASSERT_EQ(200, res1->status);
  13390. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13391. // Extremely large year that may overflow date parsing routines.
  13392. Headers h_large_date = {
  13393. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13394. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13395. ASSERT_TRUE(res_bad);
  13396. // Expect server to treat this as invalid/mismatch and return full content
  13397. EXPECT_EQ(200, res_bad->status);
  13398. // If-Range with extremely large date should be treated as mismatch -> full
  13399. // content (200)
  13400. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13401. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13402. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13403. ASSERT_TRUE(res_ifrange);
  13404. EXPECT_EQ(200, res_ifrange->status);
  13405. svr.stop();
  13406. t.join();
  13407. std::remove(fname);
  13408. }
  13409. TEST(ETagTest, NegativeFileModificationTime) {
  13410. using namespace httplib;
  13411. const char *fname = "ims_negative_mtime.txt";
  13412. const std::string content = "negative-mtime";
  13413. {
  13414. std::ofstream ofs(fname);
  13415. ofs << content;
  13416. ASSERT_TRUE(ofs.good());
  13417. }
  13418. // Try to set file mtime to a negative value. This may fail on some
  13419. // platforms/filesystems; if it fails, the test will still verify server
  13420. // behaves safely by performing a regular conditional request.
  13421. #if defined(__APPLE__) || defined(__linux__)
  13422. bool set_negative = false;
  13423. do {
  13424. struct timeval times[2];
  13425. // access time: now
  13426. times[0].tv_sec = time(nullptr);
  13427. times[0].tv_usec = 0;
  13428. // modification time: negative (e.g., -1)
  13429. times[1].tv_sec = -1;
  13430. times[1].tv_usec = 0;
  13431. if (utimes(fname, times) == 0) { set_negative = true; }
  13432. } while (0);
  13433. #else
  13434. bool set_negative = false;
  13435. #endif
  13436. Server svr;
  13437. svr.set_mount_point("/static", ".");
  13438. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13439. svr.wait_until_ready();
  13440. Client cli(HOST, PORT);
  13441. auto res1 = cli.Get(std::string("/static/") + fname);
  13442. ASSERT_TRUE(res1);
  13443. ASSERT_EQ(200, res1->status);
  13444. bool has_last_modified = res1->has_header("Last-Modified");
  13445. std::string last_modified;
  13446. if (has_last_modified) {
  13447. last_modified = res1->get_header_value("Last-Modified");
  13448. }
  13449. if (set_negative) {
  13450. // If we successfully set a negative mtime, ensure server returns a
  13451. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13452. // with an old date and ensure server handles it without crash.
  13453. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13454. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13455. ASSERT_TRUE(res2);
  13456. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13457. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13458. } else {
  13459. // Could not set negative mtime on this platform; fall back to verifying
  13460. // that normal invalid/malformed dates are treated safely (non-304).
  13461. Headers h_bad_date = {
  13462. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13463. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13464. ASSERT_TRUE(res_bad);
  13465. EXPECT_EQ(200, res_bad->status);
  13466. }
  13467. svr.stop();
  13468. t.join();
  13469. std::remove(fname);
  13470. }
  13471. //==============================================================================
  13472. // SSE Parsing Tests
  13473. //==============================================================================
  13474. class SSEParsingTest : public ::testing::Test {
  13475. protected:
  13476. // Test helper that mimics SSE parsing behavior
  13477. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13478. int &retry_ms) {
  13479. // Blank line signals end of event
  13480. if (line.empty() || line == "\r") { return true; }
  13481. // Lines starting with ':' are comments (ignored)
  13482. if (!line.empty() && line[0] == ':') { return false; }
  13483. // Find the colon separator
  13484. auto colon_pos = line.find(':');
  13485. if (colon_pos == std::string::npos) {
  13486. // Line with no colon is treated as field name with empty value
  13487. return false;
  13488. }
  13489. std::string field = line.substr(0, colon_pos);
  13490. std::string value;
  13491. // Value starts after colon, skip optional single space
  13492. if (colon_pos + 1 < line.size()) {
  13493. size_t value_start = colon_pos + 1;
  13494. if (line[value_start] == ' ') { value_start++; }
  13495. value = line.substr(value_start);
  13496. // Remove trailing \r if present
  13497. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13498. }
  13499. // Handle known fields
  13500. if (field == "event") {
  13501. msg.event = value;
  13502. } else if (field == "data") {
  13503. // Multiple data lines are concatenated with newlines
  13504. if (!msg.data.empty()) { msg.data += "\n"; }
  13505. msg.data += value;
  13506. } else if (field == "id") {
  13507. // Empty id is valid (clears the last event ID)
  13508. msg.id = value;
  13509. } else if (field == "retry") {
  13510. // Parse retry interval in milliseconds
  13511. {
  13512. int v = 0;
  13513. auto res =
  13514. detail::from_chars(value.data(), value.data() + value.size(), v);
  13515. if (res.ec == std::errc{}) { retry_ms = v; }
  13516. }
  13517. }
  13518. // Unknown fields are ignored per SSE spec
  13519. return false;
  13520. }
  13521. };
  13522. // Test: Single-line data
  13523. TEST_F(SSEParsingTest, SingleLineData) {
  13524. sse::SSEMessage msg;
  13525. int retry_ms = 3000;
  13526. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13527. EXPECT_EQ(msg.data, "hello");
  13528. EXPECT_EQ(msg.event, "message");
  13529. // Blank line ends event
  13530. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13531. }
  13532. // Test: Multi-line data
  13533. TEST_F(SSEParsingTest, MultiLineData) {
  13534. sse::SSEMessage msg;
  13535. int retry_ms = 3000;
  13536. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13537. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13538. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13539. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13540. }
  13541. // Test: Custom event types
  13542. TEST_F(SSEParsingTest, CustomEventType) {
  13543. sse::SSEMessage msg;
  13544. int retry_ms = 3000;
  13545. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13546. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13547. EXPECT_EQ(msg.event, "update");
  13548. EXPECT_EQ(msg.data, "payload");
  13549. }
  13550. // Test: Event ID handling
  13551. TEST_F(SSEParsingTest, EventIdHandling) {
  13552. sse::SSEMessage msg;
  13553. int retry_ms = 3000;
  13554. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13555. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13556. EXPECT_EQ(msg.id, "12345");
  13557. }
  13558. // Test: Empty event ID (clears last event ID)
  13559. TEST_F(SSEParsingTest, EmptyEventId) {
  13560. sse::SSEMessage msg;
  13561. msg.id = "previous";
  13562. int retry_ms = 3000;
  13563. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13564. EXPECT_EQ(msg.id, "");
  13565. }
  13566. // Test: Retry field parsing
  13567. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13568. sse::SSEMessage msg;
  13569. int retry_ms = 3000;
  13570. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13571. EXPECT_EQ(retry_ms, 5000);
  13572. }
  13573. // Test: Invalid retry value
  13574. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13575. sse::SSEMessage msg;
  13576. int retry_ms = 3000;
  13577. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13578. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13579. }
  13580. // Test: Comments (lines starting with :)
  13581. TEST_F(SSEParsingTest, CommentsIgnored) {
  13582. sse::SSEMessage msg;
  13583. int retry_ms = 3000;
  13584. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13585. EXPECT_EQ(msg.data, "");
  13586. EXPECT_EQ(msg.event, "message");
  13587. }
  13588. // Test: Colon in value
  13589. TEST_F(SSEParsingTest, ColonInValue) {
  13590. sse::SSEMessage msg;
  13591. int retry_ms = 3000;
  13592. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13593. EXPECT_EQ(msg.data, "hello:world:test");
  13594. }
  13595. // Test: Line with no colon (field name only)
  13596. TEST_F(SSEParsingTest, FieldNameOnly) {
  13597. sse::SSEMessage msg;
  13598. int retry_ms = 3000;
  13599. // According to SSE spec, this is treated as field name with empty value
  13600. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13601. // Since we don't recognize "data" without colon, data should be empty
  13602. EXPECT_EQ(msg.data, "");
  13603. }
  13604. // Test: Trailing \r handling
  13605. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13606. sse::SSEMessage msg;
  13607. int retry_ms = 3000;
  13608. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13609. EXPECT_EQ(msg.data, "hello");
  13610. }
  13611. // Test: Unknown fields ignored
  13612. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13613. sse::SSEMessage msg;
  13614. int retry_ms = 3000;
  13615. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13616. EXPECT_EQ(msg.data, "");
  13617. EXPECT_EQ(msg.event, "message");
  13618. }
  13619. // Test: Space after colon is optional
  13620. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13621. sse::SSEMessage msg1, msg2;
  13622. int retry_ms = 3000;
  13623. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13624. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13625. EXPECT_EQ(msg1.data, "hello");
  13626. EXPECT_EQ(msg2.data, "hello");
  13627. }
  13628. // Test: SSEMessage clear
  13629. TEST_F(SSEParsingTest, MessageClear) {
  13630. sse::SSEMessage msg;
  13631. msg.event = "custom";
  13632. msg.data = "some data";
  13633. msg.id = "123";
  13634. msg.clear();
  13635. EXPECT_EQ(msg.event, "message");
  13636. EXPECT_EQ(msg.data, "");
  13637. EXPECT_EQ(msg.id, "");
  13638. }
  13639. // Test: Complete event parsing
  13640. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13641. sse::SSEMessage msg;
  13642. int retry_ms = 3000;
  13643. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13644. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13645. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13646. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13647. // Blank line ends event
  13648. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13649. EXPECT_EQ(msg.event, "notification");
  13650. EXPECT_EQ(msg.id, "evt-42");
  13651. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13652. EXPECT_EQ(retry_ms, 1000);
  13653. }
  13654. //==============================================================================
  13655. // Integration Tests with Server
  13656. //==============================================================================
  13657. class SSEIntegrationTest : public ::testing::Test {
  13658. protected:
  13659. void SetUp() override {
  13660. stop_server_.store(false);
  13661. events_.clear();
  13662. server_ = httplib::detail::make_unique<Server>();
  13663. setup_server();
  13664. start_server();
  13665. }
  13666. void TearDown() override {
  13667. stop_server_.store(true);
  13668. event_cv_.notify_all();
  13669. server_->stop();
  13670. if (server_thread_.joinable()) { server_thread_.join(); }
  13671. }
  13672. void setup_server() {
  13673. // Simple SSE endpoint
  13674. server_->Get("/events", [this](const Request &req, Response &res) {
  13675. auto last_id = req.get_header_value("Last-Event-ID");
  13676. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13677. res.set_chunked_content_provider(
  13678. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13679. std::unique_lock<std::mutex> lock(event_mutex_);
  13680. if (event_cv_.wait_for(
  13681. lock, std::chrono::milliseconds(200), [this] {
  13682. return !events_.empty() || stop_server_.load();
  13683. })) {
  13684. if (stop_server_.load()) { return false; }
  13685. if (!events_.empty()) {
  13686. std::string event = events_.front();
  13687. events_.erase(events_.begin());
  13688. sink.write(event.data(), event.size());
  13689. return true;
  13690. }
  13691. }
  13692. return !stop_server_.load();
  13693. });
  13694. });
  13695. // Endpoint that returns error
  13696. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13697. res.status = 500;
  13698. res.set_content("Internal Server Error", "text/plain");
  13699. });
  13700. // Endpoint for custom event types
  13701. server_->Get("/custom-events", [](const Request &, Response &res) {
  13702. res.set_chunked_content_provider(
  13703. "text/event-stream", [](size_t offset, DataSink &sink) {
  13704. if (offset == 0) {
  13705. std::string event = "event: update\ndata: updated\n\n"
  13706. "event: delete\ndata: deleted\n\n";
  13707. sink.write(event.data(), event.size());
  13708. }
  13709. return false; // End stream after sending
  13710. });
  13711. });
  13712. }
  13713. void start_server() {
  13714. port_ = server_->bind_to_any_port(HOST);
  13715. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13716. // Wait for server to start
  13717. while (!server_->is_running()) {
  13718. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13719. }
  13720. }
  13721. int get_port() const { return port_; }
  13722. void send_event(const std::string &event) {
  13723. std::lock_guard<std::mutex> lock(event_mutex_);
  13724. events_.push_back(event);
  13725. event_cv_.notify_all();
  13726. }
  13727. std::unique_ptr<Server> server_;
  13728. std::thread server_thread_;
  13729. std::mutex event_mutex_;
  13730. std::condition_variable event_cv_;
  13731. std::vector<std::string> events_;
  13732. std::atomic<bool> stop_server_{false};
  13733. std::string last_received_event_id_;
  13734. int port_ = 0;
  13735. };
  13736. // Test: Successful connection and on_open callback
  13737. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13738. // Add a simple endpoint that sends one event and closes
  13739. server_->Get("/simple-event", [](const Request &, Response &res) {
  13740. res.set_chunked_content_provider(
  13741. "text/event-stream", [](size_t offset, DataSink &sink) {
  13742. if (offset == 0) {
  13743. std::string event = "data: hello\n\n";
  13744. sink.write(event.data(), event.size());
  13745. }
  13746. return false; // Close stream after sending
  13747. });
  13748. });
  13749. Client client("localhost", get_port());
  13750. sse::SSEClient sse(client, "/simple-event");
  13751. std::atomic<bool> open_called{false};
  13752. std::atomic<bool> message_received{false};
  13753. sse.on_open([&open_called]() { open_called.store(true); });
  13754. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13755. if (msg.data == "hello") { message_received.store(true); }
  13756. });
  13757. sse.set_reconnect_interval(100);
  13758. sse.set_max_reconnect_attempts(1);
  13759. // Start async
  13760. sse.start_async();
  13761. // Wait for message to be processed
  13762. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13763. sse.stop();
  13764. EXPECT_TRUE(open_called.load());
  13765. EXPECT_TRUE(message_received.load());
  13766. }
  13767. // Test: on_message callback
  13768. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13769. // Endpoint that sends multiple events then closes
  13770. server_->Get("/multi-event", [](const Request &, Response &res) {
  13771. res.set_chunked_content_provider(
  13772. "text/event-stream", [](size_t offset, DataSink &sink) {
  13773. if (offset == 0) {
  13774. std::string events = "data: message1\n\ndata: message2\n\n";
  13775. sink.write(events.data(), events.size());
  13776. }
  13777. return false;
  13778. });
  13779. });
  13780. Client client("localhost", get_port());
  13781. sse::SSEClient sse(client, "/multi-event");
  13782. std::vector<std::string> received_messages;
  13783. std::mutex messages_mutex;
  13784. sse.on_message([&](const sse::SSEMessage &msg) {
  13785. std::lock_guard<std::mutex> lock(messages_mutex);
  13786. received_messages.push_back(msg.data);
  13787. });
  13788. sse.set_reconnect_interval(100);
  13789. sse.set_max_reconnect_attempts(1);
  13790. sse.start_async();
  13791. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13792. sse.stop();
  13793. std::lock_guard<std::mutex> lock(messages_mutex);
  13794. EXPECT_GE(received_messages.size(), 2u);
  13795. if (received_messages.size() >= 2) {
  13796. EXPECT_EQ(received_messages[0], "message1");
  13797. EXPECT_EQ(received_messages[1], "message2");
  13798. }
  13799. }
  13800. // Test: on_event for specific types
  13801. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13802. Client client("localhost", get_port());
  13803. sse::SSEClient sse(client, "/custom-events");
  13804. std::atomic<bool> update_received{false};
  13805. std::atomic<bool> delete_received{false};
  13806. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13807. if (msg.data == "updated") { update_received.store(true); }
  13808. });
  13809. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13810. if (msg.data == "deleted") { delete_received.store(true); }
  13811. });
  13812. sse.set_max_reconnect_attempts(1);
  13813. sse.start_async();
  13814. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13815. sse.stop();
  13816. EXPECT_TRUE(update_received.load());
  13817. EXPECT_TRUE(delete_received.load());
  13818. }
  13819. // Test: on_error callback on connection failure
  13820. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13821. // Connect to a non-existent port
  13822. Client client("localhost", 59999);
  13823. sse::SSEClient sse(client, "/events");
  13824. std::atomic<bool> error_called{false};
  13825. Error received_error = Error::Success;
  13826. sse.on_error([&](Error err) {
  13827. error_called.store(true);
  13828. received_error = err;
  13829. });
  13830. sse.set_reconnect_interval(50);
  13831. sse.set_max_reconnect_attempts(1);
  13832. sse.start_async();
  13833. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13834. sse.stop();
  13835. EXPECT_TRUE(error_called.load());
  13836. EXPECT_NE(received_error, Error::Success);
  13837. }
  13838. // Test: Last-Event-ID header sent on reconnect
  13839. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13840. // Endpoint that sends event with ID
  13841. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13842. res.set_chunked_content_provider(
  13843. "text/event-stream", [](size_t offset, DataSink &sink) {
  13844. if (offset == 0) {
  13845. std::string event = "id: evt-123\ndata: test\n\n";
  13846. sink.write(event.data(), event.size());
  13847. }
  13848. return false;
  13849. });
  13850. });
  13851. Client client("localhost", get_port());
  13852. sse::SSEClient sse(client, "/event-with-id");
  13853. std::atomic<bool> id_received{false};
  13854. sse.on_message([&](const sse::SSEMessage &msg) {
  13855. if (!msg.id.empty()) { id_received.store(true); }
  13856. });
  13857. sse.set_reconnect_interval(100);
  13858. sse.set_max_reconnect_attempts(1);
  13859. sse.start_async();
  13860. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13861. sse.stop();
  13862. EXPECT_TRUE(id_received.load());
  13863. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13864. }
  13865. // Test: Manual stop
  13866. TEST_F(SSEIntegrationTest, ManualStop) {
  13867. // Endpoint that sends one event and stays open briefly
  13868. std::atomic<bool> handler_running{true};
  13869. server_->Get("/stay-open", [&handler_running](const Request &,
  13870. Response &res) {
  13871. res.set_chunked_content_provider(
  13872. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13873. if (offset == 0) {
  13874. std::string event = "data: connected\n\n";
  13875. sink.write(event.data(), event.size());
  13876. }
  13877. // Keep connection open while handler_running is true
  13878. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13879. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13880. }
  13881. return false;
  13882. });
  13883. });
  13884. Client client("localhost", get_port());
  13885. sse::SSEClient sse(client, "/stay-open");
  13886. std::atomic<bool> connected{false};
  13887. sse.on_open([&connected]() { connected.store(true); });
  13888. sse.set_reconnect_interval(100);
  13889. sse.set_max_reconnect_attempts(1);
  13890. sse.start_async();
  13891. // Wait for connection to establish
  13892. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13893. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13894. }
  13895. EXPECT_TRUE(connected.load());
  13896. EXPECT_TRUE(sse.is_connected());
  13897. // Signal handler to stop
  13898. handler_running.store(false);
  13899. // Stop SSE client
  13900. sse.stop();
  13901. EXPECT_FALSE(sse.is_connected());
  13902. }
  13903. // Test: SSEClient with custom headers
  13904. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13905. // Setup a server endpoint that checks for custom header
  13906. std::atomic<bool> header_received{false};
  13907. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13908. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13909. header_received.store(true);
  13910. }
  13911. res.set_chunked_content_provider("text/event-stream",
  13912. [](size_t, DataSink &) { return false; });
  13913. });
  13914. Client client("localhost", get_port());
  13915. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13916. sse::SSEClient sse(client, "/header-check", headers);
  13917. sse.set_max_reconnect_attempts(1);
  13918. sse.start_async();
  13919. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13920. sse.stop();
  13921. EXPECT_TRUE(header_received.load());
  13922. }
  13923. // Test: Reconnect interval configuration
  13924. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13925. Client client("localhost", get_port());
  13926. sse::SSEClient sse(client, "/events");
  13927. auto &result = sse.set_reconnect_interval(500);
  13928. // Builder pattern should return reference to self
  13929. EXPECT_EQ(&result, &sse);
  13930. }
  13931. // Test: Max reconnect attempts
  13932. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13933. // Connect to non-existent port to force reconnects
  13934. Client client("localhost", 59998);
  13935. sse::SSEClient sse(client, "/events");
  13936. std::atomic<int> error_count{0};
  13937. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13938. sse.set_reconnect_interval(50);
  13939. sse.set_max_reconnect_attempts(2);
  13940. auto start = std::chrono::steady_clock::now();
  13941. sse.start(); // Blocking call
  13942. auto end = std::chrono::steady_clock::now();
  13943. // Should have stopped after 2 failed attempts
  13944. EXPECT_GE(error_count.load(), 2);
  13945. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13946. auto duration =
  13947. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13948. #ifdef _WIN32
  13949. // Windows is much slower for socket connection failures
  13950. EXPECT_LT(duration.count(), 7000);
  13951. #else
  13952. EXPECT_LT(duration.count(), 1000);
  13953. #endif
  13954. }
  13955. // Test: Multi-line data in integration
  13956. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13957. // Endpoint with multi-line data
  13958. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13959. res.set_chunked_content_provider(
  13960. "text/event-stream", [](size_t offset, DataSink &sink) {
  13961. if (offset == 0) {
  13962. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13963. sink.write(event.data(), event.size());
  13964. }
  13965. return false;
  13966. });
  13967. });
  13968. Client client("localhost", get_port());
  13969. sse::SSEClient sse(client, "/multiline-data");
  13970. std::string received_data;
  13971. std::mutex data_mutex;
  13972. sse.on_message([&](const sse::SSEMessage &msg) {
  13973. std::lock_guard<std::mutex> lock(data_mutex);
  13974. received_data = msg.data;
  13975. });
  13976. sse.set_reconnect_interval(100);
  13977. sse.set_max_reconnect_attempts(1);
  13978. sse.start_async();
  13979. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13980. sse.stop();
  13981. std::lock_guard<std::mutex> lock(data_mutex);
  13982. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13983. }
  13984. // Test: Auto-reconnect after server disconnection
  13985. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13986. std::atomic<int> connection_count{0};
  13987. std::atomic<int> message_count{0};
  13988. // Endpoint that sends one event and closes, forcing reconnect
  13989. server_->Get("/reconnect-test",
  13990. [&connection_count](const Request &, Response &res) {
  13991. connection_count.fetch_add(1);
  13992. res.set_chunked_content_provider(
  13993. "text/event-stream", [](size_t offset, DataSink &sink) {
  13994. if (offset == 0) {
  13995. std::string event = "data: hello\n\n";
  13996. sink.write(event.data(), event.size());
  13997. }
  13998. return false; // Close connection after sending
  13999. });
  14000. });
  14001. Client client("localhost", get_port());
  14002. sse::SSEClient sse(client, "/reconnect-test");
  14003. sse.on_message([&message_count](const sse::SSEMessage &) {
  14004. message_count.fetch_add(1);
  14005. });
  14006. sse.set_reconnect_interval(100);
  14007. sse.set_max_reconnect_attempts(3);
  14008. sse.start_async();
  14009. // Wait long enough for multiple reconnects
  14010. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14011. sse.stop();
  14012. // Should have connected multiple times (initial + reconnects)
  14013. EXPECT_GE(connection_count.load(), 2);
  14014. // Should have received messages from multiple connections
  14015. EXPECT_GE(message_count.load(), 2);
  14016. }
  14017. // Test: Last-Event-ID sent on reconnect
  14018. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14019. std::atomic<int> connection_count{0};
  14020. std::vector<std::string> received_last_event_ids;
  14021. std::mutex id_mutex;
  14022. // Endpoint that checks Last-Event-ID header and sends event with ID
  14023. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14024. int conn = connection_count.fetch_add(1);
  14025. // Capture the Last-Event-ID header from each connection
  14026. {
  14027. std::lock_guard<std::mutex> lock(id_mutex);
  14028. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14029. }
  14030. res.set_chunked_content_provider(
  14031. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14032. if (offset == 0) {
  14033. std::string event =
  14034. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14035. sink.write(event.data(), event.size());
  14036. }
  14037. return false;
  14038. });
  14039. });
  14040. Client client("localhost", get_port());
  14041. sse::SSEClient sse(client, "/reconnect-with-id");
  14042. sse.set_reconnect_interval(100);
  14043. sse.set_max_reconnect_attempts(3);
  14044. sse.start_async();
  14045. // Wait for at least 2 connections
  14046. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14047. sse.stop();
  14048. // Verify behavior
  14049. std::lock_guard<std::mutex> lock(id_mutex);
  14050. EXPECT_GE(received_last_event_ids.size(), 2u);
  14051. // First connection should have no Last-Event-ID
  14052. if (!received_last_event_ids.empty()) {
  14053. EXPECT_EQ(received_last_event_ids[0], "");
  14054. }
  14055. // Second connection should have Last-Event-ID from first connection
  14056. if (received_last_event_ids.size() >= 2) {
  14057. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14058. }
  14059. }
  14060. // Test: set_headers updates headers used on reconnect
  14061. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14062. std::vector<std::string> received_tokens;
  14063. std::mutex token_mutex;
  14064. // Endpoint that captures Authorization header
  14065. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14066. {
  14067. std::lock_guard<std::mutex> lock(token_mutex);
  14068. received_tokens.push_back(req.get_header_value("Authorization"));
  14069. }
  14070. res.set_chunked_content_provider(
  14071. "text/event-stream", [](size_t offset, DataSink &sink) {
  14072. if (offset == 0) {
  14073. std::string event = "data: hello\n\n";
  14074. sink.write(event.data(), event.size());
  14075. }
  14076. return false; // Close connection to trigger reconnect
  14077. });
  14078. });
  14079. Client client("localhost", get_port());
  14080. Headers headers = {{"Authorization", "Bearer old-token"}};
  14081. sse::SSEClient sse(client, "/auth-check", headers);
  14082. // Update headers on each successful connection
  14083. sse.on_open(
  14084. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14085. sse.set_reconnect_interval(100);
  14086. sse.set_max_reconnect_attempts(3);
  14087. sse.start_async();
  14088. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14089. sse.stop();
  14090. std::lock_guard<std::mutex> lock(token_mutex);
  14091. ASSERT_GE(received_tokens.size(), 2u);
  14092. // First connection uses original header
  14093. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14094. // Second connection uses updated header from set_headers
  14095. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14096. }
  14097. // Test: 401 allows reconnection (so on_error can refresh headers)
  14098. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14099. std::atomic<int> connection_count{0};
  14100. // Endpoint: returns 401 on first attempt, 200 on second
  14101. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14102. int conn = connection_count.fetch_add(1);
  14103. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14104. res.status = StatusCode::Unauthorized_401;
  14105. res.set_content("Unauthorized", "text/plain");
  14106. return;
  14107. }
  14108. res.set_chunked_content_provider(
  14109. "text/event-stream", [](size_t offset, DataSink &sink) {
  14110. if (offset == 0) {
  14111. std::string event = "data: authenticated\n\n";
  14112. sink.write(event.data(), event.size());
  14113. }
  14114. return false;
  14115. });
  14116. });
  14117. Client client("localhost", get_port());
  14118. Headers headers = {{"Authorization", "Bearer expired"}};
  14119. sse::SSEClient sse(client, "/auth-retry", headers);
  14120. std::atomic<bool> message_received{false};
  14121. // Refresh token on error
  14122. sse.on_error(
  14123. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14124. sse.on_message([&](const sse::SSEMessage &msg) {
  14125. if (msg.data == "authenticated") { message_received.store(true); }
  14126. });
  14127. sse.set_reconnect_interval(100);
  14128. sse.set_max_reconnect_attempts(3);
  14129. sse.start_async();
  14130. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14131. sse.stop();
  14132. // Should have reconnected after 401 and succeeded with new token
  14133. EXPECT_GE(connection_count.load(), 2);
  14134. EXPECT_TRUE(message_received.load());
  14135. }
  14136. TEST(Issue2318Test, EmptyHostString) {
  14137. {
  14138. httplib::Client cli_empty("", PORT);
  14139. auto res = cli_empty.Get("/");
  14140. ASSERT_FALSE(res);
  14141. EXPECT_EQ(httplib::Error::Connection, res.error());
  14142. }
  14143. {
  14144. httplib::Client cli(" ", PORT);
  14145. auto res = cli.Get("/");
  14146. ASSERT_FALSE(res);
  14147. EXPECT_EQ(httplib::Error::Connection, res.error());
  14148. }
  14149. }
  14150. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14151. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14152. Server svr;
  14153. // Set a small payload limit (1KB)
  14154. svr.set_payload_max_length(1024);
  14155. svr.Post("/test", [&](const Request &req, Response &res) {
  14156. res.set_content("Body size: " + std::to_string(req.body.size()),
  14157. "text/plain");
  14158. });
  14159. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14160. auto se = detail::scope_exit([&] {
  14161. svr.stop();
  14162. listen_thread.join();
  14163. });
  14164. svr.wait_until_ready();
  14165. // Create data that compresses well but exceeds limit when decompressed
  14166. // 8KB of repeated null bytes compresses to a very small size
  14167. std::string original_data(8 * 1024, '\0');
  14168. // Compress the data using gzip
  14169. std::string compressed_data;
  14170. detail::gzip_compressor compressor;
  14171. compressor.compress(original_data.data(), original_data.size(), true,
  14172. [&](const char *data, size_t size) {
  14173. compressed_data.append(data, size);
  14174. return true;
  14175. });
  14176. // Verify compression worked (compressed should be much smaller)
  14177. ASSERT_LT(compressed_data.size(), original_data.size());
  14178. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14179. // Send compressed data with Content-Encoding: gzip
  14180. Client cli(HOST, PORT);
  14181. Headers headers = {{"Content-Encoding", "gzip"}};
  14182. auto res =
  14183. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14184. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14185. ASSERT_TRUE(res);
  14186. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14187. }
  14188. #endif
  14189. // ============================================================================
  14190. // OpenSSL-Specific Tests
  14191. // ============================================================================
  14192. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14193. X509 *readCertificate(const std::string &strFileName) {
  14194. std::ifstream inStream(strFileName);
  14195. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14196. std::istreambuf_iterator<char>());
  14197. if (strCertPEM.empty()) return (nullptr);
  14198. BIO *pbCert = BIO_new(BIO_s_mem());
  14199. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14200. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14201. BIO_free(pbCert);
  14202. return (pCert);
  14203. }
  14204. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14205. std::ifstream inStream(strFileName);
  14206. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14207. std::istreambuf_iterator<char>());
  14208. if (strPrivateKeyPEM.empty()) return (nullptr);
  14209. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14210. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14211. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14212. BIO_free(pbPrivKey);
  14213. return (pPrivateKey);
  14214. }
  14215. TEST(BindServerTest, UpdateCerts) {
  14216. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14217. int port = svr.bind_to_any_port("0.0.0.0");
  14218. ASSERT_TRUE(svr.is_valid());
  14219. ASSERT_TRUE(port > 0);
  14220. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14221. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14222. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14223. ASSERT_TRUE(cert != nullptr);
  14224. ASSERT_TRUE(ca_cert != nullptr);
  14225. ASSERT_TRUE(key != nullptr);
  14226. X509_STORE *cert_store = X509_STORE_new();
  14227. X509_STORE_add_cert(cert_store, ca_cert);
  14228. // svr.update_certs(cert, key, cert_store); // deprecated
  14229. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14230. CLIENT_CA_CERT_FILE);
  14231. ASSERT_TRUE(svr.is_valid());
  14232. svr.stop();
  14233. X509_STORE_free(cert_store);
  14234. X509_free(cert);
  14235. X509_free(ca_cert);
  14236. EVP_PKEY_free(key);
  14237. }
  14238. // Test that update_certs() updates client CA list correctly
  14239. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14240. // Start with file-based constructor
  14241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14242. ASSERT_TRUE(svr.is_valid());
  14243. // Initially no client CA list should be set
  14244. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14245. ASSERT_TRUE(ssl_ctx != nullptr);
  14246. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14247. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14248. EXPECT_EQ(0, count_before);
  14249. // Now update with client CA (PEM string)
  14250. std::string cert_pem, key_pem, ca_pem;
  14251. read_file(SERVER_CERT_FILE, cert_pem);
  14252. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14253. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14254. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14255. ASSERT_TRUE(svr.is_valid());
  14256. // Now client CA list should be set
  14257. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14258. ASSERT_TRUE(ca_list_after != nullptr);
  14259. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14260. }
  14261. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14262. // Test that the file-path SSLServer constructor properly sets the client CA
  14263. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14264. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14265. ASSERT_TRUE(svr.is_valid());
  14266. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14267. ASSERT_TRUE(ssl_ctx != nullptr);
  14268. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14269. ASSERT_TRUE(ca_list != nullptr);
  14270. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14271. }
  14272. #endif
  14273. // ============================================================================
  14274. // MbedTLS-Specific Tests
  14275. // ============================================================================
  14276. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14277. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14278. using namespace httplib::tls;
  14279. // Track if callback was invoked
  14280. bool callback_invoked = false;
  14281. // The callback receives void* ctx which is actually MbedTlsContext*
  14282. // We can access the mbedtls_ssl_config via the context
  14283. auto setup_callback = [&callback_invoked](void *ctx) {
  14284. callback_invoked = true;
  14285. // Cast to MbedTlsContext* to access the ssl config
  14286. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14287. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14288. // Use static variables to hold certificate data (simplified for test)
  14289. static mbedtls_x509_crt own_cert;
  14290. static mbedtls_pk_context own_key;
  14291. static mbedtls_x509_crt ca_chain;
  14292. static bool initialized = false;
  14293. if (!initialized) {
  14294. mbedtls_x509_crt_init(&own_cert);
  14295. mbedtls_pk_init(&own_key);
  14296. mbedtls_x509_crt_init(&ca_chain);
  14297. // Load server certificate
  14298. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14299. return false;
  14300. }
  14301. // Load server private key
  14302. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14303. #if MBEDTLS_VERSION_MAJOR >= 3
  14304. ,
  14305. mbedtls_ctr_drbg_random, nullptr
  14306. #endif
  14307. ) != 0) {
  14308. return false;
  14309. }
  14310. // Load CA chain for client verification
  14311. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14312. return false;
  14313. }
  14314. initialized = true;
  14315. }
  14316. // Configure the SSL config
  14317. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14318. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14319. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14320. // Set minimum TLS version using mbedTLS native API
  14321. #if MBEDTLS_VERSION_MAJOR >= 3
  14322. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14323. #else
  14324. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14325. MBEDTLS_SSL_MINOR_VERSION_3);
  14326. #endif
  14327. return true;
  14328. };
  14329. SSLServer svr(setup_callback);
  14330. ASSERT_TRUE(svr.is_valid());
  14331. ASSERT_TRUE(callback_invoked);
  14332. svr.Get("/test", [&](const Request &req, Response &res) {
  14333. res.set_content("test", "text/plain");
  14334. auto cert = req.peer_cert();
  14335. ASSERT_TRUE(static_cast<bool>(cert));
  14336. auto common_name = cert.subject_cn();
  14337. EXPECT_EQ("Common Name", common_name);
  14338. });
  14339. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14340. auto se = detail::scope_exit([&] {
  14341. svr.stop();
  14342. t.join();
  14343. ASSERT_FALSE(svr.is_running());
  14344. });
  14345. svr.wait_until_ready();
  14346. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14347. cli.enable_server_certificate_verification(false);
  14348. cli.set_connection_timeout(30);
  14349. auto res = cli.Get("/test");
  14350. ASSERT_TRUE(res);
  14351. ASSERT_EQ(StatusCode::OK_200, res->status);
  14352. }
  14353. #endif
  14354. // WebSocket Tests
  14355. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14356. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14357. // defining the meaning of these bits has been negotiated.
  14358. auto make_frame = [](uint8_t first_byte) {
  14359. std::string frame;
  14360. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14361. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14362. frame += "Hello";
  14363. return frame;
  14364. };
  14365. // RSV1 set (0x40)
  14366. {
  14367. detail::BufferStream strm;
  14368. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14369. ws::Opcode opcode;
  14370. std::string payload;
  14371. bool fin;
  14372. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14373. false, 1024));
  14374. }
  14375. // RSV2 set (0x20)
  14376. {
  14377. detail::BufferStream strm;
  14378. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14379. ws::Opcode opcode;
  14380. std::string payload;
  14381. bool fin;
  14382. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14383. false, 1024));
  14384. }
  14385. // RSV3 set (0x10)
  14386. {
  14387. detail::BufferStream strm;
  14388. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14389. ws::Opcode opcode;
  14390. std::string payload;
  14391. bool fin;
  14392. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14393. false, 1024));
  14394. }
  14395. // No RSV bits set - should succeed
  14396. {
  14397. detail::BufferStream strm;
  14398. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14399. ws::Opcode opcode;
  14400. std::string payload;
  14401. bool fin;
  14402. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14403. false, 1024));
  14404. EXPECT_EQ(ws::Opcode::Text, opcode);
  14405. EXPECT_EQ("Hello", payload);
  14406. EXPECT_TRUE(fin);
  14407. }
  14408. }
  14409. TEST(WebSocketTest, ControlFrameValidation) {
  14410. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14411. // payload length <= 125.
  14412. // Ping with FIN=0 - must be rejected
  14413. {
  14414. detail::BufferStream strm;
  14415. std::string frame;
  14416. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14417. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14418. strm.write(frame.data(), frame.size());
  14419. ws::Opcode opcode;
  14420. std::string payload;
  14421. bool fin;
  14422. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14423. false, 1024));
  14424. }
  14425. // Close with FIN=0 - must be rejected
  14426. {
  14427. detail::BufferStream strm;
  14428. std::string frame;
  14429. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14430. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14431. strm.write(frame.data(), frame.size());
  14432. ws::Opcode opcode;
  14433. std::string payload;
  14434. bool fin;
  14435. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14436. false, 1024));
  14437. }
  14438. // Ping with payload_len=126 (extended length) - must be rejected
  14439. {
  14440. detail::BufferStream strm;
  14441. std::string frame;
  14442. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14443. frame += static_cast<char>(126); // payload_len=126 (>125)
  14444. frame += static_cast<char>(0x00); // extended length high byte
  14445. frame += static_cast<char>(126); // extended length low byte
  14446. frame += std::string(126, 'x');
  14447. strm.write(frame.data(), frame.size());
  14448. ws::Opcode opcode;
  14449. std::string payload;
  14450. bool fin;
  14451. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14452. false, 1024));
  14453. }
  14454. // Ping with FIN=1 and payload_len=125 - should succeed
  14455. {
  14456. detail::BufferStream strm;
  14457. std::string frame;
  14458. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14459. frame += static_cast<char>(125); // payload_len=125
  14460. frame += std::string(125, 'x');
  14461. strm.write(frame.data(), frame.size());
  14462. ws::Opcode opcode;
  14463. std::string payload;
  14464. bool fin;
  14465. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14466. false, 1024));
  14467. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14468. EXPECT_EQ(125u, payload.size());
  14469. EXPECT_TRUE(fin);
  14470. }
  14471. }
  14472. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14473. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14474. // length MUST be 0.
  14475. // MSB set - must be rejected
  14476. {
  14477. detail::BufferStream strm;
  14478. std::string frame;
  14479. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14480. frame += static_cast<char>(127); // 64-bit extended length
  14481. frame += static_cast<char>(0x80); // MSB set (invalid)
  14482. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14483. strm.write(frame.data(), frame.size());
  14484. ws::Opcode opcode;
  14485. std::string payload;
  14486. bool fin;
  14487. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14488. false, 1024));
  14489. }
  14490. // MSB clear - should pass length parsing (will be rejected by max_len,
  14491. // but that's a different check; use a small length to verify)
  14492. {
  14493. detail::BufferStream strm;
  14494. std::string frame;
  14495. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14496. frame += static_cast<char>(127); // 64-bit extended length
  14497. frame += std::string(7, '\0'); // high bytes = 0
  14498. frame += static_cast<char>(0x03); // length = 3
  14499. frame += "abc";
  14500. strm.write(frame.data(), frame.size());
  14501. ws::Opcode opcode;
  14502. std::string payload;
  14503. bool fin;
  14504. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14505. false, 1024));
  14506. EXPECT_EQ(ws::Opcode::Text, opcode);
  14507. EXPECT_EQ("abc", payload);
  14508. }
  14509. }
  14510. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14511. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14512. // Valid UTF-8
  14513. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14514. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14515. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14516. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14517. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14518. // Invalid UTF-8
  14519. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14520. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14521. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14522. EXPECT_FALSE(
  14523. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14524. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14525. }
  14526. TEST(WebSocketTest, ConnectAndDisconnect) {
  14527. Server svr;
  14528. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14529. std::string msg;
  14530. while (ws.read(msg)) {}
  14531. });
  14532. auto port = svr.bind_to_any_port(HOST);
  14533. std::thread t([&]() { svr.listen_after_bind(); });
  14534. svr.wait_until_ready();
  14535. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14536. ASSERT_TRUE(client.connect());
  14537. EXPECT_TRUE(client.is_open());
  14538. client.close();
  14539. EXPECT_FALSE(client.is_open());
  14540. svr.stop();
  14541. t.join();
  14542. }
  14543. TEST(WebSocketTest, ValidURL) {
  14544. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14545. EXPECT_TRUE(ws1.is_valid());
  14546. ws::WebSocketClient ws2("ws://example.com/path");
  14547. EXPECT_TRUE(ws2.is_valid());
  14548. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14549. EXPECT_TRUE(ws3.is_valid());
  14550. #ifdef CPPHTTPLIB_SSL_ENABLED
  14551. ws::WebSocketClient wss1("wss://example.com/path");
  14552. EXPECT_TRUE(wss1.is_valid());
  14553. ws::WebSocketClient wss2("wss://example.com:443/path");
  14554. EXPECT_TRUE(wss2.is_valid());
  14555. #endif
  14556. }
  14557. TEST(WebSocketTest, InvalidURL) {
  14558. // No scheme
  14559. ws::WebSocketClient ws1("localhost:8080/path");
  14560. EXPECT_FALSE(ws1.is_valid());
  14561. // No path
  14562. ws::WebSocketClient ws2("ws://localhost:8080");
  14563. EXPECT_FALSE(ws2.is_valid());
  14564. // Empty string
  14565. ws::WebSocketClient ws3("");
  14566. EXPECT_FALSE(ws3.is_valid());
  14567. // Missing host
  14568. ws::WebSocketClient ws4("ws://:8080/path");
  14569. EXPECT_FALSE(ws4.is_valid());
  14570. // Port number overflow — should not crash
  14571. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14572. EXPECT_FALSE(ws5.is_valid());
  14573. // Port out of range
  14574. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14575. EXPECT_FALSE(ws6.is_valid());
  14576. }
  14577. TEST(WebSocketTest, UnsupportedScheme) {
  14578. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14579. ws::WebSocketClient ws1("http://localhost:8080/path");
  14580. EXPECT_FALSE(ws1.is_valid());
  14581. ws::WebSocketClient ws2("https://localhost:8080/path");
  14582. EXPECT_FALSE(ws2.is_valid());
  14583. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14584. EXPECT_FALSE(ws3.is_valid());
  14585. #else
  14586. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14587. std::invalid_argument);
  14588. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14589. std::invalid_argument);
  14590. #endif
  14591. }
  14592. TEST(WebSocketTest, ConnectWhenInvalid) {
  14593. ws::WebSocketClient ws("not a valid url");
  14594. EXPECT_FALSE(ws.is_valid());
  14595. EXPECT_FALSE(ws.connect());
  14596. }
  14597. TEST(WebSocketTest, DefaultPort) {
  14598. ws::WebSocketClient ws1("ws://example.com/path");
  14599. EXPECT_TRUE(ws1.is_valid());
  14600. // ws:// defaults to port 80 (verified by successful parse)
  14601. #ifdef CPPHTTPLIB_SSL_ENABLED
  14602. ws::WebSocketClient ws2("wss://example.com/path");
  14603. EXPECT_TRUE(ws2.is_valid());
  14604. // wss:// defaults to port 443 (verified by successful parse)
  14605. #endif
  14606. }
  14607. TEST(WebSocketTest, IPv6LiteralAddress) {
  14608. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14609. EXPECT_TRUE(ws1.is_valid());
  14610. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14611. EXPECT_TRUE(ws2.is_valid());
  14612. }
  14613. TEST(WebSocketTest, ComplexPath) {
  14614. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14615. EXPECT_TRUE(ws1.is_valid());
  14616. ws::WebSocketClient ws2("ws://localhost:8080/");
  14617. EXPECT_TRUE(ws2.is_valid());
  14618. }
  14619. class WebSocketIntegrationTest : public ::testing::Test {
  14620. protected:
  14621. void SetUp() override {
  14622. server_ = httplib::detail::make_unique<Server>();
  14623. setup_server();
  14624. start_server();
  14625. }
  14626. void TearDown() override {
  14627. server_->stop();
  14628. if (server_thread_.joinable()) { server_thread_.join(); }
  14629. }
  14630. void setup_server() {
  14631. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14632. std::string msg;
  14633. ws::ReadResult ret;
  14634. while ((ret = ws.read(msg))) {
  14635. if (ret == ws::Binary) {
  14636. ws.send(msg.data(), msg.size());
  14637. } else {
  14638. ws.send(msg);
  14639. }
  14640. }
  14641. });
  14642. server_->WebSocket("/ws-echo-string",
  14643. [](const Request &, ws::WebSocket &ws) {
  14644. std::string msg;
  14645. while (ws.read(msg)) {
  14646. ws.send("echo: " + msg);
  14647. }
  14648. });
  14649. server_->WebSocket(
  14650. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14651. // Echo back request metadata
  14652. ws.send("path:" + req.path);
  14653. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14654. std::string msg;
  14655. while (ws.read(msg)) {}
  14656. });
  14657. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14658. std::string msg;
  14659. ws.read(msg); // wait for a message
  14660. ws.close();
  14661. });
  14662. server_->WebSocket("/ws-close-status",
  14663. [](const Request &, ws::WebSocket &ws) {
  14664. std::string msg;
  14665. ws.read(msg); // wait for a message
  14666. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14667. });
  14668. server_->WebSocket(
  14669. "/ws-subprotocol",
  14670. [](const Request &, ws::WebSocket &ws) {
  14671. std::string msg;
  14672. while (ws.read(msg)) {
  14673. ws.send(msg);
  14674. }
  14675. },
  14676. [](const std::vector<std::string> &protocols) -> std::string {
  14677. for (const auto &p : protocols) {
  14678. if (p == "graphql-ws") { return p; }
  14679. }
  14680. return "";
  14681. });
  14682. }
  14683. void start_server() {
  14684. port_ = server_->bind_to_any_port(HOST);
  14685. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14686. server_->wait_until_ready();
  14687. }
  14688. std::unique_ptr<Server> server_;
  14689. std::thread server_thread_;
  14690. int port_ = 0;
  14691. };
  14692. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14693. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14694. "/ws-echo");
  14695. ASSERT_TRUE(client.connect());
  14696. ASSERT_TRUE(client.is_open());
  14697. ASSERT_TRUE(client.send("Hello WebSocket"));
  14698. std::string msg;
  14699. EXPECT_EQ(ws::Text, client.read(msg));
  14700. EXPECT_EQ("Hello WebSocket", msg);
  14701. client.close();
  14702. }
  14703. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14704. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14705. "/ws-echo");
  14706. ASSERT_TRUE(client.connect());
  14707. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14708. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14709. std::string msg;
  14710. EXPECT_EQ(ws::Binary, client.read(msg));
  14711. EXPECT_EQ(binary_data, msg);
  14712. client.close();
  14713. }
  14714. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14715. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14716. "/ws-echo");
  14717. ASSERT_TRUE(client.connect());
  14718. for (int i = 0; i < 10; i++) {
  14719. auto text = "message " + std::to_string(i);
  14720. ASSERT_TRUE(client.send(text));
  14721. std::string msg;
  14722. ASSERT_TRUE(client.read(msg));
  14723. EXPECT_EQ(text, msg);
  14724. }
  14725. client.close();
  14726. }
  14727. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14728. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14729. "/ws-close");
  14730. ASSERT_TRUE(client.connect());
  14731. // Send a message to trigger the server to close
  14732. ASSERT_TRUE(client.send("trigger close"));
  14733. // The server will close, so read should return false
  14734. std::string msg;
  14735. EXPECT_FALSE(client.read(msg));
  14736. EXPECT_FALSE(client.is_open());
  14737. }
  14738. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14739. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14740. "/ws-echo");
  14741. ASSERT_TRUE(client.connect());
  14742. // 128KB message
  14743. std::string large_data(128 * 1024, 'X');
  14744. ASSERT_TRUE(client.send(large_data));
  14745. std::string msg;
  14746. ASSERT_TRUE(client.read(msg));
  14747. EXPECT_EQ(large_data, msg);
  14748. client.close();
  14749. }
  14750. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14751. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14752. "/ws-echo");
  14753. ASSERT_TRUE(client.connect());
  14754. const int num_threads = 4;
  14755. std::vector<std::thread> threads;
  14756. std::atomic<int> send_count{0};
  14757. for (int t = 0; t < num_threads; t++) {
  14758. threads.emplace_back([&client, &send_count, t]() {
  14759. for (int i = 0; i < 5; i++) {
  14760. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14761. if (client.send(text)) { send_count++; }
  14762. }
  14763. });
  14764. }
  14765. for (auto &th : threads) {
  14766. th.join();
  14767. }
  14768. int received = 0;
  14769. std::string msg;
  14770. while (received < send_count.load()) {
  14771. if (!client.read(msg)) { break; }
  14772. received++;
  14773. }
  14774. EXPECT_EQ(send_count.load(), received);
  14775. client.close();
  14776. }
  14777. TEST_F(WebSocketIntegrationTest, ReadString) {
  14778. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14779. "/ws-echo-string");
  14780. ASSERT_TRUE(client.connect());
  14781. ASSERT_TRUE(client.send("hello"));
  14782. std::string msg;
  14783. ASSERT_TRUE(client.read(msg));
  14784. EXPECT_EQ("echo: hello", msg);
  14785. ASSERT_TRUE(client.send("world"));
  14786. ASSERT_TRUE(client.read(msg));
  14787. EXPECT_EQ("echo: world", msg);
  14788. client.close();
  14789. }
  14790. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14791. Headers headers = {{"X-Test-Header", "test-value"}};
  14792. ws::WebSocketClient client(
  14793. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14794. ASSERT_TRUE(client.connect());
  14795. std::string msg;
  14796. ASSERT_TRUE(client.read(msg));
  14797. EXPECT_EQ("path:/ws-request-info", msg);
  14798. ASSERT_TRUE(client.read(msg));
  14799. EXPECT_EQ("header:test-value", msg);
  14800. client.close();
  14801. }
  14802. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14803. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14804. "/ws-echo");
  14805. client.set_read_timeout(1, 0); // 1 second
  14806. ASSERT_TRUE(client.connect());
  14807. // Don't send anything — server echo handler waits for a message,
  14808. // so read() should time out and return false.
  14809. std::string msg;
  14810. EXPECT_FALSE(client.read(msg));
  14811. }
  14812. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14814. "/ws-echo");
  14815. client.set_read_timeout(5, 0);
  14816. ASSERT_TRUE(client.connect());
  14817. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14818. // The server should reject it and close the connection.
  14819. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14820. client.send(oversized);
  14821. // The server's read() should have failed due to payload limit,
  14822. // so our read() should return false (connection closed).
  14823. std::string msg;
  14824. EXPECT_FALSE(client.read(msg));
  14825. }
  14826. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14827. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14828. "/ws-echo");
  14829. client.set_read_timeout(10, 0);
  14830. ASSERT_TRUE(client.connect());
  14831. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14832. // This should succeed.
  14833. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14834. ASSERT_TRUE(client.send(at_limit));
  14835. std::string msg;
  14836. ASSERT_TRUE(client.read(msg));
  14837. EXPECT_EQ(at_limit.size(), msg.size());
  14838. client.close();
  14839. }
  14840. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14841. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14842. "/nonexistent");
  14843. EXPECT_FALSE(client.connect());
  14844. EXPECT_FALSE(client.is_open());
  14845. }
  14846. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14847. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14848. "/ws-echo");
  14849. ASSERT_TRUE(client.connect());
  14850. ASSERT_TRUE(client.send(""));
  14851. std::string msg;
  14852. EXPECT_EQ(ws::Text, client.read(msg));
  14853. EXPECT_EQ("", msg);
  14854. client.close();
  14855. }
  14856. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14857. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14858. "/ws-echo");
  14859. // First connection
  14860. ASSERT_TRUE(client.connect());
  14861. ASSERT_TRUE(client.send("first"));
  14862. std::string msg;
  14863. ASSERT_TRUE(client.read(msg));
  14864. EXPECT_EQ("first", msg);
  14865. client.close();
  14866. EXPECT_FALSE(client.is_open());
  14867. // Reconnect using the same client object
  14868. ASSERT_TRUE(client.connect());
  14869. ASSERT_TRUE(client.is_open());
  14870. ASSERT_TRUE(client.send("second"));
  14871. ASSERT_TRUE(client.read(msg));
  14872. EXPECT_EQ("second", msg);
  14873. client.close();
  14874. }
  14875. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14876. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14877. "/ws-close-status");
  14878. ASSERT_TRUE(client.connect());
  14879. // Trigger the server to close with GoingAway status
  14880. ASSERT_TRUE(client.send("trigger"));
  14881. // read() should return false after receiving the close frame
  14882. std::string msg;
  14883. EXPECT_FALSE(client.read(msg));
  14884. EXPECT_FALSE(client.is_open());
  14885. }
  14886. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14887. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14888. "/ws-echo");
  14889. ASSERT_TRUE(client.connect());
  14890. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14891. EXPECT_FALSE(client.is_open());
  14892. }
  14893. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14894. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14895. ws::WebSocketClient client(
  14896. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14897. ASSERT_TRUE(client.connect());
  14898. // Server should have selected graphql-ws
  14899. EXPECT_EQ("graphql-ws", client.subprotocol());
  14900. client.close();
  14901. }
  14902. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14903. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14904. ws::WebSocketClient client(
  14905. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14906. ASSERT_TRUE(client.connect());
  14907. // Server should not have selected any subprotocol
  14908. EXPECT_TRUE(client.subprotocol().empty());
  14909. client.close();
  14910. }
  14911. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14912. // Connect without requesting any subprotocol
  14913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14914. "/ws-subprotocol");
  14915. ASSERT_TRUE(client.connect());
  14916. EXPECT_TRUE(client.subprotocol().empty());
  14917. client.close();
  14918. }
  14919. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14920. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14921. "/ws-echo");
  14922. client.set_tcp_nodelay(true);
  14923. client.set_connection_timeout(3, 0);
  14924. bool socket_options_called = false;
  14925. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14926. ASSERT_TRUE(client.connect());
  14927. ASSERT_TRUE(client.is_open());
  14928. EXPECT_TRUE(socket_options_called);
  14929. ASSERT_TRUE(client.send("hello"));
  14930. std::string msg;
  14931. auto result = client.read(msg);
  14932. EXPECT_EQ(result, ws::ReadResult::Text);
  14933. EXPECT_EQ(msg, "hello");
  14934. client.close();
  14935. }
  14936. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14937. Server svr;
  14938. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14939. if (!req.has_header("Authorization")) {
  14940. res.status = StatusCode::Unauthorized_401;
  14941. res.set_content("Unauthorized", "text/plain");
  14942. return Server::HandlerResponse::Handled;
  14943. }
  14944. return Server::HandlerResponse::Unhandled;
  14945. });
  14946. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14947. std::string msg;
  14948. while (ws.read(msg)) {
  14949. ws.send(msg);
  14950. }
  14951. });
  14952. auto port = svr.bind_to_any_port("localhost");
  14953. std::thread t([&]() { svr.listen_after_bind(); });
  14954. svr.wait_until_ready();
  14955. // Without Authorization header - should be rejected before upgrade
  14956. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14957. EXPECT_FALSE(client1.connect());
  14958. // With Authorization header - should succeed
  14959. Headers headers = {{"Authorization", "Bearer token123"}};
  14960. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14961. headers);
  14962. ASSERT_TRUE(client2.connect());
  14963. ASSERT_TRUE(client2.send("hello"));
  14964. std::string msg;
  14965. ASSERT_TRUE(client2.read(msg));
  14966. EXPECT_EQ("hello", msg);
  14967. client2.close();
  14968. svr.stop();
  14969. t.join();
  14970. }
  14971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14972. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14973. protected:
  14974. void SetUp() override {
  14975. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14976. SERVER_PRIVATE_KEY_FILE);
  14977. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14978. std::string msg;
  14979. ws::ReadResult ret;
  14980. while ((ret = ws.read(msg))) {
  14981. if (ret == ws::Binary) {
  14982. ws.send(msg.data(), msg.size());
  14983. } else {
  14984. ws.send(msg);
  14985. }
  14986. }
  14987. });
  14988. port_ = server_->bind_to_any_port(HOST);
  14989. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14990. server_->wait_until_ready();
  14991. }
  14992. void TearDown() override {
  14993. server_->stop();
  14994. if (server_thread_.joinable()) { server_thread_.join(); }
  14995. }
  14996. std::unique_ptr<SSLServer> server_;
  14997. std::thread server_thread_;
  14998. int port_ = 0;
  14999. };
  15000. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15001. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15002. "/ws-echo");
  15003. client.enable_server_certificate_verification(false);
  15004. ASSERT_TRUE(client.connect());
  15005. ASSERT_TRUE(client.is_open());
  15006. ASSERT_TRUE(client.send("Hello WSS"));
  15007. std::string msg;
  15008. EXPECT_EQ(ws::Text, client.read(msg));
  15009. EXPECT_EQ("Hello WSS", msg);
  15010. client.close();
  15011. }
  15012. #endif
  15013. #if !defined(_WIN32)
  15014. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15015. auto secret_dir = std::string("./symlink_test_secret");
  15016. auto served_dir = std::string("./symlink_test_served");
  15017. auto secret_file = secret_dir + "/secret.txt";
  15018. auto symlink_path = served_dir + "/escape";
  15019. // Setup: create directories and files
  15020. mkdir(secret_dir.c_str(), 0755);
  15021. mkdir(served_dir.c_str(), 0755);
  15022. {
  15023. std::ofstream ofs(secret_file);
  15024. ofs << "SECRET_DATA";
  15025. }
  15026. // Create symlink using absolute path so it resolves correctly
  15027. #ifdef PATH_MAX
  15028. char abs_secret[PATH_MAX];
  15029. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15030. #else
  15031. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15032. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15033. ASSERT_NE(nullptr, abs_secret);
  15034. #endif
  15035. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15036. auto se = detail::scope_exit([&] {
  15037. unlink(symlink_path.c_str());
  15038. unlink(secret_file.c_str());
  15039. rmdir(served_dir.c_str());
  15040. rmdir(secret_dir.c_str());
  15041. });
  15042. Server svr;
  15043. svr.set_mount_point("/", served_dir);
  15044. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15045. auto se2 = detail::scope_exit([&] {
  15046. svr.stop();
  15047. listen_thread.join();
  15048. });
  15049. svr.wait_until_ready();
  15050. Client cli("localhost", PORT);
  15051. // Symlink pointing outside base dir should be blocked
  15052. auto res = cli.Get("/escape/secret.txt");
  15053. ASSERT_TRUE(res);
  15054. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15055. }
  15056. #endif
  15057. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15058. // A GET request with Content-Length to a static file handler must have its
  15059. // body drained before the keep-alive connection is reused. Otherwise the
  15060. // unread body bytes are interpreted as the next HTTP request.
  15061. //
  15062. // The body is sent AFTER receiving the first response (as in the original
  15063. // PoC) so that the stream_line_reader cannot buffer it together with the
  15064. // headers of the first request.
  15065. Server svr;
  15066. svr.set_mount_point("/", "./www");
  15067. std::atomic<int> smuggled_count(0);
  15068. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15069. smuggled_count++;
  15070. res.set_content("oops", "text/plain");
  15071. });
  15072. auto port = svr.bind_to_any_port("localhost");
  15073. thread t = thread([&] { svr.listen_after_bind(); });
  15074. auto se = detail::scope_exit([&] {
  15075. svr.stop();
  15076. t.join();
  15077. });
  15078. svr.wait_until_ready();
  15079. auto error = Error::Success;
  15080. auto sock = detail::create_client_socket(
  15081. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15082. /*connection_timeout_sec=*/2, 0,
  15083. /*read_timeout_sec=*/2, 0,
  15084. /*write_timeout_sec=*/2, 0, std::string(), error);
  15085. ASSERT_NE(INVALID_SOCKET, sock);
  15086. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15087. // The "smuggled" request will be sent as the body of the outer GET
  15088. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15089. "Host: localhost\r\n"
  15090. "Connection: close\r\n"
  15091. "\r\n";
  15092. // Step 1: Send only the outer request headers (no body yet)
  15093. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15094. "Host: localhost\r\n"
  15095. "Content-Length: " +
  15096. std::to_string(smuggled.size()) +
  15097. "\r\n"
  15098. "\r\n";
  15099. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15100. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15101. // Step 2: Read the first response (server serves file without reading body)
  15102. std::string first_response;
  15103. char buf[4096];
  15104. for (;;) {
  15105. auto n = recv(sock, buf, sizeof(buf), 0);
  15106. if (n <= 0) break;
  15107. first_response.append(buf, static_cast<size_t>(n));
  15108. // Stop once we have a complete response (headers + body)
  15109. auto hdr_end = first_response.find("\r\n\r\n");
  15110. if (hdr_end != std::string::npos) {
  15111. // Check for Content-Length to know when the body is complete
  15112. auto cl_pos = first_response.find("Content-Length:");
  15113. if (cl_pos != std::string::npos) {
  15114. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15115. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15116. auto cl = std::stoul(
  15117. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15118. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15119. } else {
  15120. break; // No Content-Length, assume headers-only response
  15121. }
  15122. }
  15123. }
  15124. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15125. // Step 3: Now send the body, which looks like a new HTTP request.
  15126. // On a vulnerable server the keep-alive loop reads this as a second request.
  15127. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15128. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15129. // Step 4: Try to read a second response (should NOT exist after fix)
  15130. std::string second_response;
  15131. for (;;) {
  15132. auto n = recv(sock, buf, sizeof(buf), 0);
  15133. if (n <= 0) break;
  15134. second_response.append(buf, static_cast<size_t>(n));
  15135. }
  15136. // The smuggled request must NOT have been processed
  15137. EXPECT_EQ(0, smuggled_count.load());
  15138. }
  15139. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15140. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15141. // must be rejected with 400 Bad Request.
  15142. Server svr;
  15143. svr.Post("/test", [&](const Request &, Response &res) {
  15144. res.set_content("ok", "text/plain");
  15145. });
  15146. thread t = thread([&] { svr.listen(HOST, PORT); });
  15147. auto se = detail::scope_exit([&] {
  15148. svr.stop();
  15149. t.join();
  15150. ASSERT_FALSE(svr.is_running());
  15151. });
  15152. svr.wait_until_ready();
  15153. // Exact "chunked"
  15154. {
  15155. auto req = "POST /test HTTP/1.1\r\n"
  15156. "Host: localhost\r\n"
  15157. "Content-Length: 5\r\n"
  15158. "Transfer-Encoding: chunked\r\n"
  15159. "Connection: close\r\n"
  15160. "\r\n"
  15161. "hello";
  15162. std::string response;
  15163. ASSERT_TRUE(send_request(1, req, &response));
  15164. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15165. response.substr(0, response.find("\r\n")));
  15166. }
  15167. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15168. {
  15169. auto req = "POST /test HTTP/1.1\r\n"
  15170. "Host: localhost\r\n"
  15171. "Content-Length: 5\r\n"
  15172. "Transfer-Encoding: gzip, chunked\r\n"
  15173. "Connection: close\r\n"
  15174. "\r\n"
  15175. "hello";
  15176. std::string response;
  15177. ASSERT_TRUE(send_request(1, req, &response));
  15178. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15179. response.substr(0, response.find("\r\n")));
  15180. }
  15181. }