test.cc 558 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159
  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. #ifndef _WIN32
  11871. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11872. Server svr;
  11873. svr.Post("/post", [&](const Request &req, Response &res) {
  11874. res.set_content(req.body, "text/plain");
  11875. });
  11876. svr.Put("/put", [&](const Request &req, Response &res) {
  11877. res.set_content(req.body, "text/plain");
  11878. });
  11879. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11880. res.set_content(req.body, "text/plain");
  11881. });
  11882. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11883. res.set_content(req.body, "text/plain");
  11884. });
  11885. thread t = thread([&]() { svr.listen(HOST, PORT); });
  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. std::string resp;
  11893. // POST without Content-Length
  11894. ASSERT_TRUE(send_request(5,
  11895. "POST /post HTTP/1.1\r\n"
  11896. "Host: localhost\r\n"
  11897. "Connection: close\r\n"
  11898. "\r\n",
  11899. &resp));
  11900. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11901. // PUT without Content-Length
  11902. resp.clear();
  11903. ASSERT_TRUE(send_request(5,
  11904. "PUT /put HTTP/1.1\r\n"
  11905. "Host: localhost\r\n"
  11906. "Connection: close\r\n"
  11907. "\r\n",
  11908. &resp));
  11909. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11910. // PATCH without Content-Length
  11911. resp.clear();
  11912. ASSERT_TRUE(send_request(5,
  11913. "PATCH /patch HTTP/1.1\r\n"
  11914. "Host: localhost\r\n"
  11915. "Connection: close\r\n"
  11916. "\r\n",
  11917. &resp));
  11918. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11919. // DELETE without Content-Length
  11920. resp.clear();
  11921. ASSERT_TRUE(send_request(5,
  11922. "DELETE /delete HTTP/1.1\r\n"
  11923. "Host: localhost\r\n"
  11924. "Connection: close\r\n"
  11925. "\r\n",
  11926. &resp));
  11927. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11928. }
  11929. #endif
  11930. //==============================================================================
  11931. // open_stream() Tests
  11932. //==============================================================================
  11933. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11934. std::string result;
  11935. char buf[8192];
  11936. ssize_t n;
  11937. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11938. result.append(buf, static_cast<size_t>(n));
  11939. }
  11940. return result;
  11941. }
  11942. // Mock stream for unit tests
  11943. class MockStream : public Stream {
  11944. public:
  11945. std::string data;
  11946. size_t pos = 0;
  11947. ssize_t error_after = -1; // -1 = no error
  11948. explicit MockStream(const std::string &d, ssize_t err = -1)
  11949. : data(d), error_after(err) {}
  11950. bool is_readable() const override { return true; }
  11951. bool wait_readable() const override { return true; }
  11952. bool wait_writable() const override { return true; }
  11953. ssize_t read(char *ptr, size_t size) override {
  11954. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11955. if (pos >= data.size()) return 0;
  11956. size_t limit =
  11957. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11958. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11959. std::memcpy(ptr, data.data() + pos, to_read);
  11960. pos += to_read;
  11961. return static_cast<ssize_t>(to_read);
  11962. }
  11963. ssize_t write(const char *, size_t) override { return -1; }
  11964. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11965. ip = "127.0.0.1";
  11966. port = 0;
  11967. }
  11968. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11969. ip = "127.0.0.1";
  11970. port = 0;
  11971. }
  11972. socket_t socket() const override { return INVALID_SOCKET; }
  11973. time_t duration() const override { return 0; }
  11974. };
  11975. TEST(StreamHandleTest, Basic) {
  11976. ClientImpl::StreamHandle handle;
  11977. EXPECT_FALSE(handle.is_valid());
  11978. handle.response = detail::make_unique<Response>();
  11979. handle.error = Error::Connection;
  11980. EXPECT_FALSE(handle.is_valid());
  11981. handle.error = Error::Success;
  11982. EXPECT_TRUE(handle.is_valid());
  11983. }
  11984. TEST(BodyReaderTest, Basic) {
  11985. MockStream stream("Hello, World!");
  11986. detail::BodyReader reader;
  11987. reader.stream = &stream;
  11988. reader.content_length = 13;
  11989. char buf[32];
  11990. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11991. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11992. EXPECT_TRUE(reader.eof);
  11993. }
  11994. TEST(BodyReaderTest, NoStream) {
  11995. detail::BodyReader reader;
  11996. char buf[32];
  11997. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11998. EXPECT_EQ(Error::Connection, reader.last_error);
  11999. }
  12000. TEST(BodyReaderTest, Error) {
  12001. MockStream stream("Hello, World!", 5);
  12002. detail::BodyReader reader;
  12003. reader.stream = &stream;
  12004. reader.content_length = 13;
  12005. char buf[32];
  12006. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12007. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12008. EXPECT_EQ(Error::Read, reader.last_error);
  12009. }
  12010. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12011. // Mock-based StreamHandle tests relying on private internals are removed.
  12012. class OpenStreamTest : public ::testing::Test {
  12013. protected:
  12014. void SetUp() override {
  12015. svr_.Get("/hello", [](const Request &, Response &res) {
  12016. res.set_content("Hello World!", "text/plain");
  12017. });
  12018. svr_.Get("/large", [](const Request &, Response &res) {
  12019. res.set_content(std::string(10000, 'X'), "text/plain");
  12020. });
  12021. svr_.Get("/chunked", [](const Request &, Response &res) {
  12022. res.set_chunked_content_provider("text/plain",
  12023. [](size_t offset, DataSink &sink) {
  12024. if (offset < 15) {
  12025. sink.write("chunk", 5);
  12026. return true;
  12027. }
  12028. sink.done();
  12029. return true;
  12030. });
  12031. });
  12032. svr_.Get("/compressible", [](const Request &, Response &res) {
  12033. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12034. DataSink &sink) {
  12035. if (offset < 100 * 1024) {
  12036. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12037. sink.write(chunk.data(), chunk.size());
  12038. return true;
  12039. }
  12040. sink.done();
  12041. return true;
  12042. });
  12043. });
  12044. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12045. [](const Request & /*req*/, Response &res) {
  12046. auto i = new int(0);
  12047. res.set_header("Trailer", "Content-Length, X-Allowed");
  12048. res.set_chunked_content_provider(
  12049. "text/plain",
  12050. [i](size_t /*offset*/, DataSink &sink) {
  12051. switch (*i) {
  12052. case 0: sink.os << "123"; break;
  12053. case 1: sink.os << "456"; break;
  12054. case 2: sink.os << "789"; break;
  12055. case 3: {
  12056. sink.done_with_trailer(
  12057. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12058. } break;
  12059. }
  12060. (*i)++;
  12061. return true;
  12062. },
  12063. [i](bool success) {
  12064. EXPECT_TRUE(success);
  12065. delete i;
  12066. });
  12067. });
  12068. // Echo headers endpoint for header-related tests
  12069. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12070. std::string body;
  12071. for (const auto &h : req.headers) {
  12072. body.append(h.first);
  12073. body.push_back(':');
  12074. body.append(h.second);
  12075. body.push_back('\n');
  12076. }
  12077. res.set_content(body, "text/plain");
  12078. });
  12079. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12080. std::string body;
  12081. for (const auto &h : req.headers) {
  12082. body.append(h.first);
  12083. body.push_back(':');
  12084. body.append(h.second);
  12085. body.push_back('\n');
  12086. }
  12087. res.set_content(body, "text/plain");
  12088. });
  12089. port_ = svr_.bind_to_any_port("127.0.0.1");
  12090. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12091. svr_.wait_until_ready();
  12092. }
  12093. void TearDown() override {
  12094. svr_.stop();
  12095. if (thread_.joinable()) thread_.join();
  12096. }
  12097. Server svr_;
  12098. std::thread thread_;
  12099. int port_ = 0;
  12100. };
  12101. TEST_F(OpenStreamTest, Basic) {
  12102. Client cli("127.0.0.1", port_);
  12103. auto handle = cli.open_stream("GET", "/hello");
  12104. EXPECT_TRUE(handle.is_valid());
  12105. EXPECT_EQ("Hello World!", read_all(handle));
  12106. }
  12107. TEST_F(OpenStreamTest, SmallBuffer) {
  12108. Client cli("127.0.0.1", port_);
  12109. auto handle = cli.open_stream("GET", "/hello");
  12110. std::string result;
  12111. char buf[4];
  12112. ssize_t n;
  12113. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12114. result.append(buf, static_cast<size_t>(n));
  12115. EXPECT_EQ("Hello World!", result);
  12116. }
  12117. TEST_F(OpenStreamTest, DefaultHeaders) {
  12118. Client cli("127.0.0.1", port_);
  12119. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12120. {
  12121. auto handle = cli.open_stream("GET", "/echo-headers");
  12122. ASSERT_TRUE(handle.is_valid());
  12123. auto body = read_all(handle);
  12124. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12125. std::string::npos);
  12126. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12127. std::string::npos);
  12128. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12129. }
  12130. // open_stream POST with body and no explicit content_type should NOT add
  12131. // text/plain Content-Type (behavior differs from non-streaming path), but
  12132. // should include Content-Length
  12133. {
  12134. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12135. ASSERT_TRUE(handle.is_valid());
  12136. auto body = read_all(handle);
  12137. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12138. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12139. }
  12140. // open_stream POST with explicit Content-Type should preserve it
  12141. {
  12142. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12143. {{"Content-Type", "application/custom"}},
  12144. "{}", "application/custom");
  12145. ASSERT_TRUE(handle.is_valid());
  12146. auto body = read_all(handle);
  12147. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12148. }
  12149. // User-specified User-Agent must not be overwritten for stream API
  12150. {
  12151. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12152. {{"User-Agent", "MyAgent/1.2"}});
  12153. ASSERT_TRUE(handle.is_valid());
  12154. auto body = read_all(handle);
  12155. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12156. }
  12157. }
  12158. TEST_F(OpenStreamTest, Large) {
  12159. Client cli("127.0.0.1", port_);
  12160. auto handle = cli.open_stream("GET", "/large");
  12161. EXPECT_EQ(10000u, read_all(handle).size());
  12162. }
  12163. TEST_F(OpenStreamTest, ConnectionError) {
  12164. Client cli("127.0.0.1", 9999);
  12165. auto handle = cli.open_stream("GET", "/hello");
  12166. EXPECT_FALSE(handle.is_valid());
  12167. }
  12168. TEST_F(OpenStreamTest, Chunked) {
  12169. Client cli("127.0.0.1", port_);
  12170. auto handle = cli.open_stream("GET", "/chunked");
  12171. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12172. "Transfer-Encoding") == "chunked");
  12173. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12174. }
  12175. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12176. Client cli("127.0.0.1", port_);
  12177. auto handle =
  12178. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12179. ASSERT_TRUE(handle.is_valid());
  12180. // Consume body to allow trailers to be received/parsed
  12181. auto body = read_all(handle);
  12182. // Explicitly parse trailers (ensure trailers are available for assertion)
  12183. handle.parse_trailers_if_needed();
  12184. EXPECT_EQ(std::string("123456789"), body);
  12185. // The response should include a Trailer header declaring both names
  12186. ASSERT_TRUE(handle.response);
  12187. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12188. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12189. handle.response->get_header_value("Trailer"));
  12190. // Prohibited trailer must not be present
  12191. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12192. // Allowed trailer should be present
  12193. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12194. EXPECT_EQ(std::string("yes"),
  12195. handle.response->get_trailer_value("X-Allowed"));
  12196. // Verify trailers are NOT present as regular headers
  12197. EXPECT_EQ(std::string(""),
  12198. handle.response->get_header_value("Content-Length"));
  12199. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12200. }
  12201. static std::thread serve_single_response(std::promise<int> &port_promise,
  12202. const std::string &response) {
  12203. return std::thread([&port_promise, response] {
  12204. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12205. default_socket_options(srv);
  12206. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12207. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12208. sockaddr_in addr{};
  12209. addr.sin_family = AF_INET;
  12210. addr.sin_port = htons(0); // Let OS assign a free port
  12211. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12212. int opt = 1;
  12213. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12214. #ifdef _WIN32
  12215. reinterpret_cast<const char *>(&opt),
  12216. #else
  12217. &opt,
  12218. #endif
  12219. sizeof(opt));
  12220. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12221. ::listen(srv, 1) != 0) {
  12222. port_promise.set_value(-1);
  12223. detail::close_socket(srv);
  12224. return;
  12225. }
  12226. socklen_t addr_len = sizeof(addr);
  12227. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12228. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12229. sockaddr_in cli_addr{};
  12230. socklen_t cli_len = sizeof(cli_addr);
  12231. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12232. if (cli != INVALID_SOCKET) {
  12233. // Read the complete HTTP request (until the blank line that terminates
  12234. // headers) before sending the response. If the server closes the socket
  12235. // while the client's request data is still unread in the kernel receive
  12236. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12237. // connection on both sides: it discards the client's receive buffer
  12238. // (which already holds our response) and causes any in-progress write on
  12239. // the client to fail with ECONNRESET. Reading all request data first
  12240. // ensures close() emits a graceful FIN.
  12241. {
  12242. char rbuf[256];
  12243. std::string req;
  12244. while (req.find("\r\n\r\n") == std::string::npos) {
  12245. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12246. if (n <= 0) { break; }
  12247. req.append(rbuf, static_cast<size_t>(n));
  12248. }
  12249. }
  12250. ::send(cli,
  12251. #ifdef _WIN32
  12252. static_cast<const char *>(response.c_str()),
  12253. static_cast<int>(response.size()),
  12254. #else
  12255. response.c_str(), response.size(),
  12256. #endif
  12257. 0);
  12258. detail::close_socket(cli);
  12259. }
  12260. detail::close_socket(srv);
  12261. });
  12262. }
  12263. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12264. #ifndef _WIN32
  12265. signal(SIGPIPE, SIG_IGN);
  12266. #endif
  12267. std::promise<int> port_promise;
  12268. auto port_future = port_promise.get_future();
  12269. auto server_thread =
  12270. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12271. "Content-Type: text/plain\r\n"
  12272. "Content-Length: not-a-number\r\n"
  12273. "Connection: close\r\n"
  12274. "\r\n"
  12275. "hello");
  12276. auto port = port_future.get();
  12277. ASSERT_GT(port, 0);
  12278. Client cli("127.0.0.1", port);
  12279. auto handle = cli.open_stream("GET", "/");
  12280. EXPECT_FALSE(handle.is_valid());
  12281. server_thread.join();
  12282. }
  12283. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12284. #ifndef _WIN32
  12285. signal(SIGPIPE, SIG_IGN);
  12286. #endif
  12287. std::promise<int> port_promise;
  12288. auto port_future = port_promise.get_future();
  12289. auto server_thread = serve_single_response(
  12290. port_promise, "HTTP/1.1 200 OK\r\n"
  12291. "Content-Type: text/plain\r\n"
  12292. "Content-Length: 99999999999999999999999999\r\n"
  12293. "Connection: close\r\n"
  12294. "\r\n"
  12295. "hello");
  12296. auto port = port_future.get();
  12297. ASSERT_GT(port, 0);
  12298. // Before the fix, std::stoull would throw std::out_of_range here and
  12299. // crash the process. After the fix, strtoull silently clamps to
  12300. // ULLONG_MAX so the stream opens without crashing. The important thing
  12301. // is that the process does NOT terminate.
  12302. Client cli("127.0.0.1", port);
  12303. auto handle = cli.open_stream("GET", "/");
  12304. EXPECT_TRUE(handle.is_valid());
  12305. server_thread.join();
  12306. }
  12307. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12308. TEST_F(OpenStreamTest, Gzip) {
  12309. Client cli("127.0.0.1", port_);
  12310. auto handle = cli.open_stream("GET", "/compressible", {},
  12311. {{"Accept-Encoding", "gzip"}});
  12312. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12313. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12314. }
  12315. #endif
  12316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12317. TEST_F(OpenStreamTest, Brotli) {
  12318. Client cli("127.0.0.1", port_);
  12319. auto handle =
  12320. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12321. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12322. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12323. }
  12324. #endif
  12325. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12326. TEST_F(OpenStreamTest, Zstd) {
  12327. Client cli("127.0.0.1", port_);
  12328. auto handle = cli.open_stream("GET", "/compressible", {},
  12329. {{"Accept-Encoding", "zstd"}});
  12330. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12331. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12332. }
  12333. #endif
  12334. #ifdef CPPHTTPLIB_SSL_ENABLED
  12335. class SSLOpenStreamTest : public ::testing::Test {
  12336. protected:
  12337. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12338. void SetUp() override {
  12339. svr_.Get("/hello", [](const Request &, Response &res) {
  12340. res.set_content("Hello SSL World!", "text/plain");
  12341. });
  12342. svr_.Get("/chunked", [](const Request &, Response &res) {
  12343. res.set_chunked_content_provider("text/plain",
  12344. [](size_t offset, DataSink &sink) {
  12345. if (offset < 15) {
  12346. sink.write("chunk", 5);
  12347. return true;
  12348. }
  12349. sink.done();
  12350. return true;
  12351. });
  12352. });
  12353. svr_.Post("/echo", [](const Request &req, Response &res) {
  12354. res.set_content(req.body, req.get_header_value("Content-Type"));
  12355. });
  12356. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12357. std::string body = req.body;
  12358. res.set_chunked_content_provider(
  12359. "text/plain", [body](size_t offset, DataSink &sink) {
  12360. if (offset < body.size()) {
  12361. sink.write(body.data() + offset, body.size() - offset);
  12362. }
  12363. sink.done();
  12364. return true;
  12365. });
  12366. });
  12367. port_ = svr_.bind_to_any_port("127.0.0.1");
  12368. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12369. svr_.wait_until_ready();
  12370. }
  12371. void TearDown() override {
  12372. svr_.stop();
  12373. if (thread_.joinable()) thread_.join();
  12374. }
  12375. SSLServer svr_;
  12376. std::thread thread_;
  12377. int port_ = 0;
  12378. };
  12379. TEST_F(SSLOpenStreamTest, Basic) {
  12380. SSLClient cli("127.0.0.1", port_);
  12381. cli.enable_server_certificate_verification(false);
  12382. auto handle = cli.open_stream("GET", "/hello");
  12383. ASSERT_TRUE(handle.is_valid());
  12384. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12385. }
  12386. TEST_F(SSLOpenStreamTest, Chunked) {
  12387. SSLClient cli("127.0.0.1", port_);
  12388. cli.enable_server_certificate_verification(false);
  12389. auto handle = cli.open_stream("GET", "/chunked");
  12390. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12391. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12392. "Transfer-Encoding") == "chunked");
  12393. auto body = read_all(handle);
  12394. EXPECT_EQ("chunkchunkchunk", body);
  12395. }
  12396. TEST_F(SSLOpenStreamTest, Post) {
  12397. SSLClient cli("127.0.0.1", port_);
  12398. cli.enable_server_certificate_verification(false);
  12399. auto handle =
  12400. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12401. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12402. EXPECT_EQ(200, handle.response->status);
  12403. auto body = read_all(handle);
  12404. EXPECT_EQ("Hello SSL POST", body);
  12405. }
  12406. TEST_F(SSLOpenStreamTest, PostChunked) {
  12407. SSLClient cli("127.0.0.1", port_);
  12408. cli.enable_server_certificate_verification(false);
  12409. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12410. "Chunked SSL Data", "text/plain");
  12411. ASSERT_TRUE(handle.is_valid());
  12412. EXPECT_EQ(200, handle.response->status);
  12413. auto body = read_all(handle);
  12414. EXPECT_EQ("Chunked SSL Data", body);
  12415. }
  12416. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12417. // Content-Length is terminated by the server closing the connection. When the
  12418. // SSL peer sends a close_notify after the body, the client must treat it as a
  12419. // clean EOF and return a successful response rather than an error.
  12420. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12422. ASSERT_TRUE(svr.is_valid());
  12423. svr.set_keep_alive_max_count(1);
  12424. const std::string expected_body = "Hello from connection-close response!";
  12425. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12426. res.set_content_provider("text/plain",
  12427. [&](size_t offset, DataSink &sink) -> bool {
  12428. if (offset < expected_body.size()) {
  12429. sink.write(expected_body.data() + offset,
  12430. expected_body.size() - offset);
  12431. }
  12432. sink.done();
  12433. return true;
  12434. });
  12435. });
  12436. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12437. auto se = detail::scope_exit([&] {
  12438. svr.stop();
  12439. listen_thread.join();
  12440. ASSERT_FALSE(svr.is_running());
  12441. });
  12442. svr.wait_until_ready();
  12443. SSLClient cli(HOST, PORT);
  12444. cli.enable_server_certificate_verification(false);
  12445. auto res = cli.Get("/no-content-length");
  12446. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12447. EXPECT_EQ(StatusCode::OK_200, res->status);
  12448. EXPECT_EQ(expected_body, res->body);
  12449. }
  12450. #endif // CPPHTTPLIB_SSL_ENABLED
  12451. //==============================================================================
  12452. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12453. // results for various scenarios.
  12454. //==============================================================================
  12455. TEST(ParityTest, GetVsOpenStream) {
  12456. Server svr;
  12457. const std::string path = "/parity";
  12458. const std::string content = "Parity test content: hello world";
  12459. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12460. res.set_content(content, "text/plain");
  12461. });
  12462. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12463. auto se = detail::scope_exit([&] {
  12464. svr.stop();
  12465. t.join();
  12466. ASSERT_FALSE(svr.is_running());
  12467. });
  12468. svr.wait_until_ready();
  12469. Client cli(HOST, PORT);
  12470. // Non-stream path
  12471. auto r1 = cli.Get(path);
  12472. ASSERT_TRUE(r1);
  12473. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12474. // Stream path
  12475. auto h = cli.open_stream("GET", path);
  12476. ASSERT_TRUE(h.is_valid());
  12477. EXPECT_EQ(r1->body, read_all(h));
  12478. }
  12479. // Helper to compress data with provided compressor type T
  12480. template <typename Compressor>
  12481. static std::string compress_payload_for_parity(const std::string &in) {
  12482. std::string out;
  12483. Compressor compressor;
  12484. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12485. [&](const char *data, size_t n) {
  12486. out.append(data, n);
  12487. return true;
  12488. });
  12489. EXPECT_TRUE(ok);
  12490. return out;
  12491. }
  12492. // Helper function for compression parity tests
  12493. template <typename Compressor>
  12494. static void test_compression_parity(const std::string &original,
  12495. const std::string &path,
  12496. const std::string &encoding) {
  12497. const std::string compressed =
  12498. compress_payload_for_parity<Compressor>(original);
  12499. Server svr;
  12500. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12501. res.set_content(compressed, "application/octet-stream");
  12502. res.set_header("Content-Encoding", encoding);
  12503. });
  12504. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12505. auto se = detail::scope_exit([&] {
  12506. svr.stop();
  12507. t.join();
  12508. ASSERT_FALSE(svr.is_running());
  12509. });
  12510. svr.wait_until_ready();
  12511. Client cli(HOST, PORT);
  12512. // Non-streaming
  12513. {
  12514. auto res = cli.Get(path);
  12515. ASSERT_TRUE(res);
  12516. EXPECT_EQ(StatusCode::OK_200, res->status);
  12517. EXPECT_EQ(original, res->body);
  12518. }
  12519. // Streaming
  12520. {
  12521. auto h = cli.open_stream("GET", path);
  12522. ASSERT_TRUE(h.is_valid());
  12523. EXPECT_EQ(original, read_all(h));
  12524. }
  12525. }
  12526. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12527. TEST(ParityTest, Gzip) {
  12528. test_compression_parity<detail::gzip_compressor>(
  12529. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12530. }
  12531. #endif
  12532. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12533. TEST(ParityTest, Brotli) {
  12534. test_compression_parity<detail::brotli_compressor>(
  12535. "Hello, brotli parity test payload", "/parity-br", "br");
  12536. }
  12537. #endif
  12538. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12539. TEST(ParityTest, Zstd) {
  12540. test_compression_parity<detail::zstd_compressor>(
  12541. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12542. }
  12543. #endif
  12544. //==============================================================================
  12545. // New Stream API Tests
  12546. //==============================================================================
  12547. inline std::string read_body(httplib::stream::Result &result) {
  12548. std::string body;
  12549. while (result.next()) {
  12550. body.append(result.data(), result.size());
  12551. }
  12552. return body;
  12553. }
  12554. TEST(ClientConnectionTest, Basic) {
  12555. httplib::ClientConnection conn;
  12556. EXPECT_FALSE(conn.is_open());
  12557. conn.sock = 1;
  12558. EXPECT_TRUE(conn.is_open());
  12559. httplib::ClientConnection conn2(std::move(conn));
  12560. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12561. conn2.sock = INVALID_SOCKET;
  12562. }
  12563. // Unified test server for all stream::* tests
  12564. class StreamApiTest : public ::testing::Test {
  12565. protected:
  12566. void SetUp() override {
  12567. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12568. res.set_content("Hello World!", "text/plain");
  12569. });
  12570. svr_.Get("/echo-params",
  12571. [](const httplib::Request &req, httplib::Response &res) {
  12572. std::string r;
  12573. for (const auto &p : req.params) {
  12574. if (!r.empty()) r += "&";
  12575. r += p.first + "=" + p.second;
  12576. }
  12577. res.set_content(r, "text/plain");
  12578. });
  12579. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12580. res.set_content(req.body, req.get_header_value("Content-Type"));
  12581. });
  12582. svr_.Post("/echo-headers",
  12583. [](const httplib::Request &req, httplib::Response &res) {
  12584. std::string r;
  12585. for (const auto &h : req.headers)
  12586. r += h.first + ": " + h.second + "\n";
  12587. res.set_content(r, "text/plain");
  12588. });
  12589. svr_.Post("/echo-params",
  12590. [](const httplib::Request &req, httplib::Response &res) {
  12591. std::string r = "params:";
  12592. for (const auto &p : req.params)
  12593. r += p.first + "=" + p.second + ";";
  12594. res.set_content(r + " body:" + req.body, "text/plain");
  12595. });
  12596. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12597. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12598. });
  12599. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12600. res.set_content("PUT:" + req.body, "text/plain");
  12601. });
  12602. svr_.Patch("/echo",
  12603. [](const httplib::Request &req, httplib::Response &res) {
  12604. res.set_content("PATCH:" + req.body, "text/plain");
  12605. });
  12606. svr_.Delete(
  12607. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12608. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12609. "text/plain");
  12610. });
  12611. svr_.Get("/head-test",
  12612. [](const httplib::Request &, httplib::Response &res) {
  12613. res.set_content("body for HEAD", "text/plain");
  12614. });
  12615. svr_.Options("/options",
  12616. [](const httplib::Request &, httplib::Response &res) {
  12617. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12618. });
  12619. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12620. svr_.wait_until_ready();
  12621. }
  12622. void TearDown() override {
  12623. svr_.stop();
  12624. if (thread_.joinable()) thread_.join();
  12625. }
  12626. httplib::Server svr_;
  12627. std::thread thread_;
  12628. };
  12629. // stream::Get tests
  12630. TEST_F(StreamApiTest, GetBasic) {
  12631. httplib::Client cli(HOST, PORT);
  12632. auto result = httplib::stream::Get(cli, "/hello");
  12633. ASSERT_TRUE(result.is_valid());
  12634. EXPECT_EQ(200, result.status());
  12635. EXPECT_EQ("Hello World!", read_body(result));
  12636. }
  12637. TEST_F(StreamApiTest, GetWithParams) {
  12638. httplib::Client cli(HOST, PORT);
  12639. httplib::Params params{{"foo", "bar"}};
  12640. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12641. ASSERT_TRUE(result.is_valid());
  12642. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12643. }
  12644. TEST_F(StreamApiTest, GetConnectionError) {
  12645. httplib::Client cli(HOST, 9999);
  12646. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12647. }
  12648. TEST_F(StreamApiTest, Get404) {
  12649. httplib::Client cli(HOST, PORT);
  12650. auto result = httplib::stream::Get(cli, "/nonexistent");
  12651. EXPECT_TRUE(result.is_valid());
  12652. EXPECT_EQ(404, result.status());
  12653. }
  12654. // stream::Post tests
  12655. TEST_F(StreamApiTest, PostBasic) {
  12656. httplib::Client cli(HOST, PORT);
  12657. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12658. "application/json");
  12659. ASSERT_TRUE(result.is_valid());
  12660. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12661. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12662. }
  12663. TEST_F(StreamApiTest, PostWithHeaders) {
  12664. httplib::Client cli(HOST, PORT);
  12665. httplib::Headers headers{{"X-Custom", "value"}};
  12666. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12667. "text/plain");
  12668. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12669. }
  12670. TEST_F(StreamApiTest, PostWithParams) {
  12671. httplib::Client cli(HOST, PORT);
  12672. httplib::Params params{{"k", "v"}};
  12673. auto result =
  12674. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12675. auto body = read_body(result);
  12676. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12677. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12678. }
  12679. TEST_F(StreamApiTest, PostLarge) {
  12680. httplib::Client cli(HOST, PORT);
  12681. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12682. size_t total = 0;
  12683. while (result.next()) {
  12684. total += result.size();
  12685. }
  12686. EXPECT_EQ(100u * 1024u, total);
  12687. }
  12688. // stream::Put/Patch tests
  12689. TEST_F(StreamApiTest, PutAndPatch) {
  12690. httplib::Client cli(HOST, PORT);
  12691. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12692. EXPECT_EQ("PUT:test", read_body(put));
  12693. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12694. EXPECT_EQ("PATCH:test", read_body(patch));
  12695. }
  12696. // stream::Delete tests
  12697. TEST_F(StreamApiTest, Delete) {
  12698. httplib::Client cli(HOST, PORT);
  12699. auto del1 = httplib::stream::Delete(cli, "/resource");
  12700. EXPECT_EQ("Deleted", read_body(del1));
  12701. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12702. EXPECT_EQ("Deleted:data", read_body(del2));
  12703. }
  12704. // stream::Head/Options tests
  12705. TEST_F(StreamApiTest, HeadAndOptions) {
  12706. httplib::Client cli(HOST, PORT);
  12707. auto head = httplib::stream::Head(cli, "/head-test");
  12708. EXPECT_TRUE(head.is_valid());
  12709. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12710. auto opts = httplib::stream::Options(cli, "/options");
  12711. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12712. }
  12713. // SSL stream::* tests
  12714. #ifdef CPPHTTPLIB_SSL_ENABLED
  12715. class SSLStreamApiTest : public ::testing::Test {
  12716. protected:
  12717. void SetUp() override {
  12718. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12719. res.set_content("Hello SSL!", "text/plain");
  12720. });
  12721. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12722. res.set_content(req.body, "text/plain");
  12723. });
  12724. port_ = svr_.bind_to_any_port("127.0.0.1");
  12725. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12726. svr_.wait_until_ready();
  12727. }
  12728. void TearDown() override {
  12729. svr_.stop();
  12730. if (thread_.joinable()) thread_.join();
  12731. }
  12732. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12733. std::thread thread_;
  12734. int port_ = 0;
  12735. };
  12736. TEST_F(SSLStreamApiTest, GetAndPost) {
  12737. httplib::SSLClient cli("127.0.0.1", port_);
  12738. cli.enable_server_certificate_verification(false);
  12739. auto get = httplib::stream::Get(cli, "/hello");
  12740. EXPECT_EQ("Hello SSL!", read_body(get));
  12741. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12742. EXPECT_EQ("test", read_body(post));
  12743. }
  12744. #endif
  12745. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12746. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12747. // BodyReader
  12748. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12749. // Test that read timeout during streaming is detected
  12750. // Use a large content-length response where server delays mid-stream
  12751. Server svr;
  12752. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12753. // Send a large response with delay in the middle
  12754. res.set_content_provider(
  12755. 1000, // content_length
  12756. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12757. if (offset < 100) {
  12758. // Send first 100 bytes immediately
  12759. std::string data(100, 'A');
  12760. sink.write(data.c_str(), data.size());
  12761. return true;
  12762. }
  12763. // Then delay longer than client timeout
  12764. std::this_thread::sleep_for(std::chrono::seconds(3));
  12765. std::string data(900, 'B');
  12766. sink.write(data.c_str(), data.size());
  12767. return true;
  12768. });
  12769. });
  12770. auto port = 8091;
  12771. std::thread t([&]() { svr.listen("localhost", port); });
  12772. svr.wait_until_ready();
  12773. Client cli("localhost", port);
  12774. cli.set_read_timeout(1, 0); // 1 second timeout
  12775. auto handle = cli.open_stream("GET", "/slow-stream");
  12776. ASSERT_TRUE(handle.is_valid());
  12777. char buf[256];
  12778. ssize_t total = 0;
  12779. ssize_t n;
  12780. bool got_error = false;
  12781. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12782. total += n;
  12783. }
  12784. if (n < 0) {
  12785. got_error = true;
  12786. // Should be timeout or read error
  12787. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12788. handle.get_read_error() == Error::Read)
  12789. << "Actual error: " << to_string(handle.get_read_error());
  12790. }
  12791. // Either we got an error, or we got less data than expected
  12792. EXPECT_TRUE(got_error || total < 1000)
  12793. << "Expected timeout but got all " << total << " bytes";
  12794. svr.stop();
  12795. t.join();
  12796. }
  12797. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12798. // Test connection closed detection via BodyReader
  12799. Server svr;
  12800. std::atomic<bool> close_now{false};
  12801. svr.Get("/will-close", [&](const Request &, Response &res) {
  12802. res.set_content_provider(
  12803. 10000, // Large content_length that we won't fully send
  12804. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12805. if (offset < 100) {
  12806. std::string data(100, 'X');
  12807. sink.write(data.c_str(), data.size());
  12808. return true;
  12809. }
  12810. // Wait for signal then abort
  12811. while (!close_now) {
  12812. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12813. }
  12814. return false; // Abort - server will close connection
  12815. });
  12816. });
  12817. auto port = 8092;
  12818. std::thread t([&]() { svr.listen("localhost", port); });
  12819. svr.wait_until_ready();
  12820. Client cli("localhost", port);
  12821. auto handle = cli.open_stream("GET", "/will-close");
  12822. ASSERT_TRUE(handle.is_valid());
  12823. char buf[256];
  12824. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12825. EXPECT_GT(n, 0) << "First read should succeed";
  12826. // Signal server to close
  12827. close_now = true;
  12828. // Keep reading until error or EOF
  12829. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12830. // Keep reading
  12831. }
  12832. // Should get an error since content_length wasn't satisfied
  12833. if (n < 0) {
  12834. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12835. handle.get_read_error() == Error::Read)
  12836. << "Actual error: " << to_string(handle.get_read_error());
  12837. }
  12838. svr.stop();
  12839. t.join();
  12840. }
  12841. #ifdef CPPHTTPLIB_SSL_ENABLED
  12842. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12843. // Test that read timeout during SSL streaming is detected
  12844. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12845. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12846. res.set_content_provider(
  12847. 1000, "text/plain",
  12848. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12849. if (offset < 100) {
  12850. std::string data(100, 'A');
  12851. sink.write(data.c_str(), data.size());
  12852. return true;
  12853. }
  12854. std::this_thread::sleep_for(std::chrono::seconds(3));
  12855. std::string data(900, 'B');
  12856. sink.write(data.c_str(), data.size());
  12857. return true;
  12858. });
  12859. });
  12860. auto port = 8093;
  12861. std::thread t([&]() { svr.listen("localhost", port); });
  12862. svr.wait_until_ready();
  12863. SSLClient cli("localhost", port);
  12864. cli.enable_server_certificate_verification(false);
  12865. cli.set_read_timeout(1, 0); // 1 second timeout
  12866. auto handle = cli.open_stream("GET", "/slow-stream");
  12867. ASSERT_TRUE(handle.is_valid());
  12868. char buf[256];
  12869. ssize_t total = 0;
  12870. ssize_t n;
  12871. bool got_error = false;
  12872. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12873. total += n;
  12874. }
  12875. if (n < 0) {
  12876. got_error = true;
  12877. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12878. handle.get_read_error() == Error::Read)
  12879. << "Actual error: " << to_string(handle.get_read_error());
  12880. }
  12881. EXPECT_TRUE(got_error || total < 1000)
  12882. << "Expected timeout but got all " << total << " bytes";
  12883. svr.stop();
  12884. t.join();
  12885. }
  12886. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12887. // Test SSL connection closed detection
  12888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12889. std::atomic<bool> close_now{false};
  12890. svr.Get("/will-close", [&](const Request &, Response &res) {
  12891. res.set_content_provider(
  12892. 10000, "text/plain",
  12893. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12894. if (offset < 100) {
  12895. std::string data(100, 'X');
  12896. sink.write(data.c_str(), data.size());
  12897. return true;
  12898. }
  12899. while (!close_now) {
  12900. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12901. }
  12902. return false;
  12903. });
  12904. });
  12905. auto port = 8094;
  12906. std::thread t([&]() { svr.listen("localhost", port); });
  12907. svr.wait_until_ready();
  12908. SSLClient cli("localhost", port);
  12909. cli.enable_server_certificate_verification(false);
  12910. auto handle = cli.open_stream("GET", "/will-close");
  12911. ASSERT_TRUE(handle.is_valid());
  12912. char buf[256];
  12913. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12914. EXPECT_GT(n, 0);
  12915. // Signal server to close
  12916. close_now = true;
  12917. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12918. // Keep reading
  12919. }
  12920. if (n < 0) {
  12921. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12922. handle.get_read_error() == Error::Read)
  12923. << "Actual error: " << to_string(handle.get_read_error());
  12924. }
  12925. svr.stop();
  12926. t.join();
  12927. }
  12928. #endif
  12929. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12930. using namespace httplib;
  12931. // Create a test file
  12932. const char *fname = "etag_testfile.txt";
  12933. const char *content = "etag-content";
  12934. {
  12935. std::ofstream ofs(fname);
  12936. ofs << content;
  12937. ASSERT_TRUE(ofs.good());
  12938. }
  12939. Server svr;
  12940. svr.set_mount_point("/static", ".");
  12941. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12942. svr.wait_until_ready();
  12943. Client cli(HOST, PORT);
  12944. // First request: should get 200 with ETag header
  12945. auto res1 = cli.Get("/static/etag_testfile.txt");
  12946. ASSERT_TRUE(res1);
  12947. ASSERT_EQ(200, res1->status);
  12948. ASSERT_TRUE(res1->has_header("ETag"));
  12949. std::string etag = res1->get_header_value("ETag");
  12950. EXPECT_FALSE(etag.empty());
  12951. // Verify ETag format: W/"hex-hex"
  12952. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12953. EXPECT_EQ('W', etag[0]);
  12954. EXPECT_EQ('/', etag[1]);
  12955. EXPECT_EQ('"', etag[2]);
  12956. EXPECT_EQ('"', etag.back());
  12957. // Exact match: expect 304 Not Modified
  12958. Headers h2 = {{"If-None-Match", etag}};
  12959. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12960. ASSERT_TRUE(res2);
  12961. EXPECT_EQ(304, res2->status);
  12962. // Wildcard match: expect 304 Not Modified
  12963. Headers h3 = {{"If-None-Match", "*"}};
  12964. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12965. ASSERT_TRUE(res3);
  12966. EXPECT_EQ(304, res3->status);
  12967. // Non-matching ETag: expect 200
  12968. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12969. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12970. ASSERT_TRUE(res4);
  12971. EXPECT_EQ(200, res4->status);
  12972. // Multiple ETags with one matching: expect 304
  12973. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12974. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12975. ASSERT_TRUE(res5);
  12976. EXPECT_EQ(304, res5->status);
  12977. svr.stop();
  12978. t.join();
  12979. std::remove(fname);
  12980. }
  12981. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12982. using namespace httplib;
  12983. Server svr;
  12984. svr.set_mount_point("/static", ".");
  12985. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12986. svr.wait_until_ready();
  12987. Client cli(HOST, PORT);
  12988. // Send If-None-Match: * to a non-existent file
  12989. Headers h = {{"If-None-Match", "*"}};
  12990. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12991. ASSERT_TRUE(res);
  12992. EXPECT_EQ(404, res->status);
  12993. svr.stop();
  12994. t.join();
  12995. }
  12996. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12997. using namespace httplib;
  12998. // Create a test file
  12999. const char *fname = "etag_boundary_testfile.txt";
  13000. const char *content = "boundary-test";
  13001. {
  13002. std::ofstream ofs(fname);
  13003. ofs << content;
  13004. ASSERT_TRUE(ofs.good());
  13005. }
  13006. Server svr;
  13007. svr.set_mount_point("/static", ".");
  13008. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13009. svr.wait_until_ready();
  13010. Client cli(HOST, PORT);
  13011. // Get the actual ETag
  13012. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13013. ASSERT_TRUE(res1);
  13014. ASSERT_EQ(200, res1->status);
  13015. ASSERT_TRUE(res1->has_header("ETag"));
  13016. std::string etag = res1->get_header_value("ETag");
  13017. // Test 1: Very long ETag value (longer than actual ETag)
  13018. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13019. Headers h1 = {{"If-None-Match", "W/"
  13020. "\"very-long-etag-value-that-is-much-longer-"
  13021. "than-the-actual-etag-value\""}};
  13022. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13023. ASSERT_TRUE(res2);
  13024. EXPECT_EQ(200, res2->status); // Should not match
  13025. // Test 2: Long string followed by wildcard
  13026. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13027. // string)
  13028. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13029. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13030. ASSERT_TRUE(res3);
  13031. EXPECT_EQ(304, res3->status); // Should match on "*"
  13032. // Test 3: Wildcard followed by long string
  13033. // Should match on "*" immediately and return 304
  13034. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13035. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13036. ASSERT_TRUE(res4);
  13037. EXPECT_EQ(304, res4->status); // Should match on "*"
  13038. // Test 4: Multiple long non-matching values
  13039. // Should NOT match and return 200 (test that all comparisons are safe)
  13040. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13041. "W/\"second-long-non-matching-value\", "
  13042. "W/\"third-long-non-matching-value\""}};
  13043. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13044. ASSERT_TRUE(res5);
  13045. EXPECT_EQ(200, res5->status); // Should not match
  13046. // Test 5: Single character that is not "*" (edge case)
  13047. Headers h5 = {{"If-None-Match", "X"}};
  13048. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13049. ASSERT_TRUE(res6);
  13050. EXPECT_EQ(200, res6->status); // Should not match
  13051. svr.stop();
  13052. t.join();
  13053. std::remove(fname);
  13054. }
  13055. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13056. using namespace httplib;
  13057. // Create a test file
  13058. const char *fname = "ims_testfile.txt";
  13059. const char *content = "if-modified-since-test";
  13060. {
  13061. std::ofstream ofs(fname);
  13062. ofs << content;
  13063. ASSERT_TRUE(ofs.good());
  13064. }
  13065. Server svr;
  13066. svr.set_mount_point("/static", ".");
  13067. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13068. svr.wait_until_ready();
  13069. Client cli(HOST, PORT);
  13070. // First request: should get 200 with Last-Modified header
  13071. auto res1 = cli.Get("/static/ims_testfile.txt");
  13072. ASSERT_TRUE(res1);
  13073. ASSERT_EQ(200, res1->status);
  13074. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13075. std::string last_modified = res1->get_header_value("Last-Modified");
  13076. EXPECT_FALSE(last_modified.empty());
  13077. // If-Modified-Since with same time: expect 304
  13078. Headers h2 = {{"If-Modified-Since", last_modified}};
  13079. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13080. ASSERT_TRUE(res2);
  13081. EXPECT_EQ(304, res2->status);
  13082. // If-Modified-Since with future time: expect 304
  13083. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13084. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13085. ASSERT_TRUE(res3);
  13086. EXPECT_EQ(304, res3->status);
  13087. // If-Modified-Since with past time: expect 200
  13088. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13089. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13090. ASSERT_TRUE(res4);
  13091. EXPECT_EQ(200, res4->status);
  13092. // If-None-Match takes precedence over If-Modified-Since
  13093. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13094. ASSERT_TRUE(res1->has_header("ETag"));
  13095. std::string etag = res1->get_header_value("ETag");
  13096. Headers h5 = {{"If-None-Match", etag},
  13097. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13098. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13099. ASSERT_TRUE(res5);
  13100. EXPECT_EQ(304, res5->status);
  13101. svr.stop();
  13102. t.join();
  13103. std::remove(fname);
  13104. }
  13105. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13106. using namespace httplib;
  13107. Server svr;
  13108. // Endpoint that returns compressible content
  13109. svr.Get("/compressible", [](const Request &, Response &res) {
  13110. // Return a large enough body to trigger compression
  13111. std::string body(1000, 'a');
  13112. res.set_content(body, "text/plain");
  13113. });
  13114. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13115. svr.wait_until_ready();
  13116. Client cli(HOST, PORT);
  13117. // Request with gzip support: should get Vary header when compressed
  13118. cli.set_compress(true);
  13119. auto res1 = cli.Get("/compressible");
  13120. ASSERT_TRUE(res1);
  13121. EXPECT_EQ(200, res1->status);
  13122. // If Content-Encoding is set, Vary should also be set
  13123. if (res1->has_header("Content-Encoding")) {
  13124. EXPECT_TRUE(res1->has_header("Vary"));
  13125. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13126. }
  13127. // Request without Accept-Encoding header: should not have compression
  13128. Headers h_no_compress;
  13129. auto res2 = cli.Get("/compressible", h_no_compress);
  13130. ASSERT_TRUE(res2);
  13131. EXPECT_EQ(200, res2->status);
  13132. // Verify Vary header is present when compression is applied
  13133. // (the exact behavior depends on server configuration)
  13134. svr.stop();
  13135. t.join();
  13136. }
  13137. TEST(ETagTest, IfRangeWithETag) {
  13138. using namespace httplib;
  13139. // Create a test file with known content
  13140. const char *fname = "if_range_testfile.txt";
  13141. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13142. {
  13143. std::ofstream ofs(fname);
  13144. ofs << content;
  13145. ASSERT_TRUE(ofs.good());
  13146. }
  13147. Server svr;
  13148. svr.set_mount_point("/static", ".");
  13149. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13150. svr.wait_until_ready();
  13151. Client cli(HOST, PORT);
  13152. // First request: get ETag
  13153. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13154. ASSERT_TRUE(res1);
  13155. ASSERT_EQ(200, res1->status);
  13156. ASSERT_TRUE(res1->has_header("ETag"));
  13157. std::string etag = res1->get_header_value("ETag");
  13158. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13159. // Since our server generates weak ETags (W/"..."), If-Range with our
  13160. // ETag should NOT result in partial content - it should return full content.
  13161. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13162. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13163. ASSERT_TRUE(res2);
  13164. // Weak ETag in If-Range -> full content (200), not partial (206)
  13165. EXPECT_EQ(200, res2->status);
  13166. EXPECT_EQ(content, res2->body);
  13167. EXPECT_FALSE(res2->has_header("Content-Range"));
  13168. // Range request with non-matching If-Range (ETag): should get 200 (full
  13169. // content)
  13170. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13171. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13172. ASSERT_TRUE(res3);
  13173. EXPECT_EQ(200, res3->status);
  13174. EXPECT_EQ(content, res3->body);
  13175. EXPECT_FALSE(res3->has_header("Content-Range"));
  13176. // Range request with strong ETag (hypothetical - our server doesn't generate
  13177. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13178. // should return full content)
  13179. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13180. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13181. ASSERT_TRUE(res4);
  13182. EXPECT_EQ(200, res4->status);
  13183. EXPECT_EQ(content, res4->body);
  13184. EXPECT_FALSE(res4->has_header("Content-Range"));
  13185. svr.stop();
  13186. t.join();
  13187. std::remove(fname);
  13188. }
  13189. TEST(ETagTest, IfRangeWithDate) {
  13190. using namespace httplib;
  13191. // Create a test file
  13192. const char *fname = "if_range_date_testfile.txt";
  13193. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13194. {
  13195. std::ofstream ofs(fname);
  13196. ofs << content;
  13197. ASSERT_TRUE(ofs.good());
  13198. }
  13199. Server svr;
  13200. svr.set_mount_point("/static", ".");
  13201. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13202. svr.wait_until_ready();
  13203. Client cli(HOST, PORT);
  13204. // First request: get Last-Modified
  13205. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13206. ASSERT_TRUE(res1);
  13207. ASSERT_EQ(200, res1->status);
  13208. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13209. std::string last_modified = res1->get_header_value("Last-Modified");
  13210. // Range request with matching If-Range (date): should get 206
  13211. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13212. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13213. ASSERT_TRUE(res2);
  13214. EXPECT_EQ(206, res2->status);
  13215. EXPECT_EQ("FGHIJ", res2->body);
  13216. // Range request with old If-Range date: should get 200 (full content)
  13217. Headers h3 = {{"Range", "bytes=5-9"},
  13218. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13219. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13220. ASSERT_TRUE(res3);
  13221. EXPECT_EQ(200, res3->status);
  13222. EXPECT_EQ(content, res3->body);
  13223. // Range request with future If-Range date: should get 206
  13224. Headers h4 = {{"Range", "bytes=0-4"},
  13225. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13226. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13227. ASSERT_TRUE(res4);
  13228. EXPECT_EQ(206, res4->status);
  13229. EXPECT_EQ("ABCDE", res4->body);
  13230. svr.stop();
  13231. t.join();
  13232. std::remove(fname);
  13233. }
  13234. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13235. using namespace httplib;
  13236. const char *fname = "etag_malformed.txt";
  13237. const char *content = "malformed-etag";
  13238. {
  13239. std::ofstream ofs(fname);
  13240. ofs << content;
  13241. ASSERT_TRUE(ofs.good());
  13242. }
  13243. Server svr;
  13244. svr.set_mount_point("/static", ".");
  13245. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13246. svr.wait_until_ready();
  13247. Client cli(HOST, PORT);
  13248. // baseline: should get 200 and an ETag
  13249. auto res1 = cli.Get("/static/etag_malformed.txt");
  13250. ASSERT_TRUE(res1);
  13251. ASSERT_EQ(200, res1->status);
  13252. ASSERT_TRUE(res1->has_header("ETag"));
  13253. // Malformed ETag value (missing quotes) should be treated as non-matching
  13254. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13255. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13256. ASSERT_TRUE(res_bad);
  13257. EXPECT_EQ(200, res_bad->status);
  13258. // Whitespace-only header value should be considered invalid / non-matching
  13259. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13260. "Host: localhost\r\n"
  13261. "If-None-Match: \r\n"
  13262. "Connection: close\r\n"
  13263. "\r\n";
  13264. std::string out;
  13265. ASSERT_TRUE(send_request(5, raw_req, &out));
  13266. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13267. svr.stop();
  13268. t.join();
  13269. std::remove(fname);
  13270. }
  13271. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13272. using namespace httplib;
  13273. const char *fname = "ims_invalid_format.txt";
  13274. const char *content = "ims-bad-format";
  13275. {
  13276. std::ofstream ofs(fname);
  13277. ofs << content;
  13278. ASSERT_TRUE(ofs.good());
  13279. }
  13280. Server svr;
  13281. svr.set_mount_point("/static", ".");
  13282. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13283. svr.wait_until_ready();
  13284. Client cli(HOST, PORT);
  13285. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13286. ASSERT_TRUE(res1);
  13287. ASSERT_EQ(200, res1->status);
  13288. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13289. // If-Modified-Since with invalid format should not result in 304
  13290. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13291. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13292. ASSERT_TRUE(res_bad);
  13293. EXPECT_EQ(200, res_bad->status);
  13294. // If-Range with invalid date format should be treated as mismatch -> full
  13295. // content (200)
  13296. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13297. {"If-Range", "invalid-date"}};
  13298. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13299. ASSERT_TRUE(res_ifrange);
  13300. EXPECT_EQ(200, res_ifrange->status);
  13301. svr.stop();
  13302. t.join();
  13303. std::remove(fname);
  13304. }
  13305. TEST(ETagTest, IfRangeWithMalformedETag) {
  13306. using namespace httplib;
  13307. const char *fname = "ifrange_malformed.txt";
  13308. const std::string content = "0123456789";
  13309. {
  13310. std::ofstream ofs(fname);
  13311. ofs << content;
  13312. ASSERT_TRUE(ofs.good());
  13313. }
  13314. Server svr;
  13315. svr.set_mount_point("/static", ".");
  13316. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13317. svr.wait_until_ready();
  13318. Client cli(HOST, PORT);
  13319. // First request: get ETag
  13320. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13321. ASSERT_TRUE(res1);
  13322. ASSERT_EQ(200, res1->status);
  13323. ASSERT_TRUE(res1->has_header("ETag"));
  13324. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13325. // full content (200)
  13326. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13327. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13328. ASSERT_TRUE(res2);
  13329. EXPECT_EQ(200, res2->status);
  13330. EXPECT_EQ(content, res2->body);
  13331. svr.stop();
  13332. t.join();
  13333. std::remove(fname);
  13334. }
  13335. TEST(ETagTest, ExtremeLargeDateValues) {
  13336. using namespace httplib;
  13337. const char *fname = "ims_extreme_date.txt";
  13338. const char *content = "ims-extreme-date";
  13339. {
  13340. std::ofstream ofs(fname);
  13341. ofs << content;
  13342. ASSERT_TRUE(ofs.good());
  13343. }
  13344. Server svr;
  13345. svr.set_mount_point("/static", ".");
  13346. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13347. svr.wait_until_ready();
  13348. Client cli(HOST, PORT);
  13349. auto res1 = cli.Get(std::string("/static/") + fname);
  13350. ASSERT_TRUE(res1);
  13351. ASSERT_EQ(200, res1->status);
  13352. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13353. // Extremely large year that may overflow date parsing routines.
  13354. Headers h_large_date = {
  13355. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13356. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13357. ASSERT_TRUE(res_bad);
  13358. // Expect server to treat this as invalid/mismatch and return full content
  13359. EXPECT_EQ(200, res_bad->status);
  13360. // If-Range with extremely large date should be treated as mismatch -> full
  13361. // content (200)
  13362. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13363. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13364. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13365. ASSERT_TRUE(res_ifrange);
  13366. EXPECT_EQ(200, res_ifrange->status);
  13367. svr.stop();
  13368. t.join();
  13369. std::remove(fname);
  13370. }
  13371. TEST(ETagTest, NegativeFileModificationTime) {
  13372. using namespace httplib;
  13373. const char *fname = "ims_negative_mtime.txt";
  13374. const std::string content = "negative-mtime";
  13375. {
  13376. std::ofstream ofs(fname);
  13377. ofs << content;
  13378. ASSERT_TRUE(ofs.good());
  13379. }
  13380. // Try to set file mtime to a negative value. This may fail on some
  13381. // platforms/filesystems; if it fails, the test will still verify server
  13382. // behaves safely by performing a regular conditional request.
  13383. #if defined(__APPLE__) || defined(__linux__)
  13384. bool set_negative = false;
  13385. do {
  13386. struct timeval times[2];
  13387. // access time: now
  13388. times[0].tv_sec = time(nullptr);
  13389. times[0].tv_usec = 0;
  13390. // modification time: negative (e.g., -1)
  13391. times[1].tv_sec = -1;
  13392. times[1].tv_usec = 0;
  13393. if (utimes(fname, times) == 0) { set_negative = true; }
  13394. } while (0);
  13395. #else
  13396. bool set_negative = false;
  13397. #endif
  13398. Server svr;
  13399. svr.set_mount_point("/static", ".");
  13400. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13401. svr.wait_until_ready();
  13402. Client cli(HOST, PORT);
  13403. auto res1 = cli.Get(std::string("/static/") + fname);
  13404. ASSERT_TRUE(res1);
  13405. ASSERT_EQ(200, res1->status);
  13406. bool has_last_modified = res1->has_header("Last-Modified");
  13407. std::string last_modified;
  13408. if (has_last_modified) {
  13409. last_modified = res1->get_header_value("Last-Modified");
  13410. }
  13411. if (set_negative) {
  13412. // If we successfully set a negative mtime, ensure server returns a
  13413. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13414. // with an old date and ensure server handles it without crash.
  13415. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13416. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13417. ASSERT_TRUE(res2);
  13418. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13419. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13420. } else {
  13421. // Could not set negative mtime on this platform; fall back to verifying
  13422. // that normal invalid/malformed dates are treated safely (non-304).
  13423. Headers h_bad_date = {
  13424. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13425. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13426. ASSERT_TRUE(res_bad);
  13427. EXPECT_EQ(200, res_bad->status);
  13428. }
  13429. svr.stop();
  13430. t.join();
  13431. std::remove(fname);
  13432. }
  13433. //==============================================================================
  13434. // SSE Parsing Tests
  13435. //==============================================================================
  13436. class SSEParsingTest : public ::testing::Test {
  13437. protected:
  13438. // Test helper that mimics SSE parsing behavior
  13439. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13440. int &retry_ms) {
  13441. // Blank line signals end of event
  13442. if (line.empty() || line == "\r") { return true; }
  13443. // Lines starting with ':' are comments (ignored)
  13444. if (!line.empty() && line[0] == ':') { return false; }
  13445. // Find the colon separator
  13446. auto colon_pos = line.find(':');
  13447. if (colon_pos == std::string::npos) {
  13448. // Line with no colon is treated as field name with empty value
  13449. return false;
  13450. }
  13451. std::string field = line.substr(0, colon_pos);
  13452. std::string value;
  13453. // Value starts after colon, skip optional single space
  13454. if (colon_pos + 1 < line.size()) {
  13455. size_t value_start = colon_pos + 1;
  13456. if (line[value_start] == ' ') { value_start++; }
  13457. value = line.substr(value_start);
  13458. // Remove trailing \r if present
  13459. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13460. }
  13461. // Handle known fields
  13462. if (field == "event") {
  13463. msg.event = value;
  13464. } else if (field == "data") {
  13465. // Multiple data lines are concatenated with newlines
  13466. if (!msg.data.empty()) { msg.data += "\n"; }
  13467. msg.data += value;
  13468. } else if (field == "id") {
  13469. // Empty id is valid (clears the last event ID)
  13470. msg.id = value;
  13471. } else if (field == "retry") {
  13472. // Parse retry interval in milliseconds
  13473. {
  13474. int v = 0;
  13475. auto res =
  13476. detail::from_chars(value.data(), value.data() + value.size(), v);
  13477. if (res.ec == std::errc{}) { retry_ms = v; }
  13478. }
  13479. }
  13480. // Unknown fields are ignored per SSE spec
  13481. return false;
  13482. }
  13483. };
  13484. // Test: Single-line data
  13485. TEST_F(SSEParsingTest, SingleLineData) {
  13486. sse::SSEMessage msg;
  13487. int retry_ms = 3000;
  13488. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13489. EXPECT_EQ(msg.data, "hello");
  13490. EXPECT_EQ(msg.event, "message");
  13491. // Blank line ends event
  13492. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13493. }
  13494. // Test: Multi-line data
  13495. TEST_F(SSEParsingTest, MultiLineData) {
  13496. sse::SSEMessage msg;
  13497. int retry_ms = 3000;
  13498. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13499. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13500. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13501. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13502. }
  13503. // Test: Custom event types
  13504. TEST_F(SSEParsingTest, CustomEventType) {
  13505. sse::SSEMessage msg;
  13506. int retry_ms = 3000;
  13507. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13508. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13509. EXPECT_EQ(msg.event, "update");
  13510. EXPECT_EQ(msg.data, "payload");
  13511. }
  13512. // Test: Event ID handling
  13513. TEST_F(SSEParsingTest, EventIdHandling) {
  13514. sse::SSEMessage msg;
  13515. int retry_ms = 3000;
  13516. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13517. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13518. EXPECT_EQ(msg.id, "12345");
  13519. }
  13520. // Test: Empty event ID (clears last event ID)
  13521. TEST_F(SSEParsingTest, EmptyEventId) {
  13522. sse::SSEMessage msg;
  13523. msg.id = "previous";
  13524. int retry_ms = 3000;
  13525. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13526. EXPECT_EQ(msg.id, "");
  13527. }
  13528. // Test: Retry field parsing
  13529. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13530. sse::SSEMessage msg;
  13531. int retry_ms = 3000;
  13532. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13533. EXPECT_EQ(retry_ms, 5000);
  13534. }
  13535. // Test: Invalid retry value
  13536. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13537. sse::SSEMessage msg;
  13538. int retry_ms = 3000;
  13539. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13540. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13541. }
  13542. // Test: Comments (lines starting with :)
  13543. TEST_F(SSEParsingTest, CommentsIgnored) {
  13544. sse::SSEMessage msg;
  13545. int retry_ms = 3000;
  13546. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13547. EXPECT_EQ(msg.data, "");
  13548. EXPECT_EQ(msg.event, "message");
  13549. }
  13550. // Test: Colon in value
  13551. TEST_F(SSEParsingTest, ColonInValue) {
  13552. sse::SSEMessage msg;
  13553. int retry_ms = 3000;
  13554. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13555. EXPECT_EQ(msg.data, "hello:world:test");
  13556. }
  13557. // Test: Line with no colon (field name only)
  13558. TEST_F(SSEParsingTest, FieldNameOnly) {
  13559. sse::SSEMessage msg;
  13560. int retry_ms = 3000;
  13561. // According to SSE spec, this is treated as field name with empty value
  13562. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13563. // Since we don't recognize "data" without colon, data should be empty
  13564. EXPECT_EQ(msg.data, "");
  13565. }
  13566. // Test: Trailing \r handling
  13567. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13568. sse::SSEMessage msg;
  13569. int retry_ms = 3000;
  13570. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13571. EXPECT_EQ(msg.data, "hello");
  13572. }
  13573. // Test: Unknown fields ignored
  13574. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13575. sse::SSEMessage msg;
  13576. int retry_ms = 3000;
  13577. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13578. EXPECT_EQ(msg.data, "");
  13579. EXPECT_EQ(msg.event, "message");
  13580. }
  13581. // Test: Space after colon is optional
  13582. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13583. sse::SSEMessage msg1, msg2;
  13584. int retry_ms = 3000;
  13585. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13586. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13587. EXPECT_EQ(msg1.data, "hello");
  13588. EXPECT_EQ(msg2.data, "hello");
  13589. }
  13590. // Test: SSEMessage clear
  13591. TEST_F(SSEParsingTest, MessageClear) {
  13592. sse::SSEMessage msg;
  13593. msg.event = "custom";
  13594. msg.data = "some data";
  13595. msg.id = "123";
  13596. msg.clear();
  13597. EXPECT_EQ(msg.event, "message");
  13598. EXPECT_EQ(msg.data, "");
  13599. EXPECT_EQ(msg.id, "");
  13600. }
  13601. // Test: Complete event parsing
  13602. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13603. sse::SSEMessage msg;
  13604. int retry_ms = 3000;
  13605. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13606. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13607. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13608. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13609. // Blank line ends event
  13610. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13611. EXPECT_EQ(msg.event, "notification");
  13612. EXPECT_EQ(msg.id, "evt-42");
  13613. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13614. EXPECT_EQ(retry_ms, 1000);
  13615. }
  13616. //==============================================================================
  13617. // Integration Tests with Server
  13618. //==============================================================================
  13619. class SSEIntegrationTest : public ::testing::Test {
  13620. protected:
  13621. void SetUp() override {
  13622. stop_server_.store(false);
  13623. events_.clear();
  13624. server_ = httplib::detail::make_unique<Server>();
  13625. setup_server();
  13626. start_server();
  13627. }
  13628. void TearDown() override {
  13629. stop_server_.store(true);
  13630. event_cv_.notify_all();
  13631. server_->stop();
  13632. if (server_thread_.joinable()) { server_thread_.join(); }
  13633. }
  13634. void setup_server() {
  13635. // Simple SSE endpoint
  13636. server_->Get("/events", [this](const Request &req, Response &res) {
  13637. auto last_id = req.get_header_value("Last-Event-ID");
  13638. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13639. res.set_chunked_content_provider(
  13640. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13641. std::unique_lock<std::mutex> lock(event_mutex_);
  13642. if (event_cv_.wait_for(
  13643. lock, std::chrono::milliseconds(200), [this] {
  13644. return !events_.empty() || stop_server_.load();
  13645. })) {
  13646. if (stop_server_.load()) { return false; }
  13647. if (!events_.empty()) {
  13648. std::string event = events_.front();
  13649. events_.erase(events_.begin());
  13650. sink.write(event.data(), event.size());
  13651. return true;
  13652. }
  13653. }
  13654. return !stop_server_.load();
  13655. });
  13656. });
  13657. // Endpoint that returns error
  13658. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13659. res.status = 500;
  13660. res.set_content("Internal Server Error", "text/plain");
  13661. });
  13662. // Endpoint for custom event types
  13663. server_->Get("/custom-events", [](const Request &, Response &res) {
  13664. res.set_chunked_content_provider(
  13665. "text/event-stream", [](size_t offset, DataSink &sink) {
  13666. if (offset == 0) {
  13667. std::string event = "event: update\ndata: updated\n\n"
  13668. "event: delete\ndata: deleted\n\n";
  13669. sink.write(event.data(), event.size());
  13670. }
  13671. return false; // End stream after sending
  13672. });
  13673. });
  13674. }
  13675. void start_server() {
  13676. port_ = server_->bind_to_any_port(HOST);
  13677. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13678. // Wait for server to start
  13679. while (!server_->is_running()) {
  13680. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13681. }
  13682. }
  13683. int get_port() const { return port_; }
  13684. void send_event(const std::string &event) {
  13685. std::lock_guard<std::mutex> lock(event_mutex_);
  13686. events_.push_back(event);
  13687. event_cv_.notify_all();
  13688. }
  13689. std::unique_ptr<Server> server_;
  13690. std::thread server_thread_;
  13691. std::mutex event_mutex_;
  13692. std::condition_variable event_cv_;
  13693. std::vector<std::string> events_;
  13694. std::atomic<bool> stop_server_{false};
  13695. std::string last_received_event_id_;
  13696. int port_ = 0;
  13697. };
  13698. // Test: Successful connection and on_open callback
  13699. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13700. // Add a simple endpoint that sends one event and closes
  13701. server_->Get("/simple-event", [](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 = "data: hello\n\n";
  13706. sink.write(event.data(), event.size());
  13707. }
  13708. return false; // Close stream after sending
  13709. });
  13710. });
  13711. Client client("localhost", get_port());
  13712. sse::SSEClient sse(client, "/simple-event");
  13713. std::atomic<bool> open_called{false};
  13714. std::atomic<bool> message_received{false};
  13715. sse.on_open([&open_called]() { open_called.store(true); });
  13716. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13717. if (msg.data == "hello") { message_received.store(true); }
  13718. });
  13719. sse.set_reconnect_interval(100);
  13720. sse.set_max_reconnect_attempts(1);
  13721. // Start async
  13722. sse.start_async();
  13723. // Wait for message to be processed
  13724. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13725. sse.stop();
  13726. EXPECT_TRUE(open_called.load());
  13727. EXPECT_TRUE(message_received.load());
  13728. }
  13729. // Test: on_message callback
  13730. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13731. // Endpoint that sends multiple events then closes
  13732. server_->Get("/multi-event", [](const Request &, Response &res) {
  13733. res.set_chunked_content_provider(
  13734. "text/event-stream", [](size_t offset, DataSink &sink) {
  13735. if (offset == 0) {
  13736. std::string events = "data: message1\n\ndata: message2\n\n";
  13737. sink.write(events.data(), events.size());
  13738. }
  13739. return false;
  13740. });
  13741. });
  13742. Client client("localhost", get_port());
  13743. sse::SSEClient sse(client, "/multi-event");
  13744. std::vector<std::string> received_messages;
  13745. std::mutex messages_mutex;
  13746. sse.on_message([&](const sse::SSEMessage &msg) {
  13747. std::lock_guard<std::mutex> lock(messages_mutex);
  13748. received_messages.push_back(msg.data);
  13749. });
  13750. sse.set_reconnect_interval(100);
  13751. sse.set_max_reconnect_attempts(1);
  13752. sse.start_async();
  13753. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13754. sse.stop();
  13755. std::lock_guard<std::mutex> lock(messages_mutex);
  13756. EXPECT_GE(received_messages.size(), 2u);
  13757. if (received_messages.size() >= 2) {
  13758. EXPECT_EQ(received_messages[0], "message1");
  13759. EXPECT_EQ(received_messages[1], "message2");
  13760. }
  13761. }
  13762. // Test: on_event for specific types
  13763. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13764. Client client("localhost", get_port());
  13765. sse::SSEClient sse(client, "/custom-events");
  13766. std::atomic<bool> update_received{false};
  13767. std::atomic<bool> delete_received{false};
  13768. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13769. if (msg.data == "updated") { update_received.store(true); }
  13770. });
  13771. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13772. if (msg.data == "deleted") { delete_received.store(true); }
  13773. });
  13774. sse.set_max_reconnect_attempts(1);
  13775. sse.start_async();
  13776. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13777. sse.stop();
  13778. EXPECT_TRUE(update_received.load());
  13779. EXPECT_TRUE(delete_received.load());
  13780. }
  13781. // Test: on_error callback on connection failure
  13782. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13783. // Connect to a non-existent port
  13784. Client client("localhost", 59999);
  13785. sse::SSEClient sse(client, "/events");
  13786. std::atomic<bool> error_called{false};
  13787. Error received_error = Error::Success;
  13788. sse.on_error([&](Error err) {
  13789. error_called.store(true);
  13790. received_error = err;
  13791. });
  13792. sse.set_reconnect_interval(50);
  13793. sse.set_max_reconnect_attempts(1);
  13794. sse.start_async();
  13795. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13796. sse.stop();
  13797. EXPECT_TRUE(error_called.load());
  13798. EXPECT_NE(received_error, Error::Success);
  13799. }
  13800. // Test: Last-Event-ID header sent on reconnect
  13801. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13802. // Endpoint that sends event with ID
  13803. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13804. res.set_chunked_content_provider(
  13805. "text/event-stream", [](size_t offset, DataSink &sink) {
  13806. if (offset == 0) {
  13807. std::string event = "id: evt-123\ndata: test\n\n";
  13808. sink.write(event.data(), event.size());
  13809. }
  13810. return false;
  13811. });
  13812. });
  13813. Client client("localhost", get_port());
  13814. sse::SSEClient sse(client, "/event-with-id");
  13815. std::atomic<bool> id_received{false};
  13816. sse.on_message([&](const sse::SSEMessage &msg) {
  13817. if (!msg.id.empty()) { id_received.store(true); }
  13818. });
  13819. sse.set_reconnect_interval(100);
  13820. sse.set_max_reconnect_attempts(1);
  13821. sse.start_async();
  13822. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13823. sse.stop();
  13824. EXPECT_TRUE(id_received.load());
  13825. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13826. }
  13827. // Test: Manual stop
  13828. TEST_F(SSEIntegrationTest, ManualStop) {
  13829. // Endpoint that sends one event and stays open briefly
  13830. std::atomic<bool> handler_running{true};
  13831. server_->Get("/stay-open", [&handler_running](const Request &,
  13832. Response &res) {
  13833. res.set_chunked_content_provider(
  13834. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13835. if (offset == 0) {
  13836. std::string event = "data: connected\n\n";
  13837. sink.write(event.data(), event.size());
  13838. }
  13839. // Keep connection open while handler_running is true
  13840. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13841. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13842. }
  13843. return false;
  13844. });
  13845. });
  13846. Client client("localhost", get_port());
  13847. sse::SSEClient sse(client, "/stay-open");
  13848. std::atomic<bool> connected{false};
  13849. sse.on_open([&connected]() { connected.store(true); });
  13850. sse.set_reconnect_interval(100);
  13851. sse.set_max_reconnect_attempts(1);
  13852. sse.start_async();
  13853. // Wait for connection to establish
  13854. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13855. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13856. }
  13857. EXPECT_TRUE(connected.load());
  13858. EXPECT_TRUE(sse.is_connected());
  13859. // Signal handler to stop
  13860. handler_running.store(false);
  13861. // Stop SSE client
  13862. sse.stop();
  13863. EXPECT_FALSE(sse.is_connected());
  13864. }
  13865. // Test: SSEClient with custom headers
  13866. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13867. // Setup a server endpoint that checks for custom header
  13868. std::atomic<bool> header_received{false};
  13869. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13870. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13871. header_received.store(true);
  13872. }
  13873. res.set_chunked_content_provider("text/event-stream",
  13874. [](size_t, DataSink &) { return false; });
  13875. });
  13876. Client client("localhost", get_port());
  13877. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13878. sse::SSEClient sse(client, "/header-check", headers);
  13879. sse.set_max_reconnect_attempts(1);
  13880. sse.start_async();
  13881. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13882. sse.stop();
  13883. EXPECT_TRUE(header_received.load());
  13884. }
  13885. // Test: Reconnect interval configuration
  13886. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13887. Client client("localhost", get_port());
  13888. sse::SSEClient sse(client, "/events");
  13889. auto &result = sse.set_reconnect_interval(500);
  13890. // Builder pattern should return reference to self
  13891. EXPECT_EQ(&result, &sse);
  13892. }
  13893. // Test: Max reconnect attempts
  13894. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13895. // Connect to non-existent port to force reconnects
  13896. Client client("localhost", 59998);
  13897. sse::SSEClient sse(client, "/events");
  13898. std::atomic<int> error_count{0};
  13899. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13900. sse.set_reconnect_interval(50);
  13901. sse.set_max_reconnect_attempts(2);
  13902. auto start = std::chrono::steady_clock::now();
  13903. sse.start(); // Blocking call
  13904. auto end = std::chrono::steady_clock::now();
  13905. // Should have stopped after 2 failed attempts
  13906. EXPECT_GE(error_count.load(), 2);
  13907. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13908. auto duration =
  13909. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13910. #ifdef _WIN32
  13911. // Windows is much slower for socket connection failures
  13912. EXPECT_LT(duration.count(), 7000);
  13913. #else
  13914. EXPECT_LT(duration.count(), 1000);
  13915. #endif
  13916. }
  13917. // Test: Multi-line data in integration
  13918. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13919. // Endpoint with multi-line data
  13920. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13921. res.set_chunked_content_provider(
  13922. "text/event-stream", [](size_t offset, DataSink &sink) {
  13923. if (offset == 0) {
  13924. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13925. sink.write(event.data(), event.size());
  13926. }
  13927. return false;
  13928. });
  13929. });
  13930. Client client("localhost", get_port());
  13931. sse::SSEClient sse(client, "/multiline-data");
  13932. std::string received_data;
  13933. std::mutex data_mutex;
  13934. sse.on_message([&](const sse::SSEMessage &msg) {
  13935. std::lock_guard<std::mutex> lock(data_mutex);
  13936. received_data = msg.data;
  13937. });
  13938. sse.set_reconnect_interval(100);
  13939. sse.set_max_reconnect_attempts(1);
  13940. sse.start_async();
  13941. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13942. sse.stop();
  13943. std::lock_guard<std::mutex> lock(data_mutex);
  13944. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13945. }
  13946. // Test: Auto-reconnect after server disconnection
  13947. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13948. std::atomic<int> connection_count{0};
  13949. std::atomic<int> message_count{0};
  13950. // Endpoint that sends one event and closes, forcing reconnect
  13951. server_->Get("/reconnect-test",
  13952. [&connection_count](const Request &, Response &res) {
  13953. connection_count.fetch_add(1);
  13954. res.set_chunked_content_provider(
  13955. "text/event-stream", [](size_t offset, DataSink &sink) {
  13956. if (offset == 0) {
  13957. std::string event = "data: hello\n\n";
  13958. sink.write(event.data(), event.size());
  13959. }
  13960. return false; // Close connection after sending
  13961. });
  13962. });
  13963. Client client("localhost", get_port());
  13964. sse::SSEClient sse(client, "/reconnect-test");
  13965. sse.on_message([&message_count](const sse::SSEMessage &) {
  13966. message_count.fetch_add(1);
  13967. });
  13968. sse.set_reconnect_interval(100);
  13969. sse.set_max_reconnect_attempts(3);
  13970. sse.start_async();
  13971. // Wait long enough for multiple reconnects
  13972. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13973. sse.stop();
  13974. // Should have connected multiple times (initial + reconnects)
  13975. EXPECT_GE(connection_count.load(), 2);
  13976. // Should have received messages from multiple connections
  13977. EXPECT_GE(message_count.load(), 2);
  13978. }
  13979. // Test: Last-Event-ID sent on reconnect
  13980. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13981. std::atomic<int> connection_count{0};
  13982. std::vector<std::string> received_last_event_ids;
  13983. std::mutex id_mutex;
  13984. // Endpoint that checks Last-Event-ID header and sends event with ID
  13985. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13986. int conn = connection_count.fetch_add(1);
  13987. // Capture the Last-Event-ID header from each connection
  13988. {
  13989. std::lock_guard<std::mutex> lock(id_mutex);
  13990. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13991. }
  13992. res.set_chunked_content_provider(
  13993. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13994. if (offset == 0) {
  13995. std::string event =
  13996. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13997. sink.write(event.data(), event.size());
  13998. }
  13999. return false;
  14000. });
  14001. });
  14002. Client client("localhost", get_port());
  14003. sse::SSEClient sse(client, "/reconnect-with-id");
  14004. sse.set_reconnect_interval(100);
  14005. sse.set_max_reconnect_attempts(3);
  14006. sse.start_async();
  14007. // Wait for at least 2 connections
  14008. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14009. sse.stop();
  14010. // Verify behavior
  14011. std::lock_guard<std::mutex> lock(id_mutex);
  14012. EXPECT_GE(received_last_event_ids.size(), 2u);
  14013. // First connection should have no Last-Event-ID
  14014. if (!received_last_event_ids.empty()) {
  14015. EXPECT_EQ(received_last_event_ids[0], "");
  14016. }
  14017. // Second connection should have Last-Event-ID from first connection
  14018. if (received_last_event_ids.size() >= 2) {
  14019. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14020. }
  14021. }
  14022. // Test: set_headers updates headers used on reconnect
  14023. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14024. std::vector<std::string> received_tokens;
  14025. std::mutex token_mutex;
  14026. // Endpoint that captures Authorization header
  14027. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14028. {
  14029. std::lock_guard<std::mutex> lock(token_mutex);
  14030. received_tokens.push_back(req.get_header_value("Authorization"));
  14031. }
  14032. res.set_chunked_content_provider(
  14033. "text/event-stream", [](size_t offset, DataSink &sink) {
  14034. if (offset == 0) {
  14035. std::string event = "data: hello\n\n";
  14036. sink.write(event.data(), event.size());
  14037. }
  14038. return false; // Close connection to trigger reconnect
  14039. });
  14040. });
  14041. Client client("localhost", get_port());
  14042. Headers headers = {{"Authorization", "Bearer old-token"}};
  14043. sse::SSEClient sse(client, "/auth-check", headers);
  14044. // Update headers on each successful connection
  14045. sse.on_open(
  14046. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14047. sse.set_reconnect_interval(100);
  14048. sse.set_max_reconnect_attempts(3);
  14049. sse.start_async();
  14050. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14051. sse.stop();
  14052. std::lock_guard<std::mutex> lock(token_mutex);
  14053. ASSERT_GE(received_tokens.size(), 2u);
  14054. // First connection uses original header
  14055. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14056. // Second connection uses updated header from set_headers
  14057. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14058. }
  14059. // Test: 401 allows reconnection (so on_error can refresh headers)
  14060. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14061. std::atomic<int> connection_count{0};
  14062. // Endpoint: returns 401 on first attempt, 200 on second
  14063. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14064. int conn = connection_count.fetch_add(1);
  14065. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14066. res.status = StatusCode::Unauthorized_401;
  14067. res.set_content("Unauthorized", "text/plain");
  14068. return;
  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: authenticated\n\n";
  14074. sink.write(event.data(), event.size());
  14075. }
  14076. return false;
  14077. });
  14078. });
  14079. Client client("localhost", get_port());
  14080. Headers headers = {{"Authorization", "Bearer expired"}};
  14081. sse::SSEClient sse(client, "/auth-retry", headers);
  14082. std::atomic<bool> message_received{false};
  14083. // Refresh token on error
  14084. sse.on_error(
  14085. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14086. sse.on_message([&](const sse::SSEMessage &msg) {
  14087. if (msg.data == "authenticated") { message_received.store(true); }
  14088. });
  14089. sse.set_reconnect_interval(100);
  14090. sse.set_max_reconnect_attempts(3);
  14091. sse.start_async();
  14092. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14093. sse.stop();
  14094. // Should have reconnected after 401 and succeeded with new token
  14095. EXPECT_GE(connection_count.load(), 2);
  14096. EXPECT_TRUE(message_received.load());
  14097. }
  14098. TEST(Issue2318Test, EmptyHostString) {
  14099. {
  14100. httplib::Client cli_empty("", PORT);
  14101. auto res = cli_empty.Get("/");
  14102. ASSERT_FALSE(res);
  14103. EXPECT_EQ(httplib::Error::Connection, res.error());
  14104. }
  14105. {
  14106. httplib::Client cli(" ", PORT);
  14107. auto res = cli.Get("/");
  14108. ASSERT_FALSE(res);
  14109. EXPECT_EQ(httplib::Error::Connection, res.error());
  14110. }
  14111. }
  14112. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14113. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14114. Server svr;
  14115. // Set a small payload limit (1KB)
  14116. svr.set_payload_max_length(1024);
  14117. svr.Post("/test", [&](const Request &req, Response &res) {
  14118. res.set_content("Body size: " + std::to_string(req.body.size()),
  14119. "text/plain");
  14120. });
  14121. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14122. auto se = detail::scope_exit([&] {
  14123. svr.stop();
  14124. listen_thread.join();
  14125. });
  14126. svr.wait_until_ready();
  14127. // Create data that compresses well but exceeds limit when decompressed
  14128. // 8KB of repeated null bytes compresses to a very small size
  14129. std::string original_data(8 * 1024, '\0');
  14130. // Compress the data using gzip
  14131. std::string compressed_data;
  14132. detail::gzip_compressor compressor;
  14133. compressor.compress(original_data.data(), original_data.size(), true,
  14134. [&](const char *data, size_t size) {
  14135. compressed_data.append(data, size);
  14136. return true;
  14137. });
  14138. // Verify compression worked (compressed should be much smaller)
  14139. ASSERT_LT(compressed_data.size(), original_data.size());
  14140. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14141. // Send compressed data with Content-Encoding: gzip
  14142. Client cli(HOST, PORT);
  14143. Headers headers = {{"Content-Encoding", "gzip"}};
  14144. auto res =
  14145. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14146. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14147. ASSERT_TRUE(res);
  14148. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14149. }
  14150. #endif
  14151. // ============================================================================
  14152. // OpenSSL-Specific Tests
  14153. // ============================================================================
  14154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14155. X509 *readCertificate(const std::string &strFileName) {
  14156. std::ifstream inStream(strFileName);
  14157. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14158. std::istreambuf_iterator<char>());
  14159. if (strCertPEM.empty()) return (nullptr);
  14160. BIO *pbCert = BIO_new(BIO_s_mem());
  14161. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14162. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14163. BIO_free(pbCert);
  14164. return (pCert);
  14165. }
  14166. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14167. std::ifstream inStream(strFileName);
  14168. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14169. std::istreambuf_iterator<char>());
  14170. if (strPrivateKeyPEM.empty()) return (nullptr);
  14171. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14172. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14173. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14174. BIO_free(pbPrivKey);
  14175. return (pPrivateKey);
  14176. }
  14177. TEST(BindServerTest, UpdateCerts) {
  14178. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14179. int port = svr.bind_to_any_port("0.0.0.0");
  14180. ASSERT_TRUE(svr.is_valid());
  14181. ASSERT_TRUE(port > 0);
  14182. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14183. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14184. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14185. ASSERT_TRUE(cert != nullptr);
  14186. ASSERT_TRUE(ca_cert != nullptr);
  14187. ASSERT_TRUE(key != nullptr);
  14188. X509_STORE *cert_store = X509_STORE_new();
  14189. X509_STORE_add_cert(cert_store, ca_cert);
  14190. // svr.update_certs(cert, key, cert_store); // deprecated
  14191. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14192. CLIENT_CA_CERT_FILE);
  14193. ASSERT_TRUE(svr.is_valid());
  14194. svr.stop();
  14195. X509_STORE_free(cert_store);
  14196. X509_free(cert);
  14197. X509_free(ca_cert);
  14198. EVP_PKEY_free(key);
  14199. }
  14200. // Test that update_certs() updates client CA list correctly
  14201. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14202. // Start with file-based constructor
  14203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14204. ASSERT_TRUE(svr.is_valid());
  14205. // Initially no client CA list should be set
  14206. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14207. ASSERT_TRUE(ssl_ctx != nullptr);
  14208. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14209. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14210. EXPECT_EQ(0, count_before);
  14211. // Now update with client CA (PEM string)
  14212. std::string cert_pem, key_pem, ca_pem;
  14213. read_file(SERVER_CERT_FILE, cert_pem);
  14214. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14215. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14216. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14217. ASSERT_TRUE(svr.is_valid());
  14218. // Now client CA list should be set
  14219. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14220. ASSERT_TRUE(ca_list_after != nullptr);
  14221. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14222. }
  14223. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14224. // Test that the file-path SSLServer constructor properly sets the client CA
  14225. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14227. ASSERT_TRUE(svr.is_valid());
  14228. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14229. ASSERT_TRUE(ssl_ctx != nullptr);
  14230. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14231. ASSERT_TRUE(ca_list != nullptr);
  14232. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14233. }
  14234. #endif
  14235. // ============================================================================
  14236. // MbedTLS-Specific Tests
  14237. // ============================================================================
  14238. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14239. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14240. using namespace httplib::tls;
  14241. // Track if callback was invoked
  14242. bool callback_invoked = false;
  14243. // The callback receives void* ctx which is actually MbedTlsContext*
  14244. // We can access the mbedtls_ssl_config via the context
  14245. auto setup_callback = [&callback_invoked](void *ctx) {
  14246. callback_invoked = true;
  14247. // Cast to MbedTlsContext* to access the ssl config
  14248. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14249. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14250. // Use static variables to hold certificate data (simplified for test)
  14251. static mbedtls_x509_crt own_cert;
  14252. static mbedtls_pk_context own_key;
  14253. static mbedtls_x509_crt ca_chain;
  14254. static bool initialized = false;
  14255. if (!initialized) {
  14256. mbedtls_x509_crt_init(&own_cert);
  14257. mbedtls_pk_init(&own_key);
  14258. mbedtls_x509_crt_init(&ca_chain);
  14259. // Load server certificate
  14260. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14261. return false;
  14262. }
  14263. // Load server private key
  14264. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14265. #if MBEDTLS_VERSION_MAJOR >= 3
  14266. ,
  14267. mbedtls_ctr_drbg_random, nullptr
  14268. #endif
  14269. ) != 0) {
  14270. return false;
  14271. }
  14272. // Load CA chain for client verification
  14273. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14274. return false;
  14275. }
  14276. initialized = true;
  14277. }
  14278. // Configure the SSL config
  14279. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14280. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14281. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14282. // Set minimum TLS version using mbedTLS native API
  14283. #if MBEDTLS_VERSION_MAJOR >= 3
  14284. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14285. #else
  14286. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14287. MBEDTLS_SSL_MINOR_VERSION_3);
  14288. #endif
  14289. return true;
  14290. };
  14291. SSLServer svr(setup_callback);
  14292. ASSERT_TRUE(svr.is_valid());
  14293. ASSERT_TRUE(callback_invoked);
  14294. svr.Get("/test", [&](const Request &req, Response &res) {
  14295. res.set_content("test", "text/plain");
  14296. auto cert = req.peer_cert();
  14297. ASSERT_TRUE(static_cast<bool>(cert));
  14298. auto common_name = cert.subject_cn();
  14299. EXPECT_EQ("Common Name", common_name);
  14300. });
  14301. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14302. auto se = detail::scope_exit([&] {
  14303. svr.stop();
  14304. t.join();
  14305. ASSERT_FALSE(svr.is_running());
  14306. });
  14307. svr.wait_until_ready();
  14308. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14309. cli.enable_server_certificate_verification(false);
  14310. cli.set_connection_timeout(30);
  14311. auto res = cli.Get("/test");
  14312. ASSERT_TRUE(res);
  14313. ASSERT_EQ(StatusCode::OK_200, res->status);
  14314. }
  14315. #endif
  14316. // WebSocket Tests
  14317. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14318. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14319. // defining the meaning of these bits has been negotiated.
  14320. auto make_frame = [](uint8_t first_byte) {
  14321. std::string frame;
  14322. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14323. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14324. frame += "Hello";
  14325. return frame;
  14326. };
  14327. // RSV1 set (0x40)
  14328. {
  14329. detail::BufferStream strm;
  14330. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14331. ws::Opcode opcode;
  14332. std::string payload;
  14333. bool fin;
  14334. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14335. false, 1024));
  14336. }
  14337. // RSV2 set (0x20)
  14338. {
  14339. detail::BufferStream strm;
  14340. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14341. ws::Opcode opcode;
  14342. std::string payload;
  14343. bool fin;
  14344. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14345. false, 1024));
  14346. }
  14347. // RSV3 set (0x10)
  14348. {
  14349. detail::BufferStream strm;
  14350. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14351. ws::Opcode opcode;
  14352. std::string payload;
  14353. bool fin;
  14354. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14355. false, 1024));
  14356. }
  14357. // No RSV bits set - should succeed
  14358. {
  14359. detail::BufferStream strm;
  14360. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14361. ws::Opcode opcode;
  14362. std::string payload;
  14363. bool fin;
  14364. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14365. false, 1024));
  14366. EXPECT_EQ(ws::Opcode::Text, opcode);
  14367. EXPECT_EQ("Hello", payload);
  14368. EXPECT_TRUE(fin);
  14369. }
  14370. }
  14371. TEST(WebSocketTest, ControlFrameValidation) {
  14372. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14373. // payload length <= 125.
  14374. // Ping with FIN=0 - must be rejected
  14375. {
  14376. detail::BufferStream strm;
  14377. std::string frame;
  14378. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14379. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14380. strm.write(frame.data(), frame.size());
  14381. ws::Opcode opcode;
  14382. std::string payload;
  14383. bool fin;
  14384. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14385. false, 1024));
  14386. }
  14387. // Close with FIN=0 - must be rejected
  14388. {
  14389. detail::BufferStream strm;
  14390. std::string frame;
  14391. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14392. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14393. strm.write(frame.data(), frame.size());
  14394. ws::Opcode opcode;
  14395. std::string payload;
  14396. bool fin;
  14397. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14398. false, 1024));
  14399. }
  14400. // Ping with payload_len=126 (extended length) - must be rejected
  14401. {
  14402. detail::BufferStream strm;
  14403. std::string frame;
  14404. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14405. frame += static_cast<char>(126); // payload_len=126 (>125)
  14406. frame += static_cast<char>(0x00); // extended length high byte
  14407. frame += static_cast<char>(126); // extended length low byte
  14408. frame += std::string(126, 'x');
  14409. strm.write(frame.data(), frame.size());
  14410. ws::Opcode opcode;
  14411. std::string payload;
  14412. bool fin;
  14413. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14414. false, 1024));
  14415. }
  14416. // Ping with FIN=1 and payload_len=125 - should succeed
  14417. {
  14418. detail::BufferStream strm;
  14419. std::string frame;
  14420. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14421. frame += static_cast<char>(125); // payload_len=125
  14422. frame += std::string(125, 'x');
  14423. strm.write(frame.data(), frame.size());
  14424. ws::Opcode opcode;
  14425. std::string payload;
  14426. bool fin;
  14427. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14428. false, 1024));
  14429. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14430. EXPECT_EQ(125u, payload.size());
  14431. EXPECT_TRUE(fin);
  14432. }
  14433. }
  14434. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14435. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14436. // length MUST be 0.
  14437. // MSB set - must be rejected
  14438. {
  14439. detail::BufferStream strm;
  14440. std::string frame;
  14441. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14442. frame += static_cast<char>(127); // 64-bit extended length
  14443. frame += static_cast<char>(0x80); // MSB set (invalid)
  14444. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14445. strm.write(frame.data(), frame.size());
  14446. ws::Opcode opcode;
  14447. std::string payload;
  14448. bool fin;
  14449. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14450. false, 1024));
  14451. }
  14452. // MSB clear - should pass length parsing (will be rejected by max_len,
  14453. // but that's a different check; use a small length to verify)
  14454. {
  14455. detail::BufferStream strm;
  14456. std::string frame;
  14457. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14458. frame += static_cast<char>(127); // 64-bit extended length
  14459. frame += std::string(7, '\0'); // high bytes = 0
  14460. frame += static_cast<char>(0x03); // length = 3
  14461. frame += "abc";
  14462. strm.write(frame.data(), frame.size());
  14463. ws::Opcode opcode;
  14464. std::string payload;
  14465. bool fin;
  14466. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14467. false, 1024));
  14468. EXPECT_EQ(ws::Opcode::Text, opcode);
  14469. EXPECT_EQ("abc", payload);
  14470. }
  14471. }
  14472. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14473. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14474. // Valid UTF-8
  14475. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14476. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14477. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14478. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14479. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14480. // Invalid UTF-8
  14481. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14482. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14483. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14484. EXPECT_FALSE(
  14485. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14486. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14487. }
  14488. TEST(WebSocketTest, ConnectAndDisconnect) {
  14489. Server svr;
  14490. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14491. std::string msg;
  14492. while (ws.read(msg)) {}
  14493. });
  14494. auto port = svr.bind_to_any_port(HOST);
  14495. std::thread t([&]() { svr.listen_after_bind(); });
  14496. svr.wait_until_ready();
  14497. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14498. ASSERT_TRUE(client.connect());
  14499. EXPECT_TRUE(client.is_open());
  14500. client.close();
  14501. EXPECT_FALSE(client.is_open());
  14502. svr.stop();
  14503. t.join();
  14504. }
  14505. TEST(WebSocketTest, ValidURL) {
  14506. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14507. EXPECT_TRUE(ws1.is_valid());
  14508. ws::WebSocketClient ws2("ws://example.com/path");
  14509. EXPECT_TRUE(ws2.is_valid());
  14510. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14511. EXPECT_TRUE(ws3.is_valid());
  14512. #ifdef CPPHTTPLIB_SSL_ENABLED
  14513. ws::WebSocketClient wss1("wss://example.com/path");
  14514. EXPECT_TRUE(wss1.is_valid());
  14515. ws::WebSocketClient wss2("wss://example.com:443/path");
  14516. EXPECT_TRUE(wss2.is_valid());
  14517. #endif
  14518. }
  14519. TEST(WebSocketTest, InvalidURL) {
  14520. // No scheme
  14521. ws::WebSocketClient ws1("localhost:8080/path");
  14522. EXPECT_FALSE(ws1.is_valid());
  14523. // No path
  14524. ws::WebSocketClient ws2("ws://localhost:8080");
  14525. EXPECT_FALSE(ws2.is_valid());
  14526. // Empty string
  14527. ws::WebSocketClient ws3("");
  14528. EXPECT_FALSE(ws3.is_valid());
  14529. // Missing host
  14530. ws::WebSocketClient ws4("ws://:8080/path");
  14531. EXPECT_FALSE(ws4.is_valid());
  14532. // Port number overflow — should not crash
  14533. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14534. EXPECT_FALSE(ws5.is_valid());
  14535. // Port out of range
  14536. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14537. EXPECT_FALSE(ws6.is_valid());
  14538. }
  14539. TEST(WebSocketTest, UnsupportedScheme) {
  14540. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14541. ws::WebSocketClient ws1("http://localhost:8080/path");
  14542. EXPECT_FALSE(ws1.is_valid());
  14543. ws::WebSocketClient ws2("https://localhost:8080/path");
  14544. EXPECT_FALSE(ws2.is_valid());
  14545. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14546. EXPECT_FALSE(ws3.is_valid());
  14547. #else
  14548. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14549. std::invalid_argument);
  14550. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14551. std::invalid_argument);
  14552. #endif
  14553. }
  14554. TEST(WebSocketTest, ConnectWhenInvalid) {
  14555. ws::WebSocketClient ws("not a valid url");
  14556. EXPECT_FALSE(ws.is_valid());
  14557. EXPECT_FALSE(ws.connect());
  14558. }
  14559. TEST(WebSocketTest, DefaultPort) {
  14560. ws::WebSocketClient ws1("ws://example.com/path");
  14561. EXPECT_TRUE(ws1.is_valid());
  14562. // ws:// defaults to port 80 (verified by successful parse)
  14563. #ifdef CPPHTTPLIB_SSL_ENABLED
  14564. ws::WebSocketClient ws2("wss://example.com/path");
  14565. EXPECT_TRUE(ws2.is_valid());
  14566. // wss:// defaults to port 443 (verified by successful parse)
  14567. #endif
  14568. }
  14569. TEST(WebSocketTest, IPv6LiteralAddress) {
  14570. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14571. EXPECT_TRUE(ws1.is_valid());
  14572. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14573. EXPECT_TRUE(ws2.is_valid());
  14574. }
  14575. TEST(WebSocketTest, ComplexPath) {
  14576. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14577. EXPECT_TRUE(ws1.is_valid());
  14578. ws::WebSocketClient ws2("ws://localhost:8080/");
  14579. EXPECT_TRUE(ws2.is_valid());
  14580. }
  14581. class WebSocketIntegrationTest : public ::testing::Test {
  14582. protected:
  14583. void SetUp() override {
  14584. server_ = httplib::detail::make_unique<Server>();
  14585. setup_server();
  14586. start_server();
  14587. }
  14588. void TearDown() override {
  14589. server_->stop();
  14590. if (server_thread_.joinable()) { server_thread_.join(); }
  14591. }
  14592. void setup_server() {
  14593. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14594. std::string msg;
  14595. ws::ReadResult ret;
  14596. while ((ret = ws.read(msg))) {
  14597. if (ret == ws::Binary) {
  14598. ws.send(msg.data(), msg.size());
  14599. } else {
  14600. ws.send(msg);
  14601. }
  14602. }
  14603. });
  14604. server_->WebSocket("/ws-echo-string",
  14605. [](const Request &, ws::WebSocket &ws) {
  14606. std::string msg;
  14607. while (ws.read(msg)) {
  14608. ws.send("echo: " + msg);
  14609. }
  14610. });
  14611. server_->WebSocket(
  14612. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14613. // Echo back request metadata
  14614. ws.send("path:" + req.path);
  14615. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14616. std::string msg;
  14617. while (ws.read(msg)) {}
  14618. });
  14619. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14620. std::string msg;
  14621. ws.read(msg); // wait for a message
  14622. ws.close();
  14623. });
  14624. server_->WebSocket("/ws-close-status",
  14625. [](const Request &, ws::WebSocket &ws) {
  14626. std::string msg;
  14627. ws.read(msg); // wait for a message
  14628. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14629. });
  14630. server_->WebSocket(
  14631. "/ws-subprotocol",
  14632. [](const Request &, ws::WebSocket &ws) {
  14633. std::string msg;
  14634. while (ws.read(msg)) {
  14635. ws.send(msg);
  14636. }
  14637. },
  14638. [](const std::vector<std::string> &protocols) -> std::string {
  14639. for (const auto &p : protocols) {
  14640. if (p == "graphql-ws") { return p; }
  14641. }
  14642. return "";
  14643. });
  14644. }
  14645. void start_server() {
  14646. port_ = server_->bind_to_any_port(HOST);
  14647. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14648. server_->wait_until_ready();
  14649. }
  14650. std::unique_ptr<Server> server_;
  14651. std::thread server_thread_;
  14652. int port_ = 0;
  14653. };
  14654. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14656. "/ws-echo");
  14657. ASSERT_TRUE(client.connect());
  14658. ASSERT_TRUE(client.is_open());
  14659. ASSERT_TRUE(client.send("Hello WebSocket"));
  14660. std::string msg;
  14661. EXPECT_EQ(ws::Text, client.read(msg));
  14662. EXPECT_EQ("Hello WebSocket", msg);
  14663. client.close();
  14664. }
  14665. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14667. "/ws-echo");
  14668. ASSERT_TRUE(client.connect());
  14669. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14670. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14671. std::string msg;
  14672. EXPECT_EQ(ws::Binary, client.read(msg));
  14673. EXPECT_EQ(binary_data, msg);
  14674. client.close();
  14675. }
  14676. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14677. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14678. "/ws-echo");
  14679. ASSERT_TRUE(client.connect());
  14680. for (int i = 0; i < 10; i++) {
  14681. auto text = "message " + std::to_string(i);
  14682. ASSERT_TRUE(client.send(text));
  14683. std::string msg;
  14684. ASSERT_TRUE(client.read(msg));
  14685. EXPECT_EQ(text, msg);
  14686. }
  14687. client.close();
  14688. }
  14689. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14690. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14691. "/ws-close");
  14692. ASSERT_TRUE(client.connect());
  14693. // Send a message to trigger the server to close
  14694. ASSERT_TRUE(client.send("trigger close"));
  14695. // The server will close, so read should return false
  14696. std::string msg;
  14697. EXPECT_FALSE(client.read(msg));
  14698. EXPECT_FALSE(client.is_open());
  14699. }
  14700. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14701. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14702. "/ws-echo");
  14703. ASSERT_TRUE(client.connect());
  14704. // 128KB message
  14705. std::string large_data(128 * 1024, 'X');
  14706. ASSERT_TRUE(client.send(large_data));
  14707. std::string msg;
  14708. ASSERT_TRUE(client.read(msg));
  14709. EXPECT_EQ(large_data, msg);
  14710. client.close();
  14711. }
  14712. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14713. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14714. "/ws-echo");
  14715. ASSERT_TRUE(client.connect());
  14716. const int num_threads = 4;
  14717. std::vector<std::thread> threads;
  14718. std::atomic<int> send_count{0};
  14719. for (int t = 0; t < num_threads; t++) {
  14720. threads.emplace_back([&client, &send_count, t]() {
  14721. for (int i = 0; i < 5; i++) {
  14722. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14723. if (client.send(text)) { send_count++; }
  14724. }
  14725. });
  14726. }
  14727. for (auto &th : threads) {
  14728. th.join();
  14729. }
  14730. int received = 0;
  14731. std::string msg;
  14732. while (received < send_count.load()) {
  14733. if (!client.read(msg)) { break; }
  14734. received++;
  14735. }
  14736. EXPECT_EQ(send_count.load(), received);
  14737. client.close();
  14738. }
  14739. TEST_F(WebSocketIntegrationTest, ReadString) {
  14740. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14741. "/ws-echo-string");
  14742. ASSERT_TRUE(client.connect());
  14743. ASSERT_TRUE(client.send("hello"));
  14744. std::string msg;
  14745. ASSERT_TRUE(client.read(msg));
  14746. EXPECT_EQ("echo: hello", msg);
  14747. ASSERT_TRUE(client.send("world"));
  14748. ASSERT_TRUE(client.read(msg));
  14749. EXPECT_EQ("echo: world", msg);
  14750. client.close();
  14751. }
  14752. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14753. Headers headers = {{"X-Test-Header", "test-value"}};
  14754. ws::WebSocketClient client(
  14755. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14756. ASSERT_TRUE(client.connect());
  14757. std::string msg;
  14758. ASSERT_TRUE(client.read(msg));
  14759. EXPECT_EQ("path:/ws-request-info", msg);
  14760. ASSERT_TRUE(client.read(msg));
  14761. EXPECT_EQ("header:test-value", msg);
  14762. client.close();
  14763. }
  14764. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14765. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14766. "/ws-echo");
  14767. client.set_read_timeout(1, 0); // 1 second
  14768. ASSERT_TRUE(client.connect());
  14769. // Don't send anything — server echo handler waits for a message,
  14770. // so read() should time out and return false.
  14771. std::string msg;
  14772. EXPECT_FALSE(client.read(msg));
  14773. }
  14774. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14775. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14776. "/ws-echo");
  14777. client.set_read_timeout(5, 0);
  14778. ASSERT_TRUE(client.connect());
  14779. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14780. // The server should reject it and close the connection.
  14781. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14782. client.send(oversized);
  14783. // The server's read() should have failed due to payload limit,
  14784. // so our read() should return false (connection closed).
  14785. std::string msg;
  14786. EXPECT_FALSE(client.read(msg));
  14787. }
  14788. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14789. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14790. "/ws-echo");
  14791. client.set_read_timeout(10, 0);
  14792. ASSERT_TRUE(client.connect());
  14793. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14794. // This should succeed.
  14795. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14796. ASSERT_TRUE(client.send(at_limit));
  14797. std::string msg;
  14798. ASSERT_TRUE(client.read(msg));
  14799. EXPECT_EQ(at_limit.size(), msg.size());
  14800. client.close();
  14801. }
  14802. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14803. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14804. "/nonexistent");
  14805. EXPECT_FALSE(client.connect());
  14806. EXPECT_FALSE(client.is_open());
  14807. }
  14808. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14809. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14810. "/ws-echo");
  14811. ASSERT_TRUE(client.connect());
  14812. ASSERT_TRUE(client.send(""));
  14813. std::string msg;
  14814. EXPECT_EQ(ws::Text, client.read(msg));
  14815. EXPECT_EQ("", msg);
  14816. client.close();
  14817. }
  14818. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14820. "/ws-echo");
  14821. // First connection
  14822. ASSERT_TRUE(client.connect());
  14823. ASSERT_TRUE(client.send("first"));
  14824. std::string msg;
  14825. ASSERT_TRUE(client.read(msg));
  14826. EXPECT_EQ("first", msg);
  14827. client.close();
  14828. EXPECT_FALSE(client.is_open());
  14829. // Reconnect using the same client object
  14830. ASSERT_TRUE(client.connect());
  14831. ASSERT_TRUE(client.is_open());
  14832. ASSERT_TRUE(client.send("second"));
  14833. ASSERT_TRUE(client.read(msg));
  14834. EXPECT_EQ("second", msg);
  14835. client.close();
  14836. }
  14837. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14838. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14839. "/ws-close-status");
  14840. ASSERT_TRUE(client.connect());
  14841. // Trigger the server to close with GoingAway status
  14842. ASSERT_TRUE(client.send("trigger"));
  14843. // read() should return false after receiving the close frame
  14844. std::string msg;
  14845. EXPECT_FALSE(client.read(msg));
  14846. EXPECT_FALSE(client.is_open());
  14847. }
  14848. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14849. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14850. "/ws-echo");
  14851. ASSERT_TRUE(client.connect());
  14852. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14853. EXPECT_FALSE(client.is_open());
  14854. }
  14855. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14856. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14857. ws::WebSocketClient client(
  14858. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14859. ASSERT_TRUE(client.connect());
  14860. // Server should have selected graphql-ws
  14861. EXPECT_EQ("graphql-ws", client.subprotocol());
  14862. client.close();
  14863. }
  14864. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14865. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14866. ws::WebSocketClient client(
  14867. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14868. ASSERT_TRUE(client.connect());
  14869. // Server should not have selected any subprotocol
  14870. EXPECT_TRUE(client.subprotocol().empty());
  14871. client.close();
  14872. }
  14873. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14874. // Connect without requesting any subprotocol
  14875. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14876. "/ws-subprotocol");
  14877. ASSERT_TRUE(client.connect());
  14878. EXPECT_TRUE(client.subprotocol().empty());
  14879. client.close();
  14880. }
  14881. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14883. "/ws-echo");
  14884. client.set_tcp_nodelay(true);
  14885. client.set_connection_timeout(3, 0);
  14886. bool socket_options_called = false;
  14887. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14888. ASSERT_TRUE(client.connect());
  14889. ASSERT_TRUE(client.is_open());
  14890. EXPECT_TRUE(socket_options_called);
  14891. ASSERT_TRUE(client.send("hello"));
  14892. std::string msg;
  14893. auto result = client.read(msg);
  14894. EXPECT_EQ(result, ws::ReadResult::Text);
  14895. EXPECT_EQ(msg, "hello");
  14896. client.close();
  14897. }
  14898. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14899. Server svr;
  14900. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14901. if (!req.has_header("Authorization")) {
  14902. res.status = StatusCode::Unauthorized_401;
  14903. res.set_content("Unauthorized", "text/plain");
  14904. return Server::HandlerResponse::Handled;
  14905. }
  14906. return Server::HandlerResponse::Unhandled;
  14907. });
  14908. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14909. std::string msg;
  14910. while (ws.read(msg)) {
  14911. ws.send(msg);
  14912. }
  14913. });
  14914. auto port = svr.bind_to_any_port("localhost");
  14915. std::thread t([&]() { svr.listen_after_bind(); });
  14916. svr.wait_until_ready();
  14917. // Without Authorization header - should be rejected before upgrade
  14918. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14919. EXPECT_FALSE(client1.connect());
  14920. // With Authorization header - should succeed
  14921. Headers headers = {{"Authorization", "Bearer token123"}};
  14922. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14923. headers);
  14924. ASSERT_TRUE(client2.connect());
  14925. ASSERT_TRUE(client2.send("hello"));
  14926. std::string msg;
  14927. ASSERT_TRUE(client2.read(msg));
  14928. EXPECT_EQ("hello", msg);
  14929. client2.close();
  14930. svr.stop();
  14931. t.join();
  14932. }
  14933. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14934. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14935. protected:
  14936. void SetUp() override {
  14937. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14938. SERVER_PRIVATE_KEY_FILE);
  14939. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14940. std::string msg;
  14941. ws::ReadResult ret;
  14942. while ((ret = ws.read(msg))) {
  14943. if (ret == ws::Binary) {
  14944. ws.send(msg.data(), msg.size());
  14945. } else {
  14946. ws.send(msg);
  14947. }
  14948. }
  14949. });
  14950. port_ = server_->bind_to_any_port(HOST);
  14951. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14952. server_->wait_until_ready();
  14953. }
  14954. void TearDown() override {
  14955. server_->stop();
  14956. if (server_thread_.joinable()) { server_thread_.join(); }
  14957. }
  14958. std::unique_ptr<SSLServer> server_;
  14959. std::thread server_thread_;
  14960. int port_ = 0;
  14961. };
  14962. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14963. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14964. "/ws-echo");
  14965. client.enable_server_certificate_verification(false);
  14966. ASSERT_TRUE(client.connect());
  14967. ASSERT_TRUE(client.is_open());
  14968. ASSERT_TRUE(client.send("Hello WSS"));
  14969. std::string msg;
  14970. EXPECT_EQ(ws::Text, client.read(msg));
  14971. EXPECT_EQ("Hello WSS", msg);
  14972. client.close();
  14973. }
  14974. #endif
  14975. #if !defined(_WIN32)
  14976. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14977. auto secret_dir = std::string("./symlink_test_secret");
  14978. auto served_dir = std::string("./symlink_test_served");
  14979. auto secret_file = secret_dir + "/secret.txt";
  14980. auto symlink_path = served_dir + "/escape";
  14981. // Setup: create directories and files
  14982. mkdir(secret_dir.c_str(), 0755);
  14983. mkdir(served_dir.c_str(), 0755);
  14984. {
  14985. std::ofstream ofs(secret_file);
  14986. ofs << "SECRET_DATA";
  14987. }
  14988. // Create symlink using absolute path so it resolves correctly
  14989. #ifdef PATH_MAX
  14990. char abs_secret[PATH_MAX];
  14991. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14992. #else
  14993. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  14994. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  14995. ASSERT_NE(nullptr, abs_secret);
  14996. #endif
  14997. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14998. auto se = detail::scope_exit([&] {
  14999. unlink(symlink_path.c_str());
  15000. unlink(secret_file.c_str());
  15001. rmdir(served_dir.c_str());
  15002. rmdir(secret_dir.c_str());
  15003. });
  15004. Server svr;
  15005. svr.set_mount_point("/", served_dir);
  15006. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15007. auto se2 = detail::scope_exit([&] {
  15008. svr.stop();
  15009. listen_thread.join();
  15010. });
  15011. svr.wait_until_ready();
  15012. Client cli("localhost", PORT);
  15013. // Symlink pointing outside base dir should be blocked
  15014. auto res = cli.Get("/escape/secret.txt");
  15015. ASSERT_TRUE(res);
  15016. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15017. }
  15018. #endif
  15019. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15020. // A GET request with Content-Length to a static file handler must have its
  15021. // body drained before the keep-alive connection is reused. Otherwise the
  15022. // unread body bytes are interpreted as the next HTTP request.
  15023. //
  15024. // The body is sent AFTER receiving the first response (as in the original
  15025. // PoC) so that the stream_line_reader cannot buffer it together with the
  15026. // headers of the first request.
  15027. Server svr;
  15028. svr.set_mount_point("/", "./www");
  15029. std::atomic<int> smuggled_count(0);
  15030. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15031. smuggled_count++;
  15032. res.set_content("oops", "text/plain");
  15033. });
  15034. auto port = svr.bind_to_any_port("localhost");
  15035. thread t = thread([&] { svr.listen_after_bind(); });
  15036. auto se = detail::scope_exit([&] {
  15037. svr.stop();
  15038. t.join();
  15039. });
  15040. svr.wait_until_ready();
  15041. auto error = Error::Success;
  15042. auto sock = detail::create_client_socket(
  15043. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15044. /*connection_timeout_sec=*/2, 0,
  15045. /*read_timeout_sec=*/2, 0,
  15046. /*write_timeout_sec=*/2, 0, std::string(), error);
  15047. ASSERT_NE(INVALID_SOCKET, sock);
  15048. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15049. // The "smuggled" request will be sent as the body of the outer GET
  15050. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15051. "Host: localhost\r\n"
  15052. "Connection: close\r\n"
  15053. "\r\n";
  15054. // Step 1: Send only the outer request headers (no body yet)
  15055. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15056. "Host: localhost\r\n"
  15057. "Content-Length: " +
  15058. std::to_string(smuggled.size()) +
  15059. "\r\n"
  15060. "\r\n";
  15061. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15062. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15063. // Step 2: Read the first response (server serves file without reading body)
  15064. std::string first_response;
  15065. char buf[4096];
  15066. for (;;) {
  15067. auto n = recv(sock, buf, sizeof(buf), 0);
  15068. if (n <= 0) break;
  15069. first_response.append(buf, static_cast<size_t>(n));
  15070. // Stop once we have a complete response (headers + body)
  15071. auto hdr_end = first_response.find("\r\n\r\n");
  15072. if (hdr_end != std::string::npos) {
  15073. // Check for Content-Length to know when the body is complete
  15074. auto cl_pos = first_response.find("Content-Length:");
  15075. if (cl_pos != std::string::npos) {
  15076. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15077. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15078. auto cl = std::stoul(
  15079. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15080. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15081. } else {
  15082. break; // No Content-Length, assume headers-only response
  15083. }
  15084. }
  15085. }
  15086. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15087. // Step 3: Now send the body, which looks like a new HTTP request.
  15088. // On a vulnerable server the keep-alive loop reads this as a second request.
  15089. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15090. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15091. // Step 4: Try to read a second response (should NOT exist after fix)
  15092. std::string second_response;
  15093. for (;;) {
  15094. auto n = recv(sock, buf, sizeof(buf), 0);
  15095. if (n <= 0) break;
  15096. second_response.append(buf, static_cast<size_t>(n));
  15097. }
  15098. // The smuggled request must NOT have been processed
  15099. EXPECT_EQ(0, smuggled_count.load());
  15100. }
  15101. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15102. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15103. // must be rejected with 400 Bad Request.
  15104. Server svr;
  15105. svr.Post("/test", [&](const Request &, Response &res) {
  15106. res.set_content("ok", "text/plain");
  15107. });
  15108. thread t = thread([&] { svr.listen(HOST, PORT); });
  15109. auto se = detail::scope_exit([&] {
  15110. svr.stop();
  15111. t.join();
  15112. ASSERT_FALSE(svr.is_running());
  15113. });
  15114. svr.wait_until_ready();
  15115. // Exact "chunked"
  15116. {
  15117. auto req = "POST /test HTTP/1.1\r\n"
  15118. "Host: localhost\r\n"
  15119. "Content-Length: 5\r\n"
  15120. "Transfer-Encoding: chunked\r\n"
  15121. "Connection: close\r\n"
  15122. "\r\n"
  15123. "hello";
  15124. std::string response;
  15125. ASSERT_TRUE(send_request(1, req, &response));
  15126. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15127. response.substr(0, response.find("\r\n")));
  15128. }
  15129. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15130. {
  15131. auto req = "POST /test HTTP/1.1\r\n"
  15132. "Host: localhost\r\n"
  15133. "Content-Length: 5\r\n"
  15134. "Transfer-Encoding: gzip, chunked\r\n"
  15135. "Connection: close\r\n"
  15136. "\r\n"
  15137. "hello";
  15138. std::string response;
  15139. ASSERT_TRUE(send_request(1, req, &response));
  15140. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15141. response.substr(0, response.find("\r\n")));
  15142. }
  15143. }