test.cc 595 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372
  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(ServerStartHandlerTest, CalledOnceWhenReady) {
  666. Server svr;
  667. svr.Get("/", [](const Request & /*req*/, Response &res) {
  668. res.set_content("ok", "text/plain");
  669. });
  670. std::atomic<int> start_count{0};
  671. std::atomic<bool> running_when_called{false};
  672. svr.set_start_handler([&]() {
  673. running_when_called = svr.is_running();
  674. start_count++;
  675. });
  676. auto port = svr.bind_to_any_port(HOST);
  677. std::thread t([&]() { svr.listen_after_bind(); });
  678. auto se = detail::scope_exit([&] {
  679. svr.stop();
  680. t.join();
  681. ASSERT_FALSE(svr.is_running());
  682. });
  683. svr.wait_until_ready();
  684. // A successful request proves the accept loop is running, which the start
  685. // handler precedes; so by now the handler must have run exactly once.
  686. Client cli(HOST, port);
  687. cli.set_connection_timeout(std::chrono::seconds(5));
  688. auto res = cli.Get("/");
  689. ASSERT_TRUE(res);
  690. EXPECT_EQ(StatusCode::OK_200, res->status);
  691. EXPECT_EQ(1, start_count.load());
  692. EXPECT_TRUE(running_when_called.load());
  693. }
  694. TEST(DivideTest, DivideStringTests) {
  695. auto divide = [](const std::string &str, char d) {
  696. std::string lhs;
  697. std::string rhs;
  698. detail::divide(str, d,
  699. [&](const char *lhs_data, std::size_t lhs_size,
  700. const char *rhs_data, std::size_t rhs_size) {
  701. lhs.assign(lhs_data, lhs_size);
  702. rhs.assign(rhs_data, rhs_size);
  703. });
  704. return std::make_pair(std::move(lhs), std::move(rhs));
  705. };
  706. {
  707. const auto res = divide("", '=');
  708. EXPECT_EQ(res.first, "");
  709. EXPECT_EQ(res.second, "");
  710. }
  711. {
  712. const auto res = divide("=", '=');
  713. EXPECT_EQ(res.first, "");
  714. EXPECT_EQ(res.second, "");
  715. }
  716. {
  717. const auto res = divide(" ", '=');
  718. EXPECT_EQ(res.first, " ");
  719. EXPECT_EQ(res.second, "");
  720. }
  721. {
  722. const auto res = divide("a", '=');
  723. EXPECT_EQ(res.first, "a");
  724. EXPECT_EQ(res.second, "");
  725. }
  726. {
  727. const auto res = divide("a=", '=');
  728. EXPECT_EQ(res.first, "a");
  729. EXPECT_EQ(res.second, "");
  730. }
  731. {
  732. const auto res = divide("=b", '=');
  733. EXPECT_EQ(res.first, "");
  734. EXPECT_EQ(res.second, "b");
  735. }
  736. {
  737. const auto res = divide("a=b", '=');
  738. EXPECT_EQ(res.first, "a");
  739. EXPECT_EQ(res.second, "b");
  740. }
  741. {
  742. const auto res = divide("a=b=", '=');
  743. EXPECT_EQ(res.first, "a");
  744. EXPECT_EQ(res.second, "b=");
  745. }
  746. {
  747. const auto res = divide("a=b=c", '=');
  748. EXPECT_EQ(res.first, "a");
  749. EXPECT_EQ(res.second, "b=c");
  750. }
  751. }
  752. TEST(SplitTest, ParseQueryString) {
  753. string s = "key1=val1&key2=val2&key3=val3";
  754. Params dic;
  755. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  756. [&](const char *b, const char *e) {
  757. string key, val;
  758. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  759. if (key.empty()) {
  760. key.assign(b2, e2);
  761. } else {
  762. val.assign(b2, e2);
  763. }
  764. });
  765. dic.emplace(key, val);
  766. });
  767. EXPECT_EQ("val1", dic.find("key1")->second);
  768. EXPECT_EQ("val2", dic.find("key2")->second);
  769. EXPECT_EQ("val3", dic.find("key3")->second);
  770. }
  771. TEST(SplitTest, ParseInvalidQueryTests) {
  772. {
  773. string s = " ";
  774. Params dict;
  775. detail::parse_query_text(s, dict);
  776. EXPECT_TRUE(dict.empty());
  777. }
  778. {
  779. string s = " = =";
  780. Params dict;
  781. detail::parse_query_text(s, dict);
  782. EXPECT_TRUE(dict.empty());
  783. }
  784. }
  785. TEST(ParseQueryTest, ParseQueryString) {
  786. {
  787. std::string s = "key1=val1&key2=val2&key3=val3";
  788. Params dic;
  789. detail::parse_query_text(s, dic);
  790. EXPECT_EQ("val1", dic.find("key1")->second);
  791. EXPECT_EQ("val2", dic.find("key2")->second);
  792. EXPECT_EQ("val3", dic.find("key3")->second);
  793. }
  794. {
  795. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  796. Params dic;
  797. detail::parse_query_text(s, dic);
  798. EXPECT_EQ("", dic.find("key1")->second);
  799. EXPECT_EQ("val1", dic.find("key2")->second);
  800. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  801. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  802. }
  803. }
  804. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  805. Params dic;
  806. EXPECT_EQ(detail::params_to_query_str(dic), "");
  807. dic.emplace("key1", "val1");
  808. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  809. dic.emplace("key2", "val2");
  810. dic.emplace("key3", "val3");
  811. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  812. }
  813. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  814. string content_type = "multipart/form-data; boundary=something";
  815. string boundary;
  816. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  817. EXPECT_TRUE(ret);
  818. EXPECT_EQ(boundary, "something");
  819. }
  820. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  821. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  822. string boundary;
  823. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  824. EXPECT_TRUE(ret);
  825. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  826. }
  827. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  828. string content_type =
  829. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  830. string boundary;
  831. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  832. EXPECT_TRUE(ret);
  833. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  834. }
  835. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  836. string content_type =
  837. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  838. string boundary;
  839. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  840. EXPECT_TRUE(ret);
  841. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  842. }
  843. TEST(GetHeaderValueTest, DefaultValue) {
  844. Headers headers = {{"Dummy", "Dummy"}};
  845. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  846. EXPECT_STREQ("text/plain", val);
  847. }
  848. TEST(GetHeaderValueTest, DefaultValueInt) {
  849. Headers headers = {{"Dummy", "Dummy"}};
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  851. EXPECT_EQ(100ull, val);
  852. }
  853. TEST(GetHeaderValueTest, RegularValue) {
  854. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  855. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  856. EXPECT_STREQ("text/html", val);
  857. }
  858. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  859. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  860. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  861. EXPECT_STREQ("text/html", val);
  862. }
  863. TEST(GetHeaderValueTest, SetContent) {
  864. Response res;
  865. res.set_content("html", "text/html");
  866. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  867. res.set_content("text", "text/plain");
  868. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  869. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  870. }
  871. TEST(GetHeaderValueTest, RegularValueInt) {
  872. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  873. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  874. EXPECT_EQ(100ull, val);
  875. }
  876. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  877. Headers headers = {{"Content-Length", "x"}};
  878. auto is_invalid_value = false;
  879. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  880. is_invalid_value);
  881. EXPECT_EQ(0ull, val);
  882. EXPECT_TRUE(is_invalid_value);
  883. }
  884. TEST(GetHeaderValueTest, Range) {
  885. {
  886. Headers headers = {make_range_header({{1, -1}})};
  887. auto val = detail::get_header_value(headers, "Range", 0, 0);
  888. EXPECT_STREQ("bytes=1-", val);
  889. }
  890. {
  891. Headers headers = {make_range_header({{-1, 1}})};
  892. auto val = detail::get_header_value(headers, "Range", 0, 0);
  893. EXPECT_STREQ("bytes=-1", val);
  894. }
  895. {
  896. Headers headers = {make_range_header({{1, 10}})};
  897. auto val = detail::get_header_value(headers, "Range", 0, 0);
  898. EXPECT_STREQ("bytes=1-10", val);
  899. }
  900. {
  901. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  902. auto val = detail::get_header_value(headers, "Range", 0, 0);
  903. EXPECT_STREQ("bytes=1-10, 100-", val);
  904. }
  905. {
  906. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  907. auto val = detail::get_header_value(headers, "Range", 0, 0);
  908. EXPECT_STREQ("bytes=1-10, 100-200", val);
  909. }
  910. {
  911. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  912. auto val = detail::get_header_value(headers, "Range", 0, 0);
  913. EXPECT_STREQ("bytes=0-0, -1", val);
  914. }
  915. }
  916. TEST(ParseHeaderValueTest, Range) {
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(1u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(-1, ranges[0].second);
  924. }
  925. {
  926. Ranges ranges;
  927. auto ret = detail::parse_range_header("bytes=-1", ranges);
  928. EXPECT_TRUE(ret);
  929. EXPECT_EQ(1u, ranges.size());
  930. EXPECT_EQ(-1, ranges[0].first);
  931. EXPECT_EQ(1u, ranges[0].second);
  932. }
  933. {
  934. Ranges ranges;
  935. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  936. EXPECT_TRUE(ret);
  937. EXPECT_EQ(1u, ranges.size());
  938. EXPECT_EQ(1u, ranges[0].first);
  939. EXPECT_EQ(10u, ranges[0].second);
  940. }
  941. {
  942. Ranges ranges;
  943. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  944. EXPECT_FALSE(ret);
  945. }
  946. {
  947. Ranges ranges;
  948. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  949. EXPECT_TRUE(ret);
  950. EXPECT_EQ(2u, ranges.size());
  951. EXPECT_EQ(1u, ranges[0].first);
  952. EXPECT_EQ(10u, ranges[0].second);
  953. EXPECT_EQ(100u, ranges[1].first);
  954. EXPECT_EQ(-1, ranges[1].second);
  955. }
  956. {
  957. Ranges ranges;
  958. auto ret =
  959. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  960. EXPECT_TRUE(ret);
  961. EXPECT_EQ(3u, ranges.size());
  962. EXPECT_EQ(1u, ranges[0].first);
  963. EXPECT_EQ(10u, ranges[0].second);
  964. EXPECT_EQ(100u, ranges[1].first);
  965. EXPECT_EQ(200u, ranges[1].second);
  966. EXPECT_EQ(300u, ranges[2].first);
  967. EXPECT_EQ(400u, ranges[2].second);
  968. }
  969. {
  970. Ranges ranges;
  971. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  972. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  973. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  974. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  975. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  976. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  977. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  978. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  979. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  980. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  981. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  982. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  983. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  984. EXPECT_TRUE(ranges.empty());
  985. }
  986. }
  987. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  988. Request req;
  989. req.set_header("Accept-Encoding", "gzip");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  995. #else
  996. EXPECT_TRUE(ret == detail::EncodingType::None);
  997. #endif
  998. }
  999. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1000. Request req;
  1001. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1002. Response res;
  1003. res.set_header("Content-Type", "text/plain");
  1004. auto ret = detail::encoding_type(req, res);
  1005. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1006. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1007. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1008. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1009. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1010. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1011. #else
  1012. EXPECT_TRUE(ret == detail::EncodingType::None);
  1013. #endif
  1014. }
  1015. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1016. Request req;
  1017. req.set_header("Accept-Encoding",
  1018. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1019. Response res;
  1020. res.set_header("Content-Type", "text/plain");
  1021. auto ret = detail::encoding_type(req, res);
  1022. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1023. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1024. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1025. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1026. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1027. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1028. #else
  1029. EXPECT_TRUE(ret == detail::EncodingType::None);
  1030. #endif
  1031. }
  1032. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1033. // All supported encodings rejected with q=0 should return None
  1034. Request req;
  1035. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1036. Response res;
  1037. res.set_header("Content-Type", "text/plain");
  1038. auto ret = detail::encoding_type(req, res);
  1039. EXPECT_TRUE(ret == detail::EncodingType::None);
  1040. }
  1041. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1042. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1043. Request req;
  1044. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1045. Response res;
  1046. res.set_header("Content-Type", "text/plain");
  1047. auto ret = detail::encoding_type(req, res);
  1048. EXPECT_TRUE(ret == detail::EncodingType::None);
  1049. }
  1050. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1051. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1052. Request req;
  1053. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1054. Response res;
  1055. res.set_header("Content-Type", "text/plain");
  1056. auto ret = detail::encoding_type(req, res);
  1057. EXPECT_TRUE(ret == detail::EncodingType::None);
  1058. }
  1059. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1060. // RFC 7231: Accept-Encoding values are case-insensitive
  1061. Request req;
  1062. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1063. Response res;
  1064. res.set_header("Content-Type", "text/plain");
  1065. auto ret = detail::encoding_type(req, res);
  1066. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1067. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1068. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1069. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1070. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1071. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1072. #else
  1073. EXPECT_TRUE(ret == detail::EncodingType::None);
  1074. #endif
  1075. }
  1076. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1077. // q value should determine priority, not hardcoded order
  1078. Request req;
  1079. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1080. Response res;
  1081. res.set_header("Content-Type", "text/plain");
  1082. auto ret = detail::encoding_type(req, res);
  1083. // gzip has highest q=1.0, so it should be selected even though
  1084. // br and zstd are also supported
  1085. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1086. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1087. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1088. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1089. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1090. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1091. #else
  1092. EXPECT_TRUE(ret == detail::EncodingType::None);
  1093. #endif
  1094. }
  1095. TEST(BufferStreamTest, read) {
  1096. detail::BufferStream strm1;
  1097. Stream &strm = strm1;
  1098. EXPECT_EQ(5, strm.write("hello"));
  1099. char buf[512];
  1100. EXPECT_EQ(2, strm.read(buf, 2));
  1101. EXPECT_EQ('h', buf[0]);
  1102. EXPECT_EQ('e', buf[1]);
  1103. EXPECT_EQ(2, strm.read(buf, 2));
  1104. EXPECT_EQ('l', buf[0]);
  1105. EXPECT_EQ('l', buf[1]);
  1106. EXPECT_EQ(1, strm.read(buf, 1));
  1107. EXPECT_EQ('o', buf[0]);
  1108. EXPECT_EQ(0, strm.read(buf, 1));
  1109. }
  1110. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1111. auto host = "www.httpwatch.com";
  1112. auto ip = hosted_at(host);
  1113. EXPECT_EQ("23.96.13.243", ip);
  1114. std::vector<std::string> addrs;
  1115. hosted_at(host, addrs);
  1116. EXPECT_EQ(1u, addrs.size());
  1117. }
  1118. #if 0 // It depends on each test environment...
  1119. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1120. auto host = "www.youtube.com";
  1121. std::vector<std::string> addrs;
  1122. hosted_at(host, addrs);
  1123. EXPECT_EQ(20u, addrs.size());
  1124. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1125. EXPECT_TRUE(it != addrs.end());
  1126. }
  1127. #endif
  1128. class ChunkedEncodingTest : public ::testing::Test {
  1129. protected:
  1130. ChunkedEncodingTest()
  1131. : cli_(HOST, PORT)
  1132. #ifdef CPPHTTPLIB_SSL_ENABLED
  1133. ,
  1134. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1135. #endif
  1136. {
  1137. cli_.set_connection_timeout(2);
  1138. #ifdef CPPHTTPLIB_SSL_ENABLED
  1139. cli_.enable_server_certificate_verification(false);
  1140. #endif
  1141. }
  1142. virtual void SetUp() {
  1143. read_file("./image.jpg", image_data_);
  1144. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1145. res.set_content("Hello World!", "text/plain");
  1146. });
  1147. svr_.Get(
  1148. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1149. res.set_chunked_content_provider(
  1150. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1151. size_t remaining = image_data_.size() - offset;
  1152. if (remaining == 0) {
  1153. sink.done();
  1154. } else {
  1155. constexpr size_t CHUNK_SIZE = 1024;
  1156. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1157. sink.write(&image_data_[offset], send_size);
  1158. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1159. }
  1160. return true;
  1161. });
  1162. });
  1163. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1164. svr_.wait_until_ready();
  1165. }
  1166. virtual void TearDown() {
  1167. svr_.stop();
  1168. if (!request_threads_.empty()) {
  1169. std::this_thread::sleep_for(std::chrono::seconds(1));
  1170. for (auto &t : request_threads_) {
  1171. t.join();
  1172. }
  1173. }
  1174. t_.join();
  1175. }
  1176. #ifdef CPPHTTPLIB_SSL_ENABLED
  1177. SSLClient cli_;
  1178. SSLServer svr_;
  1179. #else
  1180. Client cli_;
  1181. Server svr_;
  1182. #endif
  1183. thread t_;
  1184. std::vector<thread> request_threads_;
  1185. std::string image_data_;
  1186. };
  1187. TEST_F(ChunkedEncodingTest, NormalGet) {
  1188. auto res = cli_.Get("/chunked");
  1189. ASSERT_TRUE(res);
  1190. std::string out;
  1191. read_file("./image.jpg", out);
  1192. EXPECT_EQ(StatusCode::OK_200, res->status);
  1193. EXPECT_EQ(out, res->body);
  1194. }
  1195. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1196. std::string body;
  1197. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1198. body.append(data, data_length);
  1199. return true;
  1200. });
  1201. ASSERT_TRUE(res);
  1202. std::string out;
  1203. read_file("./image.jpg", out);
  1204. EXPECT_EQ(StatusCode::OK_200, res->status);
  1205. EXPECT_EQ(out, body);
  1206. }
  1207. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1208. std::string body;
  1209. auto res = cli_.Get(
  1210. "/chunked",
  1211. [&](const Response &response) {
  1212. EXPECT_EQ(StatusCode::OK_200, response.status);
  1213. return true;
  1214. },
  1215. [&](const char *data, size_t data_length) {
  1216. body.append(data, data_length);
  1217. return true;
  1218. });
  1219. ASSERT_TRUE(res);
  1220. std::string out;
  1221. read_file("./image.jpg", out);
  1222. EXPECT_EQ(StatusCode::OK_200, res->status);
  1223. EXPECT_EQ(out, body);
  1224. }
  1225. TEST(RangeTest, FromHTTPBin_Online) {
  1226. auto host = "httpbingo.org";
  1227. auto path = std::string{"/range/32"};
  1228. #ifdef CPPHTTPLIB_SSL_ENABLED
  1229. auto port = 443;
  1230. SSLClient cli(host, port);
  1231. #else
  1232. auto port = 80;
  1233. Client cli(host, port);
  1234. #endif
  1235. cli.set_connection_timeout(5);
  1236. {
  1237. auto res = cli.Get(path);
  1238. ASSERT_TRUE(res);
  1239. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1240. EXPECT_EQ(StatusCode::OK_200, res->status);
  1241. }
  1242. {
  1243. Headers headers = {make_range_header({{1, -1}})};
  1244. auto res = cli.Get(path, headers);
  1245. ASSERT_TRUE(res);
  1246. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1248. }
  1249. {
  1250. Headers headers = {make_range_header({{1, 10}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. EXPECT_EQ("bcdefghijk", res->body);
  1254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1255. }
  1256. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1257. // entire resource, while the original httpbin returned 200. Both are
  1258. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1259. {
  1260. Headers headers = {make_range_header({{0, 31}})};
  1261. auto res = cli.Get(path, headers);
  1262. ASSERT_TRUE(res);
  1263. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1264. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1265. res->status == StatusCode::PartialContent_206);
  1266. }
  1267. {
  1268. Headers headers = {make_range_header({{0, -1}})};
  1269. auto res = cli.Get(path, headers);
  1270. ASSERT_TRUE(res);
  1271. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1272. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1273. res->status == StatusCode::PartialContent_206);
  1274. }
  1275. // go-httpbin returns 206 with clamped range for over-range requests,
  1276. // while the original httpbin returned 416. Both behaviors are observed
  1277. // in real servers, so we only verify the request succeeds.
  1278. {
  1279. Headers headers = {make_range_header({{0, 32}})};
  1280. auto res = cli.Get(path, headers);
  1281. ASSERT_TRUE(res);
  1282. }
  1283. }
  1284. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1285. auto host = "unresolvableaddress.local";
  1286. auto path = std::string{"/"};
  1287. #ifdef CPPHTTPLIB_SSL_ENABLED
  1288. auto port = 443;
  1289. SSLClient cli(host, port);
  1290. #else
  1291. auto port = 80;
  1292. Client cli(host, port);
  1293. #endif
  1294. cli.set_connection_timeout(1);
  1295. {
  1296. auto res = cli.Get(path);
  1297. ASSERT_FALSE(res);
  1298. }
  1299. std::this_thread::sleep_for(std::chrono::seconds(8));
  1300. }
  1301. #if defined(__linux__) && defined(__GLIBC__) && \
  1302. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1303. // Forward declaration: in split builds split.py strips `inline` and moves the
  1304. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1305. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1306. // against the symbol in both header-only and split builds.
  1307. namespace httplib {
  1308. namespace detail {
  1309. int getaddrinfo_with_timeout(const char *node, const char *service,
  1310. const struct addrinfo *hints,
  1311. struct addrinfo **res, time_t timeout_sec);
  1312. } // namespace detail
  1313. } // namespace httplib
  1314. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1315. //
  1316. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1317. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1318. // gai_suspend() call hits the connection timeout the function calls
  1319. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1320. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1321. // still alive and still references the now-destroyed stack frame.
  1322. //
  1323. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1324. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1325. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1326. // and runs them in a container.
  1327. namespace {
  1328. bool should_run_issue_2431_tests() {
  1329. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1330. return v && *v && std::string(v) != "0";
  1331. }
  1332. std::string unique_unresolvable_host(int n) {
  1333. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1334. // glibc still asks the configured nameserver — which is exactly the path
  1335. // we want to exercise. A unique label per call avoids the resolver cache.
  1336. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1337. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1338. std::to_string(n) + ".invalid";
  1339. }
  1340. } // namespace
  1341. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1342. if (!should_run_issue_2431_tests()) {
  1343. GTEST_SKIP()
  1344. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1345. }
  1346. for (int i = 0; i < 8; ++i) {
  1347. struct addrinfo hints;
  1348. memset(&hints, 0, sizeof(hints));
  1349. hints.ai_family = AF_UNSPEC;
  1350. hints.ai_socktype = SOCK_STREAM;
  1351. auto host = unique_unresolvable_host(i);
  1352. struct addrinfo *result = nullptr;
  1353. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1354. &result, /*timeout_sec=*/1);
  1355. if (rc == 0 && result) { freeaddrinfo(result); }
  1356. }
  1357. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1358. // stack region they still believe holds their gaicb.
  1359. std::this_thread::sleep_for(std::chrono::seconds(3));
  1360. }
  1361. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1362. if (!should_run_issue_2431_tests()) {
  1363. GTEST_SKIP()
  1364. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1365. }
  1366. std::atomic<bool> stop{false};
  1367. std::vector<std::thread> threads;
  1368. for (int t = 0; t < 8; ++t) {
  1369. threads.emplace_back([t, &stop] {
  1370. int i = 0;
  1371. while (!stop.load(std::memory_order_relaxed)) {
  1372. struct addrinfo hints;
  1373. memset(&hints, 0, sizeof(hints));
  1374. hints.ai_family = AF_UNSPEC;
  1375. hints.ai_socktype = SOCK_STREAM;
  1376. auto host = unique_unresolvable_host(t * 100000 + i++);
  1377. struct addrinfo *result = nullptr;
  1378. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1379. &result, /*timeout_sec=*/1);
  1380. if (rc == 0 && result) { freeaddrinfo(result); }
  1381. }
  1382. });
  1383. }
  1384. std::this_thread::sleep_for(std::chrono::seconds(8));
  1385. stop.store(true, std::memory_order_relaxed);
  1386. for (auto &th : threads) {
  1387. th.join();
  1388. }
  1389. std::this_thread::sleep_for(std::chrono::seconds(3));
  1390. }
  1391. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1392. if (!should_run_issue_2431_tests()) {
  1393. GTEST_SKIP()
  1394. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1395. }
  1396. std::atomic<bool> stop{false};
  1397. std::vector<std::thread> threads;
  1398. for (int t = 0; t < 8; ++t) {
  1399. threads.emplace_back([t, &stop] {
  1400. int i = 0;
  1401. while (!stop.load(std::memory_order_relaxed)) {
  1402. auto host = unique_unresolvable_host(t * 100000 + i++);
  1403. Client cli(host, 80);
  1404. cli.set_connection_timeout(1, 0);
  1405. cli.set_read_timeout(1, 0);
  1406. cli.set_write_timeout(1, 0);
  1407. (void)cli.Get("/");
  1408. }
  1409. });
  1410. }
  1411. std::this_thread::sleep_for(std::chrono::seconds(8));
  1412. stop.store(true, std::memory_order_relaxed);
  1413. for (auto &th : threads) {
  1414. th.join();
  1415. }
  1416. std::this_thread::sleep_for(std::chrono::seconds(3));
  1417. }
  1418. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1419. TEST(ConnectionErrorTest, InvalidHost) {
  1420. auto host = "-abcde.com";
  1421. #ifdef CPPHTTPLIB_SSL_ENABLED
  1422. auto port = 443;
  1423. SSLClient cli(host, port);
  1424. #else
  1425. auto port = 80;
  1426. Client cli(host, port);
  1427. #endif
  1428. cli.set_connection_timeout(std::chrono::seconds(2));
  1429. auto res = cli.Get("/");
  1430. ASSERT_TRUE(!res);
  1431. EXPECT_EQ(Error::Connection, res.error());
  1432. }
  1433. TEST(ConnectionErrorTest, InvalidHost2) {
  1434. auto host = "httpcan.org/";
  1435. #ifdef CPPHTTPLIB_SSL_ENABLED
  1436. SSLClient cli(host);
  1437. #else
  1438. Client cli(host);
  1439. #endif
  1440. cli.set_connection_timeout(std::chrono::seconds(2));
  1441. auto res = cli.Get("/");
  1442. ASSERT_TRUE(!res);
  1443. EXPECT_EQ(Error::Connection, res.error());
  1444. }
  1445. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1446. auto host = "httpcan.org/";
  1447. #ifdef CPPHTTPLIB_SSL_ENABLED
  1448. SSLClient cli(host);
  1449. #else
  1450. Client cli(host);
  1451. #endif
  1452. cli.set_connection_timeout(std::chrono::seconds(2));
  1453. auto res = cli.Get("/");
  1454. ASSERT_TRUE(!res);
  1455. stringstream s;
  1456. s << "error code: " << res.error();
  1457. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1458. }
  1459. TEST(ConnectionErrorTest, InvalidPort) {
  1460. auto host = "localhost";
  1461. auto port = 44380;
  1462. #ifdef CPPHTTPLIB_SSL_ENABLED
  1463. SSLClient cli(host, port);
  1464. #else
  1465. Client cli(host, port);
  1466. #endif
  1467. cli.set_connection_timeout(std::chrono::seconds(2));
  1468. auto res = cli.Get("/");
  1469. ASSERT_TRUE(!res);
  1470. EXPECT_TRUE(Error::Connection == res.error() ||
  1471. Error::ConnectionTimeout == res.error());
  1472. }
  1473. TEST(ConnectionErrorTest, Timeout_Online) {
  1474. auto host = "google.com";
  1475. #ifdef CPPHTTPLIB_SSL_ENABLED
  1476. auto port = 44380;
  1477. SSLClient cli(host, port);
  1478. #else
  1479. auto port = 8080;
  1480. Client cli(host, port);
  1481. #endif
  1482. cli.set_connection_timeout(std::chrono::seconds(2));
  1483. // only probe one address type so that the error reason
  1484. // correlates to the timed-out IPv4, not the unsupported
  1485. // IPv6 connection attempt
  1486. cli.set_address_family(AF_INET);
  1487. auto res = cli.Get("/");
  1488. ASSERT_TRUE(!res);
  1489. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1490. }
  1491. TEST(CancelTest, NoCancel_Online) {
  1492. auto host = "httpbingo.org";
  1493. auto path = std::string{"/range/32"};
  1494. #ifdef CPPHTTPLIB_SSL_ENABLED
  1495. auto port = 443;
  1496. SSLClient cli(host, port);
  1497. #else
  1498. auto port = 80;
  1499. Client cli(host, port);
  1500. #endif
  1501. cli.set_connection_timeout(std::chrono::seconds(5));
  1502. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1503. ASSERT_TRUE(res);
  1504. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1505. EXPECT_EQ(StatusCode::OK_200, res->status);
  1506. }
  1507. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1508. // Use /bytes with a large payload so that the DownloadProgress callback
  1509. // (which only fires for Content-Length responses) is invoked before the
  1510. // entire body is received, giving cancellation a chance to fire.
  1511. auto host = "httpbingo.org";
  1512. auto path = std::string{"/bytes/524288"};
  1513. #ifdef CPPHTTPLIB_SSL_ENABLED
  1514. auto port = 443;
  1515. SSLClient cli(host, port);
  1516. #else
  1517. auto port = 80;
  1518. Client cli(host, port);
  1519. #endif
  1520. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1521. cli.set_connection_timeout(std::chrono::seconds(5));
  1522. ASSERT_TRUE(!res);
  1523. EXPECT_EQ(Error::Canceled, res.error());
  1524. }
  1525. TEST(CancelTest, WithCancelLargePayload_Online) {
  1526. auto host = "httpbingo.org";
  1527. auto path = std::string{"/bytes/524288"};
  1528. #ifdef CPPHTTPLIB_SSL_ENABLED
  1529. auto port = 443;
  1530. SSLClient cli(host, port);
  1531. #else
  1532. auto port = 80;
  1533. Client cli(host, port);
  1534. #endif
  1535. cli.set_connection_timeout(std::chrono::seconds(5));
  1536. uint32_t count = 0;
  1537. auto res =
  1538. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1539. ASSERT_TRUE(!res);
  1540. EXPECT_EQ(Error::Canceled, res.error());
  1541. }
  1542. TEST(CancelTest, NoCancelPost) {
  1543. Server svr;
  1544. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1545. res.set_content("Hello World!", "text/plain");
  1546. });
  1547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1548. auto se = detail::scope_exit([&] {
  1549. svr.stop();
  1550. thread.join();
  1551. ASSERT_FALSE(svr.is_running());
  1552. });
  1553. svr.wait_until_ready();
  1554. Client cli(HOST, PORT);
  1555. cli.set_connection_timeout(std::chrono::seconds(5));
  1556. auto res =
  1557. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1558. "application/json", [](uint64_t, uint64_t) { return true; });
  1559. ASSERT_TRUE(res);
  1560. EXPECT_EQ("Hello World!", res->body);
  1561. EXPECT_EQ(StatusCode::OK_200, res->status);
  1562. }
  1563. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1564. Server svr;
  1565. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1566. res.set_content("Hello World!", "text/plain");
  1567. });
  1568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. thread.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. Client cli(HOST, PORT);
  1576. cli.set_connection_timeout(std::chrono::seconds(5));
  1577. auto res =
  1578. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1579. "application/json", [](uint64_t, uint64_t) { return false; });
  1580. ASSERT_TRUE(!res);
  1581. EXPECT_EQ(Error::Canceled, res.error());
  1582. }
  1583. TEST(CancelTest, WithCancelLargePayloadPost) {
  1584. Server svr;
  1585. svr.set_payload_max_length(200 * 1024 * 1024);
  1586. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1587. res.set_content(LARGE_DATA, "text/plain");
  1588. });
  1589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1590. auto se = detail::scope_exit([&] {
  1591. svr.stop();
  1592. thread.join();
  1593. ASSERT_FALSE(svr.is_running());
  1594. });
  1595. svr.wait_until_ready();
  1596. Client cli(HOST, PORT);
  1597. cli.set_payload_max_length(200 * 1024 * 1024);
  1598. cli.set_connection_timeout(std::chrono::seconds(5));
  1599. auto res =
  1600. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1601. "application/json", [](uint64_t, uint64_t) { return false; });
  1602. ASSERT_TRUE(!res);
  1603. EXPECT_EQ(Error::Canceled, res.error());
  1604. }
  1605. TEST(CancelTest, NoCancelPut) {
  1606. Server svr;
  1607. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. thread.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. Client cli(HOST, PORT);
  1618. cli.set_connection_timeout(std::chrono::seconds(5));
  1619. auto res =
  1620. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1621. "application/json", [](uint64_t, uint64_t) { return true; });
  1622. ASSERT_TRUE(res);
  1623. EXPECT_EQ("Hello World!", res->body);
  1624. EXPECT_EQ(StatusCode::OK_200, res->status);
  1625. }
  1626. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1627. Server svr;
  1628. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1629. res.set_content("Hello World!", "text/plain");
  1630. });
  1631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. thread.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. Client cli(HOST, PORT);
  1639. cli.set_connection_timeout(std::chrono::seconds(5));
  1640. auto res =
  1641. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1642. "application/json", [](uint64_t, uint64_t) { return false; });
  1643. ASSERT_TRUE(!res);
  1644. EXPECT_EQ(Error::Canceled, res.error());
  1645. }
  1646. TEST(CancelTest, WithCancelLargePayloadPut) {
  1647. Server svr;
  1648. svr.set_payload_max_length(200 * 1024 * 1024);
  1649. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1650. res.set_content(LARGE_DATA, "text/plain");
  1651. });
  1652. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1653. auto se = detail::scope_exit([&] {
  1654. svr.stop();
  1655. thread.join();
  1656. ASSERT_FALSE(svr.is_running());
  1657. });
  1658. svr.wait_until_ready();
  1659. Client cli(HOST, PORT);
  1660. cli.set_payload_max_length(200 * 1024 * 1024);
  1661. cli.set_connection_timeout(std::chrono::seconds(5));
  1662. auto res =
  1663. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1664. "application/json", [](uint64_t, uint64_t) { return false; });
  1665. ASSERT_TRUE(!res);
  1666. EXPECT_EQ(Error::Canceled, res.error());
  1667. }
  1668. TEST(CancelTest, NoCancelPatch) {
  1669. Server svr;
  1670. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1671. res.set_content("Hello World!", "text/plain");
  1672. });
  1673. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1674. auto se = detail::scope_exit([&] {
  1675. svr.stop();
  1676. thread.join();
  1677. ASSERT_FALSE(svr.is_running());
  1678. });
  1679. svr.wait_until_ready();
  1680. Client cli(HOST, PORT);
  1681. cli.set_connection_timeout(std::chrono::seconds(5));
  1682. auto res =
  1683. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1684. "application/json", [](uint64_t, uint64_t) { return true; });
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ("Hello World!", res->body);
  1687. EXPECT_EQ(StatusCode::OK_200, res->status);
  1688. }
  1689. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1690. Server svr;
  1691. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1692. res.set_content("Hello World!", "text/plain");
  1693. });
  1694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1695. auto se = detail::scope_exit([&] {
  1696. svr.stop();
  1697. thread.join();
  1698. ASSERT_FALSE(svr.is_running());
  1699. });
  1700. svr.wait_until_ready();
  1701. Client cli(HOST, PORT);
  1702. cli.set_connection_timeout(std::chrono::seconds(5));
  1703. auto res =
  1704. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1705. "application/json", [](uint64_t, uint64_t) { return false; });
  1706. ASSERT_TRUE(!res);
  1707. EXPECT_EQ(Error::Canceled, res.error());
  1708. }
  1709. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1710. Server svr;
  1711. svr.set_payload_max_length(200 * 1024 * 1024);
  1712. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1713. res.set_content(LARGE_DATA, "text/plain");
  1714. });
  1715. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1716. auto se = detail::scope_exit([&] {
  1717. svr.stop();
  1718. thread.join();
  1719. ASSERT_FALSE(svr.is_running());
  1720. });
  1721. svr.wait_until_ready();
  1722. Client cli(HOST, PORT);
  1723. cli.set_payload_max_length(200 * 1024 * 1024);
  1724. cli.set_connection_timeout(std::chrono::seconds(5));
  1725. auto res =
  1726. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1727. "application/json", [](uint64_t, uint64_t) { return false; });
  1728. ASSERT_TRUE(!res);
  1729. EXPECT_EQ(Error::Canceled, res.error());
  1730. }
  1731. TEST(CancelTest, NoCancelDelete) {
  1732. Server svr;
  1733. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1734. res.set_content("Hello World!", "text/plain");
  1735. });
  1736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1737. auto se = detail::scope_exit([&] {
  1738. svr.stop();
  1739. thread.join();
  1740. ASSERT_FALSE(svr.is_running());
  1741. });
  1742. svr.wait_until_ready();
  1743. Client cli(HOST, PORT);
  1744. cli.set_connection_timeout(std::chrono::seconds(5));
  1745. auto res =
  1746. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1747. "application/json", [](uint64_t, uint64_t) { return true; });
  1748. ASSERT_TRUE(res);
  1749. EXPECT_EQ("Hello World!", res->body);
  1750. EXPECT_EQ(StatusCode::OK_200, res->status);
  1751. }
  1752. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1753. Server svr;
  1754. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1755. res.set_content("Hello World!", "text/plain");
  1756. });
  1757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1758. auto se = detail::scope_exit([&] {
  1759. svr.stop();
  1760. thread.join();
  1761. ASSERT_FALSE(svr.is_running());
  1762. });
  1763. svr.wait_until_ready();
  1764. Client cli(HOST, PORT);
  1765. cli.set_connection_timeout(std::chrono::seconds(5));
  1766. auto res =
  1767. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1768. "application/json", [](uint64_t, uint64_t) { return false; });
  1769. ASSERT_TRUE(!res);
  1770. EXPECT_EQ(Error::Canceled, res.error());
  1771. }
  1772. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1773. Server svr;
  1774. svr.set_payload_max_length(200 * 1024 * 1024);
  1775. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1776. res.set_content(LARGE_DATA, "text/plain");
  1777. });
  1778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1779. auto se = detail::scope_exit([&] {
  1780. svr.stop();
  1781. thread.join();
  1782. ASSERT_FALSE(svr.is_running());
  1783. });
  1784. svr.wait_until_ready();
  1785. Client cli(HOST, PORT);
  1786. cli.set_payload_max_length(200 * 1024 * 1024);
  1787. cli.set_connection_timeout(std::chrono::seconds(5));
  1788. auto res =
  1789. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1790. "application/json", [](uint64_t, uint64_t) { return false; });
  1791. ASSERT_TRUE(!res);
  1792. EXPECT_EQ(Error::Canceled, res.error());
  1793. }
  1794. static std::string remove_whitespace(const std::string &input) {
  1795. std::string output;
  1796. output.reserve(input.size());
  1797. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1798. [](unsigned char c) { return !std::isspace(c); });
  1799. return output;
  1800. }
  1801. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1802. auto host = "httpbingo.org";
  1803. auto path = std::string{"/basic-auth/hello/world"};
  1804. #ifdef CPPHTTPLIB_SSL_ENABLED
  1805. auto port = 443;
  1806. SSLClient cli(host, port);
  1807. #else
  1808. auto port = 80;
  1809. Client cli(host, port);
  1810. #endif
  1811. {
  1812. auto res = cli.Get(path);
  1813. ASSERT_TRUE(res);
  1814. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1815. }
  1816. {
  1817. auto res =
  1818. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1819. ASSERT_TRUE(res);
  1820. auto body = remove_whitespace(res->body);
  1821. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1822. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1823. EXPECT_EQ(StatusCode::OK_200, res->status);
  1824. }
  1825. {
  1826. cli.set_basic_auth("hello", "world");
  1827. auto res = cli.Get(path);
  1828. ASSERT_TRUE(res);
  1829. auto body = remove_whitespace(res->body);
  1830. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1831. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1832. EXPECT_EQ(StatusCode::OK_200, res->status);
  1833. }
  1834. {
  1835. cli.set_basic_auth("hello", "bad");
  1836. auto res = cli.Get(path);
  1837. ASSERT_TRUE(res);
  1838. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1839. }
  1840. {
  1841. cli.set_basic_auth("bad", "world");
  1842. auto res = cli.Get(path);
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1845. }
  1846. }
  1847. #ifdef CPPHTTPLIB_SSL_ENABLED
  1848. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1849. auto host = "httpbingo.org";
  1850. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1851. auto paths = std::vector<std::string>{
  1852. "/digest-auth/auth/hello/world/MD5",
  1853. "/digest-auth/auth/hello/world/SHA-256",
  1854. };
  1855. auto port = 443;
  1856. SSLClient cli(host, port);
  1857. {
  1858. auto res = cli.Get(unauth_path);
  1859. ASSERT_TRUE(res);
  1860. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1861. }
  1862. {
  1863. cli.set_digest_auth("hello", "world");
  1864. for (const auto &path : paths) {
  1865. auto res = cli.Get(path.c_str());
  1866. ASSERT_TRUE(res);
  1867. auto body = remove_whitespace(res->body);
  1868. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1869. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1870. EXPECT_EQ(StatusCode::OK_200, res->status);
  1871. }
  1872. cli.set_digest_auth("hello", "bad");
  1873. for (const auto &path : paths) {
  1874. auto res = cli.Get(path.c_str());
  1875. ASSERT_TRUE(res);
  1876. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1877. }
  1878. }
  1879. }
  1880. #endif
  1881. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1882. auto host = "google.com";
  1883. auto another_host = "example.com";
  1884. auto wrong_ip = "0.0.0.0";
  1885. #ifdef CPPHTTPLIB_SSL_ENABLED
  1886. SSLClient cli(host);
  1887. #else
  1888. Client cli(host);
  1889. #endif
  1890. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1891. auto res = cli.Get("/");
  1892. ASSERT_TRUE(res);
  1893. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1894. }
  1895. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1896. auto host = "google.com";
  1897. auto wrong_ip = "0.0.0.0";
  1898. #ifdef CPPHTTPLIB_SSL_ENABLED
  1899. SSLClient cli(host);
  1900. #else
  1901. Client cli(host);
  1902. #endif
  1903. cli.set_hostname_addr_map({{host, wrong_ip}});
  1904. auto res = cli.Get("/");
  1905. ASSERT_TRUE(!res);
  1906. EXPECT_EQ(Error::Connection, res.error());
  1907. }
  1908. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1909. auto host = "httpbingo.org";
  1910. auto path = std::string{"/absolute-redirect/3"};
  1911. #ifdef CPPHTTPLIB_SSL_ENABLED
  1912. SSLClient cli(host);
  1913. #else
  1914. Client cli(host);
  1915. #endif
  1916. cli.set_follow_location(true);
  1917. auto res = cli.Get(path);
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::OK_200, res->status);
  1920. }
  1921. TEST(RedirectTest, Redirect_Online) {
  1922. auto host = "httpbingo.org";
  1923. auto path = std::string{"/redirect/3"};
  1924. #ifdef CPPHTTPLIB_SSL_ENABLED
  1925. SSLClient cli(host);
  1926. #else
  1927. Client cli(host);
  1928. #endif
  1929. cli.set_follow_location(true);
  1930. auto res = cli.Get(path);
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. }
  1934. TEST(RelativeRedirectTest, Redirect_Online) {
  1935. auto host = "httpbingo.org";
  1936. auto path = std::string{"/relative-redirect/3"};
  1937. #ifdef CPPHTTPLIB_SSL_ENABLED
  1938. SSLClient cli(host);
  1939. #else
  1940. Client cli(host);
  1941. #endif
  1942. cli.set_follow_location(true);
  1943. auto res = cli.Get(path);
  1944. ASSERT_TRUE(res);
  1945. EXPECT_EQ(StatusCode::OK_200, res->status);
  1946. }
  1947. TEST(TooManyRedirectTest, Redirect_Online) {
  1948. auto host = "httpbingo.org";
  1949. auto path = std::string{"/redirect/21"};
  1950. #ifdef CPPHTTPLIB_SSL_ENABLED
  1951. SSLClient cli(host);
  1952. #else
  1953. Client cli(host);
  1954. #endif
  1955. cli.set_follow_location(true);
  1956. auto res = cli.Get(path);
  1957. ASSERT_TRUE(!res);
  1958. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1959. }
  1960. #ifdef CPPHTTPLIB_SSL_ENABLED
  1961. TEST(YahooRedirectTest, Redirect_Online) {
  1962. Client cli("yahoo.com");
  1963. auto res = cli.Get("/");
  1964. ASSERT_TRUE(res);
  1965. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1966. cli.set_follow_location(true);
  1967. res = cli.Get("/");
  1968. ASSERT_TRUE(res);
  1969. EXPECT_EQ(StatusCode::OK_200, res->status);
  1970. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1971. }
  1972. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1973. #define REDIR_HOST "httpbingo.org"
  1974. #define REDIR_PATH "/redirect-to"
  1975. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1976. SSLClient cli(REDIR_HOST);
  1977. cli.set_follow_location(true);
  1978. auto res =
  1979. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ(StatusCode::OK_200, res->status);
  1982. }
  1983. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1984. SSLClient cli(REDIR_HOST);
  1985. cli.set_follow_location(true);
  1986. Params params;
  1987. params.emplace("url", "http://example.com");
  1988. params.emplace("status_code", "302");
  1989. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1990. ASSERT_TRUE(res);
  1991. EXPECT_EQ(StatusCode::OK_200, res->status);
  1992. }
  1993. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1994. SSLClient cli(REDIR_HOST);
  1995. cli.set_follow_location(true);
  1996. Params params;
  1997. params.emplace("url", "http://example.com");
  1998. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1999. ASSERT_TRUE(res);
  2000. EXPECT_EQ(StatusCode::OK_200, res->status);
  2001. }
  2002. TEST(UrlWithSpace, Redirect_Online) {
  2003. SSLClient cli("edge.forgecdn.net");
  2004. cli.set_follow_location(true);
  2005. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2006. ASSERT_TRUE(res);
  2007. EXPECT_EQ(StatusCode::OK_200, res->status);
  2008. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2009. }
  2010. #endif
  2011. #if !defined(_WIN32) && !defined(_WIN64)
  2012. TEST(ReceiveSignals, Signal) {
  2013. auto setupSignalHandlers = []() {
  2014. struct sigaction act;
  2015. sigemptyset(&act.sa_mask);
  2016. act.sa_flags = SA_SIGINFO;
  2017. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2018. switch (sig) {
  2019. case SIGINT:
  2020. default: break;
  2021. }
  2022. };
  2023. ::sigaction(SIGINT, &act, nullptr);
  2024. };
  2025. Server svr;
  2026. int port = 0;
  2027. auto thread = std::thread([&]() {
  2028. setupSignalHandlers();
  2029. port = svr.bind_to_any_port(HOST);
  2030. svr.listen_after_bind();
  2031. });
  2032. auto se = detail::scope_exit([&] {
  2033. svr.stop();
  2034. thread.join();
  2035. ASSERT_FALSE(svr.is_running());
  2036. });
  2037. svr.wait_until_ready();
  2038. ASSERT_TRUE(svr.is_running());
  2039. pthread_kill(thread.native_handle(), SIGINT);
  2040. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2041. ASSERT_TRUE(svr.is_running());
  2042. }
  2043. #endif
  2044. TEST(RedirectToDifferentPort, Redirect) {
  2045. Server svr1;
  2046. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2047. res.set_content("Hello World!", "text/plain");
  2048. });
  2049. int svr1_port = 0;
  2050. auto thread1 = std::thread([&]() {
  2051. svr1_port = svr1.bind_to_any_port(HOST);
  2052. svr1.listen_after_bind();
  2053. });
  2054. Server svr2;
  2055. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2056. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2057. });
  2058. int svr2_port = 0;
  2059. auto thread2 = std::thread([&]() {
  2060. svr2_port = svr2.bind_to_any_port(HOST);
  2061. svr2.listen_after_bind();
  2062. });
  2063. auto se = detail::scope_exit([&] {
  2064. svr2.stop();
  2065. thread2.join();
  2066. svr1.stop();
  2067. thread1.join();
  2068. ASSERT_FALSE(svr2.is_running());
  2069. ASSERT_FALSE(svr1.is_running());
  2070. });
  2071. svr1.wait_until_ready();
  2072. svr2.wait_until_ready();
  2073. Client cli("localhost", svr2_port);
  2074. cli.set_follow_location(true);
  2075. auto res = cli.Get("/2");
  2076. ASSERT_TRUE(res);
  2077. EXPECT_EQ(StatusCode::OK_200, res->status);
  2078. EXPECT_EQ("Hello World!", res->body);
  2079. }
  2080. static void
  2081. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2082. Server svr1;
  2083. std::string captured_authorization;
  2084. svr1.Get("/target", [&](const Request &req, Response &res) {
  2085. captured_authorization = req.get_header_value("Authorization");
  2086. res.set_content("OK", "text/plain");
  2087. });
  2088. int svr1_port = 0;
  2089. auto thread1 = std::thread([&]() {
  2090. svr1_port = svr1.bind_to_any_port(HOST);
  2091. svr1.listen_after_bind();
  2092. });
  2093. Server svr2;
  2094. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2095. res.set_redirect(
  2096. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2097. });
  2098. int svr2_port = 0;
  2099. auto thread2 = std::thread([&]() {
  2100. svr2_port = svr2.bind_to_any_port(HOST);
  2101. svr2.listen_after_bind();
  2102. });
  2103. auto se = detail::scope_exit([&] {
  2104. svr2.stop();
  2105. thread2.join();
  2106. svr1.stop();
  2107. thread1.join();
  2108. ASSERT_FALSE(svr2.is_running());
  2109. ASSERT_FALSE(svr1.is_running());
  2110. });
  2111. svr1.wait_until_ready();
  2112. svr2.wait_until_ready();
  2113. Client cli("localhost", svr2_port);
  2114. cli.set_follow_location(true);
  2115. set_auth(cli);
  2116. auto res = cli.Get("/redir");
  2117. ASSERT_TRUE(res);
  2118. EXPECT_EQ(StatusCode::OK_200, res->status);
  2119. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2120. EXPECT_TRUE(captured_authorization.empty());
  2121. }
  2122. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2123. TestDoNotForwardCredentialsOnRedirect(
  2124. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2125. }
  2126. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2127. TestDoNotForwardCredentialsOnRedirect(
  2128. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2129. }
  2130. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2131. Server svr;
  2132. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2133. // Port number that overflows int — should not crash
  2134. res.set_redirect("http://localhost:99999999999999999999/target");
  2135. });
  2136. auto port = svr.bind_to_any_port(HOST);
  2137. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2138. auto se = detail::scope_exit([&] {
  2139. svr.stop();
  2140. thread.join();
  2141. ASSERT_FALSE(svr.is_running());
  2142. });
  2143. svr.wait_until_ready();
  2144. Client cli(HOST, port);
  2145. cli.set_follow_location(true);
  2146. auto res = cli.Get("/redir");
  2147. // Should fail gracefully, not crash (no valid response due to bad port)
  2148. EXPECT_FALSE(res);
  2149. }
  2150. TEST(RedirectFromPageWithContent, Redirect) {
  2151. Server svr;
  2152. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2153. res.set_content("___", "text/plain");
  2154. res.set_redirect("/2");
  2155. });
  2156. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2157. res.set_content("Hello World!", "text/plain");
  2158. });
  2159. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2160. auto se = detail::scope_exit([&] {
  2161. svr.stop();
  2162. th.join();
  2163. ASSERT_FALSE(svr.is_running());
  2164. });
  2165. svr.wait_until_ready();
  2166. {
  2167. Client cli("localhost", PORT);
  2168. cli.set_follow_location(true);
  2169. std::string body;
  2170. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2171. body.append(data, data_length);
  2172. return true;
  2173. });
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::OK_200, res->status);
  2176. EXPECT_EQ("Hello World!", body);
  2177. }
  2178. {
  2179. Client cli("localhost", PORT);
  2180. std::string body;
  2181. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2182. body.append(data, data_length);
  2183. return true;
  2184. });
  2185. ASSERT_TRUE(res);
  2186. EXPECT_EQ(StatusCode::Found_302, res->status);
  2187. EXPECT_EQ("___", body);
  2188. }
  2189. }
  2190. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2191. Server svr;
  2192. auto port_str = std::to_string(PORT);
  2193. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2194. auto expected_host = "[::1]:" + port_str;
  2195. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2196. res.set_content("___", "text/plain");
  2197. // res.set_redirect("/2");
  2198. res.set_redirect(redirect_url);
  2199. });
  2200. svr.Get("/2", [&](const Request &req, Response &res) {
  2201. auto host_header = req.headers.find("Host");
  2202. ASSERT_TRUE(host_header != req.headers.end());
  2203. EXPECT_EQ(expected_host, host_header->second);
  2204. res.set_content("Hello World!", "text/plain");
  2205. });
  2206. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2207. auto se = detail::scope_exit([&] {
  2208. svr.stop();
  2209. th.join();
  2210. ASSERT_FALSE(svr.is_running());
  2211. });
  2212. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2213. // actually starts anything, so the condition !svr.is_running() will
  2214. // always remain true, and the loop never stops.
  2215. // This basically counts how many milliseconds have passed since the
  2216. // call to svr.listen(), and if after 5 seconds nothing started yet
  2217. // aborts the test.
  2218. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2219. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2220. ASSERT_LT(milliseconds, 5000U);
  2221. }
  2222. {
  2223. Client cli("::1", PORT);
  2224. cli.set_follow_location(true);
  2225. std::string body;
  2226. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2227. body.append(data, data_length);
  2228. return true;
  2229. });
  2230. ASSERT_TRUE(res);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ("Hello World!", body);
  2233. }
  2234. {
  2235. Client cli("::1", PORT);
  2236. std::string body;
  2237. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2238. body.append(data, data_length);
  2239. return true;
  2240. });
  2241. ASSERT_TRUE(res);
  2242. EXPECT_EQ(StatusCode::Found_302, res->status);
  2243. EXPECT_EQ("___", body);
  2244. }
  2245. }
  2246. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2247. Server svr;
  2248. svr.Get("/foo", [](const Request &req, Response &res) {
  2249. auto a = req.params.find("a");
  2250. if (a != req.params.end()) {
  2251. res.set_content((*a).second, "text/plain");
  2252. res.status = StatusCode::OK_200;
  2253. } else {
  2254. res.status = StatusCode::BadRequest_400;
  2255. }
  2256. });
  2257. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2258. auto se = detail::scope_exit([&] {
  2259. svr.stop();
  2260. thread.join();
  2261. ASSERT_FALSE(svr.is_running());
  2262. });
  2263. svr.wait_until_ready();
  2264. {
  2265. Client cli(HOST, PORT);
  2266. cli.set_path_encode(false);
  2267. auto res = cli.Get("/foo?a=explicitly+encoded");
  2268. ASSERT_TRUE(res);
  2269. EXPECT_EQ(StatusCode::OK_200, res->status);
  2270. // This expects it back with a space, as the `+` won't have been
  2271. // url-encoded, and server-side the params get decoded turning `+`
  2272. // into spaces.
  2273. EXPECT_EQ("explicitly encoded", res->body);
  2274. }
  2275. }
  2276. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2277. Server svr;
  2278. svr.Get("/", [](const Request &req, Response &) {
  2279. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2280. });
  2281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2282. auto se = detail::scope_exit([&] {
  2283. svr.stop();
  2284. thread.join();
  2285. ASSERT_FALSE(svr.is_running());
  2286. });
  2287. svr.wait_until_ready();
  2288. {
  2289. Client cli(HOST, PORT);
  2290. cli.set_path_encode(false);
  2291. auto res = cli.Get("/?something=%0A");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ(StatusCode::OK_200, res->status);
  2294. }
  2295. }
  2296. TEST(BindServerTest, BindDualStack) {
  2297. Server svr;
  2298. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2299. res.set_content("Hello World!", "text/plain");
  2300. });
  2301. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2302. auto se = detail::scope_exit([&] {
  2303. svr.stop();
  2304. thread.join();
  2305. ASSERT_FALSE(svr.is_running());
  2306. });
  2307. svr.wait_until_ready();
  2308. {
  2309. Client cli("127.0.0.1", PORT);
  2310. auto res = cli.Get("/1");
  2311. ASSERT_TRUE(res);
  2312. EXPECT_EQ(StatusCode::OK_200, res->status);
  2313. EXPECT_EQ("Hello World!", res->body);
  2314. }
  2315. {
  2316. Client cli("::1", PORT);
  2317. auto res = cli.Get("/1");
  2318. ASSERT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. EXPECT_EQ("Hello World!", res->body);
  2321. }
  2322. }
  2323. TEST(BindServerTest, BindAndListenSeparately) {
  2324. Server svr;
  2325. int port = svr.bind_to_any_port("0.0.0.0");
  2326. ASSERT_TRUE(svr.is_valid());
  2327. ASSERT_TRUE(port > 0);
  2328. svr.stop();
  2329. }
  2330. #ifdef CPPHTTPLIB_SSL_ENABLED
  2331. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2332. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2333. CLIENT_CA_CERT_DIR);
  2334. int port = svr.bind_to_any_port("0.0.0.0");
  2335. ASSERT_TRUE(svr.is_valid());
  2336. ASSERT_TRUE(port > 0);
  2337. svr.stop();
  2338. }
  2339. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2340. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2341. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2342. int port = svr.bind_to_any_port("0.0.0.0");
  2343. ASSERT_TRUE(svr.is_valid());
  2344. ASSERT_TRUE(port > 0);
  2345. svr.stop();
  2346. }
  2347. TEST(BindServerTest, UpdateCertsPem) {
  2348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2349. int port = svr.bind_to_any_port("0.0.0.0");
  2350. ASSERT_TRUE(svr.is_valid());
  2351. ASSERT_TRUE(port > 0);
  2352. // Read PEM files
  2353. std::string cert_pem, key_pem, ca_pem;
  2354. read_file(SERVER_CERT_FILE, cert_pem);
  2355. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2356. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2357. // Update server certificates using PEM API
  2358. ASSERT_TRUE(
  2359. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2360. ASSERT_TRUE(svr.is_valid());
  2361. svr.stop();
  2362. }
  2363. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2364. // Start server with client CA (enables client auth)
  2365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2366. ASSERT_TRUE(svr.is_valid());
  2367. bool handler_called = false;
  2368. svr.Get("/test", [&](const Request &req, Response &res) {
  2369. handler_called = true;
  2370. // Verify client certificate is present
  2371. auto cert = req.peer_cert();
  2372. EXPECT_TRUE(static_cast<bool>(cert));
  2373. res.set_content("ok", "text/plain");
  2374. });
  2375. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2376. auto se = detail::scope_exit([&] {
  2377. svr.stop();
  2378. t.join();
  2379. ASSERT_FALSE(svr.is_running());
  2380. });
  2381. svr.wait_until_ready();
  2382. // Read PEM files
  2383. std::string cert_pem, key_pem, ca_pem;
  2384. read_file(SERVER_CERT_FILE, cert_pem);
  2385. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2386. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2387. // Update server certificates and client CA using PEM API while server running
  2388. ASSERT_TRUE(
  2389. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2390. // Connect with client certificate
  2391. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2392. cli.enable_server_certificate_verification(false);
  2393. cli.set_connection_timeout(30);
  2394. auto res = cli.Get("/test");
  2395. ASSERT_TRUE(res);
  2396. ASSERT_EQ(StatusCode::OK_200, res->status);
  2397. ASSERT_TRUE(handler_called);
  2398. EXPECT_EQ("ok", res->body);
  2399. }
  2400. #endif
  2401. TEST(ErrorHandlerTest, ContentLength) {
  2402. Server svr;
  2403. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2404. res.status = StatusCode::OK_200;
  2405. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2406. "text/html"); // <= Content-Length still 13
  2407. });
  2408. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2409. res.set_content("Hello World!\n", "text/plain");
  2410. res.status = 524;
  2411. });
  2412. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2413. auto se = detail::scope_exit([&] {
  2414. svr.stop();
  2415. thread.join();
  2416. ASSERT_FALSE(svr.is_running());
  2417. });
  2418. svr.wait_until_ready();
  2419. {
  2420. Client cli(HOST, PORT);
  2421. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2422. ASSERT_TRUE(res);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2425. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2426. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2427. }
  2428. }
  2429. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2430. TEST(ExceptionTest, WithoutExceptionHandler) {
  2431. Server svr;
  2432. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2433. throw std::runtime_error("exception...");
  2434. });
  2435. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2436. throw std::runtime_error("exception\r\n...");
  2437. });
  2438. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. listen_thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli("localhost", PORT);
  2446. {
  2447. auto res = cli.Get("/exception");
  2448. ASSERT_TRUE(res);
  2449. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2450. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2451. }
  2452. {
  2453. auto res = cli.Get("/unknown");
  2454. ASSERT_TRUE(res);
  2455. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2456. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2457. }
  2458. }
  2459. TEST(ExceptionTest, WithExceptionHandler) {
  2460. Server svr;
  2461. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2462. std::exception_ptr ep) {
  2463. EXPECT_FALSE(ep == nullptr);
  2464. try {
  2465. std::rethrow_exception(ep);
  2466. } catch (std::exception &e) {
  2467. EXPECT_EQ("abc", std::string(e.what()));
  2468. } catch (...) {}
  2469. res.status = StatusCode::InternalServerError_500;
  2470. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2471. "text/html"); // <= Content-Length still 13 at this point
  2472. });
  2473. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!\n", "text/plain");
  2475. throw std::runtime_error("abc");
  2476. });
  2477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2478. auto se = detail::scope_exit([&] {
  2479. svr.stop();
  2480. thread.join();
  2481. ASSERT_FALSE(svr.is_running());
  2482. });
  2483. svr.wait_until_ready();
  2484. for (size_t i = 0; i < 10; i++) {
  2485. Client cli(HOST, PORT);
  2486. for (size_t j = 0; j < 100; j++) {
  2487. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2488. ASSERT_TRUE(res);
  2489. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2490. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2491. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2492. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2493. }
  2494. cli.set_keep_alive(true);
  2495. for (size_t j = 0; j < 100; j++) {
  2496. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2497. ASSERT_TRUE(res);
  2498. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2499. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2500. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2501. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2502. }
  2503. }
  2504. }
  2505. TEST(ExceptionTest, AndErrorHandler) {
  2506. Server svr;
  2507. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2508. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2509. });
  2510. svr.set_exception_handler(
  2511. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2512. EXPECT_FALSE(ep == nullptr);
  2513. try {
  2514. std::rethrow_exception(ep);
  2515. } catch (std::exception &e) {
  2516. res.set_content(e.what(), "text/html");
  2517. } catch (...) {}
  2518. res.status = StatusCode::InternalServerError_500;
  2519. });
  2520. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2521. throw std::runtime_error("EXCEPTION");
  2522. });
  2523. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2524. res.set_content("ERROR", "text/html");
  2525. res.status = StatusCode::InternalServerError_500;
  2526. });
  2527. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2528. auto se = detail::scope_exit([&] {
  2529. svr.stop();
  2530. thread.join();
  2531. ASSERT_FALSE(svr.is_running());
  2532. });
  2533. svr.wait_until_ready();
  2534. Client cli(HOST, PORT);
  2535. {
  2536. auto res = cli.Get("/exception");
  2537. ASSERT_TRUE(res);
  2538. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2539. EXPECT_EQ("EXCEPTION", res->body);
  2540. }
  2541. {
  2542. auto res = cli.Get("/error");
  2543. ASSERT_TRUE(res);
  2544. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2545. EXPECT_EQ("ERROR", res->body);
  2546. }
  2547. {
  2548. auto res = cli.Get("/invalid");
  2549. ASSERT_TRUE(res);
  2550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2551. EXPECT_EQ("NOT_FOUND", res->body);
  2552. }
  2553. }
  2554. #endif
  2555. TEST(NoContentTest, ContentLength) {
  2556. Server svr;
  2557. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2558. res.status = StatusCode::NoContent_204;
  2559. });
  2560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2561. auto se = detail::scope_exit([&] {
  2562. svr.stop();
  2563. thread.join();
  2564. ASSERT_FALSE(svr.is_running());
  2565. });
  2566. svr.wait_until_ready();
  2567. {
  2568. Client cli(HOST, PORT);
  2569. auto res = cli.Get("/hi");
  2570. ASSERT_TRUE(res);
  2571. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2572. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2573. }
  2574. }
  2575. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2576. #ifdef CPPHTTPLIB_SSL_ENABLED
  2577. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2578. ASSERT_TRUE(svr.is_valid());
  2579. #else
  2580. Server svr;
  2581. #endif
  2582. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2583. if (req.path == "/routing_handler") {
  2584. res.set_header("PRE_ROUTING", "on");
  2585. res.set_content("Routing Handler", "text/plain");
  2586. return httplib::Server::HandlerResponse::Handled;
  2587. }
  2588. return httplib::Server::HandlerResponse::Unhandled;
  2589. });
  2590. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2591. res.set_content("Error", "text/html");
  2592. });
  2593. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2594. if (req.path == "/routing_handler") {
  2595. res.set_header("POST_ROUTING", "on");
  2596. }
  2597. });
  2598. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!\n", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. {
  2609. #ifdef CPPHTTPLIB_SSL_ENABLED
  2610. SSLClient cli(HOST, PORT);
  2611. cli.enable_server_certificate_verification(false);
  2612. #else
  2613. Client cli(HOST, PORT);
  2614. #endif
  2615. auto res = cli.Get("/routing_handler");
  2616. ASSERT_TRUE(res);
  2617. EXPECT_EQ(StatusCode::OK_200, res->status);
  2618. EXPECT_EQ("Routing Handler", res->body);
  2619. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2620. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2621. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2622. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2623. }
  2624. {
  2625. #ifdef CPPHTTPLIB_SSL_ENABLED
  2626. SSLClient cli(HOST, PORT);
  2627. cli.enable_server_certificate_verification(false);
  2628. #else
  2629. Client cli(HOST, PORT);
  2630. #endif
  2631. auto res = cli.Get("/hi");
  2632. ASSERT_TRUE(res);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. EXPECT_EQ("Hello World!\n", res->body);
  2635. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2636. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2637. }
  2638. {
  2639. #ifdef CPPHTTPLIB_SSL_ENABLED
  2640. SSLClient cli(HOST, PORT);
  2641. cli.enable_server_certificate_verification(false);
  2642. #else
  2643. Client cli(HOST, PORT);
  2644. #endif
  2645. auto res = cli.Get("/aaa");
  2646. ASSERT_TRUE(res);
  2647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2648. EXPECT_EQ("Error", res->body);
  2649. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2650. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2651. }
  2652. }
  2653. TEST(RequestHandlerTest, PreRequestHandler) {
  2654. auto route_path = "/user/:user";
  2655. Server svr;
  2656. svr.Get("/hi", [](const Request &, Response &res) {
  2657. res.set_content("hi", "text/plain");
  2658. });
  2659. svr.Get(route_path, [](const Request &req, Response &res) {
  2660. res.set_content(req.path_params.at("user"), "text/plain");
  2661. });
  2662. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2663. if (req.matched_route == route_path) {
  2664. auto user = req.path_params.at("user");
  2665. if (user != "john") {
  2666. res.status = StatusCode::Forbidden_403;
  2667. res.set_content("error", "text/html");
  2668. return Server::HandlerResponse::Handled;
  2669. }
  2670. }
  2671. return Server::HandlerResponse::Unhandled;
  2672. });
  2673. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2674. auto se = detail::scope_exit([&] {
  2675. svr.stop();
  2676. thread.join();
  2677. ASSERT_FALSE(svr.is_running());
  2678. });
  2679. svr.wait_until_ready();
  2680. Client cli(HOST, PORT);
  2681. {
  2682. auto res = cli.Get("/hi");
  2683. ASSERT_TRUE(res);
  2684. EXPECT_EQ(StatusCode::OK_200, res->status);
  2685. EXPECT_EQ("hi", res->body);
  2686. }
  2687. {
  2688. auto res = cli.Get("/user/john");
  2689. ASSERT_TRUE(res);
  2690. EXPECT_EQ(StatusCode::OK_200, res->status);
  2691. EXPECT_EQ("john", res->body);
  2692. }
  2693. {
  2694. auto res = cli.Get("/user/invalid-user");
  2695. ASSERT_TRUE(res);
  2696. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2697. EXPECT_EQ("error", res->body);
  2698. }
  2699. }
  2700. // The pre-request handler must run before the request body is read, so a
  2701. // rejected request never forces the server to buffer a (potentially large)
  2702. // body. Here the posted body is larger than the payload limit: if the body
  2703. // were read first the server would answer 413, but because the pre-request
  2704. // handler runs first it answers 403 and the body is never read.
  2705. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  2706. Server svr;
  2707. svr.set_payload_max_length(8);
  2708. auto handler_ran = false;
  2709. svr.Post("/reject", [&](const Request &req, Response &res) {
  2710. handler_ran = true;
  2711. res.set_content(req.body, "text/plain");
  2712. });
  2713. svr.Post("/accept", [](const Request &req, Response &res) {
  2714. res.set_content(req.body, "text/plain");
  2715. });
  2716. svr.set_pre_request_handler([](const Request &req, Response &res) {
  2717. if (req.matched_route == "/reject") {
  2718. res.status = StatusCode::Forbidden_403;
  2719. res.set_content("denied", "text/plain");
  2720. return Server::HandlerResponse::Handled;
  2721. }
  2722. return Server::HandlerResponse::Unhandled;
  2723. });
  2724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2725. auto se = detail::scope_exit([&] {
  2726. svr.stop();
  2727. thread.join();
  2728. ASSERT_FALSE(svr.is_running());
  2729. });
  2730. svr.wait_until_ready();
  2731. Client cli(HOST, PORT);
  2732. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  2733. // rejects with 403 before the body is read, so 413 is never reached.
  2734. {
  2735. auto res = cli.Post("/reject", "0123456789", "text/plain");
  2736. ASSERT_TRUE(res);
  2737. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2738. EXPECT_EQ("denied", res->body);
  2739. EXPECT_FALSE(handler_ran);
  2740. }
  2741. // An approved route still reads the body and enforces the payload limit.
  2742. {
  2743. auto res = cli.Post("/accept", "0123456789", "text/plain");
  2744. ASSERT_TRUE(res);
  2745. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  2746. }
  2747. }
  2748. TEST(UserDataTest, BasicOperations) {
  2749. httplib::UserData ud;
  2750. // Initially empty
  2751. EXPECT_FALSE(ud.has("key"));
  2752. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2753. // set and get
  2754. ud.set("key", 42);
  2755. EXPECT_TRUE(ud.has("key"));
  2756. auto *p = ud.get<int>("key");
  2757. ASSERT_NE(nullptr, p);
  2758. EXPECT_EQ(42, *p);
  2759. // Type mismatch → nullptr
  2760. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2761. // Overwrite with different type
  2762. ud.set("key", std::string("hello"));
  2763. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2764. auto *s = ud.get<std::string>("key");
  2765. ASSERT_NE(nullptr, s);
  2766. EXPECT_EQ("hello", *s);
  2767. // erase
  2768. ud.erase("key");
  2769. EXPECT_FALSE(ud.has("key"));
  2770. // clear
  2771. ud.set("a", 1);
  2772. ud.set("b", 2);
  2773. ud.clear();
  2774. EXPECT_FALSE(ud.has("a"));
  2775. EXPECT_FALSE(ud.has("b"));
  2776. }
  2777. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2778. struct AuthCtx {
  2779. std::string user_id;
  2780. };
  2781. Server svr;
  2782. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2783. res.user_data.set("auth", AuthCtx{"alice"});
  2784. return Server::HandlerResponse::Unhandled;
  2785. });
  2786. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2787. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2788. ASSERT_NE(nullptr, ctx);
  2789. res.set_content("Hello " + ctx->user_id, "text/plain");
  2790. });
  2791. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2792. auto se = detail::scope_exit([&] {
  2793. svr.stop();
  2794. thread.join();
  2795. ASSERT_FALSE(svr.is_running());
  2796. });
  2797. svr.wait_until_ready();
  2798. Client cli(HOST, PORT);
  2799. auto res = cli.Get("/me");
  2800. ASSERT_TRUE(res);
  2801. EXPECT_EQ(StatusCode::OK_200, res->status);
  2802. EXPECT_EQ("Hello alice", res->body);
  2803. }
  2804. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2805. struct RoleCtx {
  2806. std::string role;
  2807. };
  2808. Server svr;
  2809. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2810. res.user_data.set("role", RoleCtx{"admin"});
  2811. return Server::HandlerResponse::Unhandled;
  2812. });
  2813. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2814. auto *ctx = res.user_data.get<RoleCtx>("role");
  2815. ASSERT_NE(nullptr, ctx);
  2816. res.set_content(ctx->role, "text/plain");
  2817. });
  2818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2819. auto se = detail::scope_exit([&] {
  2820. svr.stop();
  2821. thread.join();
  2822. ASSERT_FALSE(svr.is_running());
  2823. });
  2824. svr.wait_until_ready();
  2825. Client cli(HOST, PORT);
  2826. auto res = cli.Get("/role");
  2827. ASSERT_TRUE(res);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. EXPECT_EQ("admin", res->body);
  2830. }
  2831. TEST(InvalidFormatTest, StatusCode) {
  2832. Server svr;
  2833. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2834. res.set_content("Hello World!\n", "text/plain");
  2835. res.status = 9999; // Status should be a three-digit code...
  2836. });
  2837. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2838. auto se = detail::scope_exit([&] {
  2839. svr.stop();
  2840. thread.join();
  2841. ASSERT_FALSE(svr.is_running());
  2842. });
  2843. svr.wait_until_ready();
  2844. {
  2845. Client cli(HOST, PORT);
  2846. auto res = cli.Get("/hi");
  2847. ASSERT_FALSE(res);
  2848. }
  2849. }
  2850. TEST(URLFragmentTest, WithFragment) {
  2851. Server svr;
  2852. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2853. EXPECT_TRUE(req.target == "/hi");
  2854. });
  2855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2856. auto se = detail::scope_exit([&] {
  2857. svr.stop();
  2858. thread.join();
  2859. ASSERT_FALSE(svr.is_running());
  2860. });
  2861. svr.wait_until_ready();
  2862. {
  2863. Client cli(HOST, PORT);
  2864. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2865. EXPECT_TRUE(res);
  2866. EXPECT_EQ(StatusCode::OK_200, res->status);
  2867. res = cli.Get("/hi%23key1=val1=key2=val2");
  2868. EXPECT_TRUE(res);
  2869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2870. }
  2871. }
  2872. TEST(HeaderWriter, SetHeaderWriter) {
  2873. Server svr;
  2874. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2875. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2876. return detail::write_headers(strm, hdrs);
  2877. });
  2878. svr.Get("/hi", [](const Request &req, Response &res) {
  2879. auto it = req.headers.find("CustomClientHeader");
  2880. EXPECT_TRUE(it != req.headers.end());
  2881. EXPECT_EQ(it->second, "CustomClientValue");
  2882. res.set_content("Hello World!\n", "text/plain");
  2883. });
  2884. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2885. auto se = detail::scope_exit([&] {
  2886. svr.stop();
  2887. thread.join();
  2888. ASSERT_FALSE(svr.is_running());
  2889. });
  2890. svr.wait_until_ready();
  2891. {
  2892. Client cli(HOST, PORT);
  2893. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2894. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2895. return detail::write_headers(strm, hdrs);
  2896. });
  2897. auto res = cli.Get("/hi");
  2898. EXPECT_TRUE(res);
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. auto it = res->headers.find("CustomServerHeader");
  2901. EXPECT_TRUE(it != res->headers.end());
  2902. EXPECT_EQ(it->second, "CustomServerValue");
  2903. }
  2904. }
  2905. class ServerTest : public ::testing::Test {
  2906. protected:
  2907. ServerTest()
  2908. : cli_(HOST, PORT)
  2909. #ifdef CPPHTTPLIB_SSL_ENABLED
  2910. ,
  2911. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2912. #endif
  2913. {
  2914. #ifdef CPPHTTPLIB_SSL_ENABLED
  2915. cli_.enable_server_certificate_verification(false);
  2916. #endif
  2917. // Allow LARGE_DATA (100MB) responses
  2918. cli_.set_payload_max_length(200 * 1024 * 1024);
  2919. }
  2920. virtual void SetUp() {
  2921. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2922. svr_.set_payload_max_length(200 * 1024 * 1024);
  2923. svr_.set_mount_point("/", "./www");
  2924. svr_.set_mount_point("/mount", "./www2");
  2925. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2926. svr_.Get("/hi",
  2927. [&](const Request & /*req*/, Response &res) {
  2928. res.set_content("Hello World!", "text/plain");
  2929. })
  2930. .Get("/file_content",
  2931. [&](const Request & /*req*/, Response &res) {
  2932. res.set_file_content("./www/dir/test.html");
  2933. })
  2934. .Get("/file_content_with_content_type",
  2935. [&](const Request & /*req*/, Response &res) {
  2936. res.set_file_content("./www/file", "text/plain");
  2937. })
  2938. .Get("/invalid_file_content",
  2939. [&](const Request & /*req*/, Response &res) {
  2940. res.set_file_content("./www/dir/invalid_file_path");
  2941. })
  2942. .Get("/http_response_splitting",
  2943. [&](const Request & /*req*/, Response &res) {
  2944. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2945. EXPECT_EQ(0U, res.headers.size());
  2946. EXPECT_FALSE(res.has_header("a"));
  2947. res.set_header("a", "1\nSet-Cookie: a=1");
  2948. EXPECT_EQ(0U, res.headers.size());
  2949. EXPECT_FALSE(res.has_header("a"));
  2950. res.set_header("a", "1\rSet-Cookie: a=1");
  2951. EXPECT_EQ(0U, res.headers.size());
  2952. EXPECT_FALSE(res.has_header("a"));
  2953. res.set_header("a\r\nb", "0");
  2954. EXPECT_EQ(0U, res.headers.size());
  2955. EXPECT_FALSE(res.has_header("a"));
  2956. res.set_header("a\rb", "0");
  2957. EXPECT_EQ(0U, res.headers.size());
  2958. EXPECT_FALSE(res.has_header("a"));
  2959. res.set_header("a\nb", "0");
  2960. EXPECT_EQ(0U, res.headers.size());
  2961. EXPECT_FALSE(res.has_header("a"));
  2962. res.set_redirect("1\r\nSet-Cookie: a=1");
  2963. EXPECT_EQ(0U, res.headers.size());
  2964. EXPECT_FALSE(res.has_header("Location"));
  2965. })
  2966. .Get("/slow",
  2967. [&](const Request & /*req*/, Response &res) {
  2968. std::this_thread::sleep_for(std::chrono::seconds(4));
  2969. res.set_content("slow", "text/plain");
  2970. })
  2971. #if 0
  2972. .Post("/slowpost",
  2973. [&](const Request & /*req*/, Response &res) {
  2974. std::this_thread::sleep_for(std::chrono::seconds(2));
  2975. res.set_content("slow", "text/plain");
  2976. })
  2977. #endif
  2978. .Get("/remote_addr",
  2979. [&](const Request &req, Response &res) {
  2980. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2981. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2982. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2983. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2984. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2985. #endif
  2986. res.set_content(req.remote_addr, "text/plain");
  2987. })
  2988. .Get("/local_addr",
  2989. [&](const Request &req, Response &res) {
  2990. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2991. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2992. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2993. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2994. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2995. #endif
  2996. auto local_addr = req.local_addr;
  2997. auto local_port = std::to_string(req.local_port);
  2998. res.set_content(local_addr.append(":").append(local_port),
  2999. "text/plain");
  3000. })
  3001. .Get("/endwith%",
  3002. [&](const Request & /*req*/, Response &res) {
  3003. res.set_content("Hello World!", "text/plain");
  3004. })
  3005. .Get("/a\\+\\+b",
  3006. [&](const Request &req, Response &res) {
  3007. ASSERT_TRUE(req.has_param("a +b"));
  3008. auto val = req.get_param_value("a +b");
  3009. res.set_content(val, "text/plain");
  3010. })
  3011. .Get("/", [&](const Request & /*req*/,
  3012. Response &res) { res.set_redirect("/hi"); })
  3013. .Post("/1",
  3014. [](const Request & /*req*/, Response &res) {
  3015. res.set_redirect("/2", StatusCode::SeeOther_303);
  3016. })
  3017. .Get("/2",
  3018. [](const Request & /*req*/, Response &res) {
  3019. res.set_content("redirected.", "text/plain");
  3020. res.status = StatusCode::OK_200;
  3021. })
  3022. .Post("/person",
  3023. [&](const Request &req, Response &res) {
  3024. if (req.has_param("name") && req.has_param("note")) {
  3025. persons_[req.get_param_value("name")] =
  3026. req.get_param_value("note");
  3027. } else {
  3028. res.status = StatusCode::BadRequest_400;
  3029. }
  3030. })
  3031. .Put("/person",
  3032. [&](const Request &req, Response &res) {
  3033. if (req.has_param("name") && req.has_param("note")) {
  3034. persons_[req.get_param_value("name")] =
  3035. req.get_param_value("note");
  3036. } else {
  3037. res.status = StatusCode::BadRequest_400;
  3038. }
  3039. })
  3040. .Get("/person/(.*)",
  3041. [&](const Request &req, Response &res) {
  3042. string name = req.matches[1];
  3043. if (persons_.find(name) != persons_.end()) {
  3044. auto note = persons_[name];
  3045. res.set_content(note, "text/plain");
  3046. } else {
  3047. res.status = StatusCode::NotFound_404;
  3048. }
  3049. })
  3050. .Delete("/person",
  3051. [&](const Request &req, Response &res) {
  3052. if (req.has_param("name")) {
  3053. string name = req.get_param_value("name");
  3054. if (persons_.find(name) != persons_.end()) {
  3055. persons_.erase(name);
  3056. res.set_content("DELETED", "text/plain");
  3057. } else {
  3058. res.status = StatusCode::NotFound_404;
  3059. }
  3060. } else {
  3061. res.status = StatusCode::BadRequest_400;
  3062. }
  3063. })
  3064. .Post("/x-www-form-urlencoded-json",
  3065. [&](const Request &req, Response &res) {
  3066. auto json = req.get_param_value("json");
  3067. ASSERT_EQ(JSON_DATA, json);
  3068. res.set_content(json, "appliation/json");
  3069. res.status = StatusCode::OK_200;
  3070. })
  3071. .Get("/streamed-chunked",
  3072. [&](const Request & /*req*/, Response &res) {
  3073. res.set_chunked_content_provider(
  3074. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  3075. sink.os << "123";
  3076. sink.os << "456";
  3077. sink.os << "789";
  3078. sink.done();
  3079. return true;
  3080. });
  3081. })
  3082. .Get("/streamed-chunked-with-prohibited-trailer",
  3083. [&](const Request & /*req*/, Response &res) {
  3084. auto i = new int(0);
  3085. // Declare both a prohibited trailer (Content-Length) and an
  3086. // allowed one
  3087. res.set_header("Trailer", "Content-Length, X-Allowed");
  3088. res.set_chunked_content_provider(
  3089. "text/plain",
  3090. [i](size_t /*offset*/, DataSink &sink) {
  3091. switch (*i) {
  3092. case 0: sink.os << "123"; break;
  3093. case 1: sink.os << "456"; break;
  3094. case 2: sink.os << "789"; break;
  3095. case 3: {
  3096. sink.done_with_trailer(
  3097. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3098. } break;
  3099. }
  3100. (*i)++;
  3101. return true;
  3102. },
  3103. [i](bool success) {
  3104. EXPECT_TRUE(success);
  3105. delete i;
  3106. });
  3107. })
  3108. .Get("/streamed-chunked2",
  3109. [&](const Request & /*req*/, Response &res) {
  3110. auto i = new int(0);
  3111. res.set_chunked_content_provider(
  3112. "text/plain",
  3113. [i](size_t /*offset*/, DataSink &sink) {
  3114. switch (*i) {
  3115. case 0: sink.os << "123"; break;
  3116. case 1: sink.os << "456"; break;
  3117. case 2: sink.os << "789"; break;
  3118. case 3: sink.done(); break;
  3119. }
  3120. (*i)++;
  3121. return true;
  3122. },
  3123. [i](bool success) {
  3124. EXPECT_TRUE(success);
  3125. delete i;
  3126. });
  3127. })
  3128. .Get("/streamed-chunked-with-trailer",
  3129. [&](const Request & /*req*/, Response &res) {
  3130. auto i = new int(0);
  3131. res.set_header("Trailer", "Dummy1, Dummy2");
  3132. res.set_chunked_content_provider(
  3133. "text/plain",
  3134. [i](size_t /*offset*/, DataSink &sink) {
  3135. switch (*i) {
  3136. case 0: sink.os << "123"; break;
  3137. case 1: sink.os << "456"; break;
  3138. case 2: sink.os << "789"; break;
  3139. case 3: {
  3140. sink.done_with_trailer(
  3141. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3142. } break;
  3143. }
  3144. (*i)++;
  3145. return true;
  3146. },
  3147. [i](bool success) {
  3148. EXPECT_TRUE(success);
  3149. delete i;
  3150. });
  3151. })
  3152. .Get("/streamed",
  3153. [&](const Request & /*req*/, Response &res) {
  3154. res.set_content_provider(
  3155. 6, "text/plain",
  3156. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3157. sink.os << (offset < 3 ? "a" : "b");
  3158. return true;
  3159. });
  3160. })
  3161. .Get("/streamed-without-length",
  3162. [&](const Request & /*req*/, Response &res) {
  3163. auto data = new std::string("abcdefg");
  3164. res.set_content_provider(
  3165. "text/plain",
  3166. [data](size_t offset, DataSink &sink) {
  3167. if (offset < data->size()) {
  3168. sink.os << data->substr(offset);
  3169. }
  3170. sink.done();
  3171. return true;
  3172. },
  3173. [data](bool success) {
  3174. EXPECT_TRUE(success);
  3175. delete data;
  3176. });
  3177. })
  3178. .Get("/streamed-with-range",
  3179. [&](const Request &req, Response &res) {
  3180. auto data = new std::string("abcdefg");
  3181. res.set_content_provider(
  3182. data->size(), "text/plain",
  3183. [data](size_t offset, size_t length, DataSink &sink) {
  3184. size_t DATA_CHUNK_SIZE = 4;
  3185. const auto &d = *data;
  3186. auto out_len =
  3187. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3188. auto ret =
  3189. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3190. EXPECT_TRUE(ret);
  3191. return true;
  3192. },
  3193. [data, &req](bool success) {
  3194. EXPECT_EQ(success, !req.has_param("error"));
  3195. delete data;
  3196. });
  3197. })
  3198. .Get("/streamed-cancel",
  3199. [&](const Request & /*req*/, Response &res) {
  3200. res.set_content_provider(
  3201. size_t(-1), "text/plain",
  3202. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3203. sink.os << "data_chunk";
  3204. return true;
  3205. });
  3206. })
  3207. .Get("/regex-with-delimiter",
  3208. [&](const Request &req, Response & /*res*/) {
  3209. ASSERT_TRUE(req.has_param("key"));
  3210. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3211. })
  3212. .Get("/with-range",
  3213. [&](const Request & /*req*/, Response &res) {
  3214. res.set_content("abcdefg", "text/plain");
  3215. })
  3216. .Get("/test-start-time",
  3217. [&](const Request &req, Response & /*res*/) {
  3218. EXPECT_NE(req.start_time_,
  3219. std::chrono::steady_clock::time_point::min());
  3220. })
  3221. .Get("/with-range-customized-response",
  3222. [&](const Request & /*req*/, Response &res) {
  3223. res.status = StatusCode::BadRequest_400;
  3224. res.set_content(JSON_DATA, "application/json");
  3225. })
  3226. .Post("/chunked",
  3227. [&](const Request &req, Response & /*res*/) {
  3228. EXPECT_EQ(req.body, "dechunked post body");
  3229. })
  3230. .Post("/large-chunked",
  3231. [&](const Request &req, Response & /*res*/) {
  3232. std::string expected(6 * 30 * 1024u, 'a');
  3233. EXPECT_EQ(req.body, expected);
  3234. })
  3235. .Post("/multipart",
  3236. [&](const Request &req, Response & /*res*/) {
  3237. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3238. req.form.get_field_count("text2") +
  3239. req.form.get_field_count("file3") +
  3240. req.form.get_field_count("file4"));
  3241. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3242. req.form.get_file_count("file2"));
  3243. ASSERT_TRUE(!req.form.has_file("???"));
  3244. ASSERT_TRUE(!req.form.has_field("???"));
  3245. ASSERT_TRUE(req.body.empty());
  3246. {
  3247. const auto &text = req.form.get_field("text1");
  3248. EXPECT_EQ("text default", text);
  3249. }
  3250. {
  3251. const auto &text = req.form.get_field("text2");
  3252. EXPECT_EQ("aωb", text);
  3253. }
  3254. {
  3255. const auto &file = req.form.get_file("file1");
  3256. EXPECT_EQ("hello.txt", file.filename);
  3257. EXPECT_EQ("text/plain", file.content_type);
  3258. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3259. }
  3260. {
  3261. const auto &file = req.form.get_file("file2");
  3262. EXPECT_EQ("world.json", file.filename);
  3263. EXPECT_EQ("application/json", file.content_type);
  3264. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3265. }
  3266. {
  3267. const auto &text = req.form.get_field("file3");
  3268. EXPECT_EQ(0u, text.size());
  3269. }
  3270. {
  3271. const auto &text = req.form.get_field("file4");
  3272. EXPECT_EQ(0u, text.size());
  3273. }
  3274. })
  3275. .Post("/multipart/multi_file_values",
  3276. [&](const Request &req, Response & /*res*/) {
  3277. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3278. req.form.get_field_count("multi_text1"));
  3279. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3280. ASSERT_TRUE(!req.form.has_file("???"));
  3281. ASSERT_TRUE(!req.form.has_field("???"));
  3282. ASSERT_TRUE(req.body.empty());
  3283. {
  3284. const auto &text = req.form.get_field("text");
  3285. EXPECT_EQ("default text", text);
  3286. }
  3287. {
  3288. const auto &text1_values = req.form.get_fields("multi_text1");
  3289. EXPECT_EQ(2u, text1_values.size());
  3290. EXPECT_EQ("aaaaa", text1_values[0]);
  3291. EXPECT_EQ("bbbbb", text1_values[1]);
  3292. }
  3293. {
  3294. const auto &file1_values = req.form.get_files("multi_file1");
  3295. EXPECT_EQ(2u, file1_values.size());
  3296. auto file1 = file1_values[0];
  3297. EXPECT_EQ(file1.filename, "hello.txt");
  3298. EXPECT_EQ(file1.content_type, "text/plain");
  3299. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3300. auto file2 = file1_values[1];
  3301. EXPECT_EQ(file2.filename, "world.json");
  3302. EXPECT_EQ(file2.content_type, "application/json");
  3303. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3304. }
  3305. })
  3306. .Post("/empty",
  3307. [&](const Request &req, Response &res) {
  3308. EXPECT_EQ(req.body, "");
  3309. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3310. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3311. res.set_content("empty", "text/plain");
  3312. })
  3313. .Post("/empty-no-content-type",
  3314. [&](const Request &req, Response &res) {
  3315. EXPECT_EQ(req.body, "");
  3316. EXPECT_FALSE(req.has_header("Content-Type"));
  3317. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3318. res.set_content("empty-no-content-type", "text/plain");
  3319. })
  3320. .Post("/path-only",
  3321. [&](const Request &req, Response &res) {
  3322. EXPECT_EQ(req.body, "");
  3323. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3324. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3325. res.set_content("path-only", "text/plain");
  3326. })
  3327. .Post("/path-headers-only",
  3328. [&](const Request &req, Response &res) {
  3329. EXPECT_EQ(req.body, "");
  3330. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3331. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3332. EXPECT_EQ("world", req.get_header_value("hello"));
  3333. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3334. res.set_content("path-headers-only", "text/plain");
  3335. })
  3336. .Post("/post-large",
  3337. [&](const Request &req, Response &res) {
  3338. EXPECT_EQ(req.body, LARGE_DATA);
  3339. res.set_content(req.body, "text/plain");
  3340. })
  3341. .Post("/post-loopback",
  3342. [&](const Request &, Response &res,
  3343. ContentReader const &content_reader) {
  3344. std::string body;
  3345. content_reader([&](const char *data, size_t data_length) {
  3346. body.append(data, data_length);
  3347. return true;
  3348. });
  3349. res.set_content(body, "text/plain");
  3350. })
  3351. .Put("/put-loopback",
  3352. [&](const Request &, Response &res,
  3353. ContentReader const &content_reader) {
  3354. std::string body;
  3355. content_reader([&](const char *data, size_t data_length) {
  3356. body.append(data, data_length);
  3357. return true;
  3358. });
  3359. res.set_content(body, "text/plain");
  3360. })
  3361. .Patch("/patch-loopback",
  3362. [&](const Request &, Response &res,
  3363. ContentReader const &content_reader) {
  3364. std::string body;
  3365. content_reader([&](const char *data, size_t data_length) {
  3366. body.append(data, data_length);
  3367. return true;
  3368. });
  3369. res.set_content(body, "text/plain");
  3370. })
  3371. .Put("/empty-no-content-type",
  3372. [&](const Request &req, Response &res) {
  3373. EXPECT_EQ(req.body, "");
  3374. EXPECT_FALSE(req.has_header("Content-Type"));
  3375. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3376. res.set_content("empty-no-content-type", "text/plain");
  3377. })
  3378. .Put("/put",
  3379. [&](const Request &req, Response &res) {
  3380. EXPECT_EQ(req.body, "PUT");
  3381. res.set_content(req.body, "text/plain");
  3382. })
  3383. .Put("/put-large",
  3384. [&](const Request &req, Response &res) {
  3385. EXPECT_EQ(req.body, LARGE_DATA);
  3386. res.set_content(req.body, "text/plain");
  3387. })
  3388. .Patch("/patch",
  3389. [&](const Request &req, Response &res) {
  3390. EXPECT_EQ(req.body, "PATCH");
  3391. res.set_content(req.body, "text/plain");
  3392. })
  3393. .Delete("/delete",
  3394. [&](const Request & /*req*/, Response &res) {
  3395. res.set_content("DELETE", "text/plain");
  3396. })
  3397. .Delete("/delete-body",
  3398. [&](const Request &req, Response &res) {
  3399. EXPECT_EQ(req.body, "content");
  3400. res.set_content(req.body, "text/plain");
  3401. })
  3402. .Options(R"(\*)",
  3403. [&](const Request & /*req*/, Response &res) {
  3404. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3405. })
  3406. .Get("/request-target",
  3407. [&](const Request &req, Response & /*res*/) {
  3408. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3409. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3410. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3411. })
  3412. .Get("/long-query-value",
  3413. [&](const Request &req, Response & /*res*/) {
  3414. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3415. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3416. })
  3417. .Get("/too-long-query-value",
  3418. [&](const Request &req, Response & /*res*/) {
  3419. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3420. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3421. })
  3422. .Get("/array-param",
  3423. [&](const Request &req, Response & /*res*/) {
  3424. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3425. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3426. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3427. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3428. })
  3429. .Get("/array-param-values",
  3430. [&](const Request &req, Response & /*res*/) {
  3431. auto values = req.get_param_values("array");
  3432. EXPECT_EQ(3u, values.size());
  3433. EXPECT_EQ("value1", values[0]);
  3434. EXPECT_EQ("value2", values[1]);
  3435. EXPECT_EQ("value3", values[2]);
  3436. auto empty = req.get_param_values("nonexistent");
  3437. EXPECT_TRUE(empty.empty());
  3438. })
  3439. .Post("/validate-no-multiple-headers",
  3440. [&](const Request &req, Response & /*res*/) {
  3441. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3442. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3443. })
  3444. .Post("/content_receiver",
  3445. [&](const Request &req, Response &res,
  3446. const ContentReader &content_reader) {
  3447. if (req.is_multipart_form_data()) {
  3448. std::vector<FormData> items;
  3449. content_reader(
  3450. [&](const FormData &file) {
  3451. items.push_back(file);
  3452. return true;
  3453. },
  3454. [&](const char *data, size_t data_length) {
  3455. items.back().content.append(data, data_length);
  3456. return true;
  3457. });
  3458. EXPECT_EQ(5u, items.size());
  3459. {
  3460. const auto &file = get_file_value(items, "text1");
  3461. EXPECT_TRUE(file.filename.empty());
  3462. EXPECT_EQ("text default", file.content);
  3463. }
  3464. {
  3465. const auto &file = get_file_value(items, "text2");
  3466. EXPECT_TRUE(file.filename.empty());
  3467. EXPECT_EQ("aωb", file.content);
  3468. }
  3469. {
  3470. const auto &file = get_file_value(items, "file1");
  3471. EXPECT_EQ("hello.txt", file.filename);
  3472. EXPECT_EQ("text/plain", file.content_type);
  3473. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3474. }
  3475. {
  3476. const auto &file = get_file_value(items, "file2");
  3477. EXPECT_EQ("world.json", file.filename);
  3478. EXPECT_EQ("application/json", file.content_type);
  3479. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3480. }
  3481. {
  3482. const auto &file = get_file_value(items, "file3");
  3483. EXPECT_TRUE(file.filename.empty());
  3484. EXPECT_EQ("application/octet-stream", file.content_type);
  3485. EXPECT_EQ(0u, file.content.size());
  3486. }
  3487. } else {
  3488. std::string body;
  3489. content_reader([&](const char *data, size_t data_length) {
  3490. EXPECT_EQ(7U, data_length);
  3491. body.append(data, data_length);
  3492. return true;
  3493. });
  3494. EXPECT_EQ(body, "content");
  3495. res.set_content(body, "text/plain");
  3496. }
  3497. })
  3498. .Put("/content_receiver",
  3499. [&](const Request & /*req*/, Response &res,
  3500. const ContentReader &content_reader) {
  3501. std::string body;
  3502. content_reader([&](const char *data, size_t data_length) {
  3503. body.append(data, data_length);
  3504. return true;
  3505. });
  3506. EXPECT_EQ(body, "content");
  3507. res.set_content(body, "text/plain");
  3508. })
  3509. .Patch("/content_receiver",
  3510. [&](const Request & /*req*/, Response &res,
  3511. const ContentReader &content_reader) {
  3512. std::string body;
  3513. content_reader([&](const char *data, size_t data_length) {
  3514. body.append(data, data_length);
  3515. return true;
  3516. });
  3517. EXPECT_EQ(body, "content");
  3518. res.set_content(body, "text/plain");
  3519. })
  3520. .Post("/query-string-and-body",
  3521. [&](const Request &req, Response & /*res*/) {
  3522. ASSERT_TRUE(req.has_param("key"));
  3523. EXPECT_EQ(req.get_param_value("key"), "value");
  3524. EXPECT_EQ(req.body, "content");
  3525. })
  3526. .Get("/last-request",
  3527. [&](const Request &req, Response & /*res*/) {
  3528. EXPECT_EQ("close", req.get_header_value("Connection"));
  3529. })
  3530. .Get(R"(/redirect/(\d+))",
  3531. [&](const Request &req, Response &res) {
  3532. auto num = std::stoi(req.matches[1]) + 1;
  3533. std::string url = "/redirect/" + std::to_string(num);
  3534. res.set_redirect(url);
  3535. })
  3536. .Post("/binary",
  3537. [&](const Request &req, Response &res) {
  3538. EXPECT_EQ(4U, req.body.size());
  3539. EXPECT_EQ("application/octet-stream",
  3540. req.get_header_value("Content-Type"));
  3541. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3542. res.set_content(req.body, "application/octet-stream");
  3543. })
  3544. .Put("/binary",
  3545. [&](const Request &req, Response &res) {
  3546. EXPECT_EQ(4U, req.body.size());
  3547. EXPECT_EQ("application/octet-stream",
  3548. req.get_header_value("Content-Type"));
  3549. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3550. res.set_content(req.body, "application/octet-stream");
  3551. })
  3552. .Patch("/binary",
  3553. [&](const Request &req, Response &res) {
  3554. EXPECT_EQ(4U, req.body.size());
  3555. EXPECT_EQ("application/octet-stream",
  3556. req.get_header_value("Content-Type"));
  3557. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3558. res.set_content(req.body, "application/octet-stream");
  3559. })
  3560. .Delete("/binary",
  3561. [&](const Request &req, Response &res) {
  3562. EXPECT_EQ(4U, req.body.size());
  3563. EXPECT_EQ("application/octet-stream",
  3564. req.get_header_value("Content-Type"));
  3565. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3566. res.set_content(req.body, "application/octet-stream");
  3567. })
  3568. .Get("/issue1772",
  3569. [&](const Request & /*req*/, Response &res) {
  3570. res.status = 401;
  3571. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3572. })
  3573. .Delete("/issue609",
  3574. [](const httplib::Request &, httplib::Response &res,
  3575. const httplib::ContentReader &) {
  3576. res.set_content("ok", "text/plain");
  3577. })
  3578. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3579. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3580. .Get("/compress",
  3581. [&](const Request & /*req*/, Response &res) {
  3582. res.set_content(
  3583. "12345678901234567890123456789012345678901234567890123456789"
  3584. "01234567890123456789012345678901234567890",
  3585. "text/plain");
  3586. })
  3587. .Get("/compress-with-charset",
  3588. [&](const Request & /*req*/, Response &res) {
  3589. res.set_content(
  3590. "12345678901234567890123456789012345678901234567890123456789"
  3591. "01234567890123456789012345678901234567890",
  3592. "application/json; charset=utf-8");
  3593. })
  3594. .Get("/nocompress",
  3595. [&](const Request & /*req*/, Response &res) {
  3596. res.set_content(
  3597. "12345678901234567890123456789012345678901234567890123456789"
  3598. "01234567890123456789012345678901234567890",
  3599. "application/octet-stream");
  3600. })
  3601. .Post("/compress-multipart",
  3602. [&](const Request &req, Response & /*res*/) {
  3603. EXPECT_EQ(2u, req.form.fields.size());
  3604. ASSERT_TRUE(!req.form.has_field("???"));
  3605. {
  3606. const auto &text = req.form.get_field("key1");
  3607. EXPECT_EQ("test", text);
  3608. }
  3609. {
  3610. const auto &text = req.form.get_field("key2");
  3611. EXPECT_EQ("--abcdefg123", text);
  3612. }
  3613. })
  3614. #endif
  3615. ;
  3616. persons_["john"] = "programmer";
  3617. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3618. svr_.wait_until_ready();
  3619. }
  3620. virtual void TearDown() {
  3621. svr_.stop();
  3622. if (!request_threads_.empty()) {
  3623. std::this_thread::sleep_for(std::chrono::seconds(1));
  3624. for (auto &t : request_threads_) {
  3625. t.join();
  3626. }
  3627. }
  3628. t_.join();
  3629. }
  3630. map<string, string> persons_;
  3631. #ifdef CPPHTTPLIB_SSL_ENABLED
  3632. SSLClient cli_;
  3633. SSLServer svr_;
  3634. #else
  3635. Client cli_;
  3636. Server svr_;
  3637. #endif
  3638. thread t_;
  3639. std::vector<thread> request_threads_;
  3640. };
  3641. TEST_F(ServerTest, GetMethod200) {
  3642. auto res = cli_.Get("/hi");
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ("HTTP/1.1", res->version);
  3645. EXPECT_EQ(StatusCode::OK_200, res->status);
  3646. EXPECT_EQ("OK", res->reason);
  3647. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3648. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3649. EXPECT_EQ("Hello World!", res->body);
  3650. }
  3651. TEST_F(ServerTest, GetEmptyFile) {
  3652. auto res = cli_.Get("/empty_file");
  3653. ASSERT_TRUE(res);
  3654. EXPECT_EQ(StatusCode::OK_200, res->status);
  3655. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3656. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3657. EXPECT_EQ("", res->body);
  3658. }
  3659. TEST_F(ServerTest, GetFileContent) {
  3660. auto res = cli_.Get("/file_content");
  3661. ASSERT_TRUE(res);
  3662. EXPECT_EQ(StatusCode::OK_200, res->status);
  3663. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3664. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3665. EXPECT_EQ("test.html", res->body);
  3666. }
  3667. TEST_F(ServerTest, GetFileContentWithRange) {
  3668. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3669. ASSERT_TRUE(res);
  3670. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3671. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3672. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3673. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3674. EXPECT_EQ("est", res->body);
  3675. }
  3676. TEST_F(ServerTest, GetFileContentWithContentType) {
  3677. auto res = cli_.Get("/file_content_with_content_type");
  3678. ASSERT_TRUE(res);
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3681. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3682. EXPECT_EQ("file\n", res->body);
  3683. }
  3684. TEST_F(ServerTest, GetInvalidFileContent) {
  3685. auto res = cli_.Get("/invalid_file_content");
  3686. ASSERT_TRUE(res);
  3687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3688. }
  3689. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3690. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ("HTTP/1.1", res->version);
  3693. EXPECT_EQ(StatusCode::OK_200, res->status);
  3694. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3695. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3696. EXPECT_EQ("Hello World!", res->body);
  3697. }
  3698. TEST_F(ServerTest, GetMethod302) {
  3699. auto res = cli_.Get("/");
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::Found_302, res->status);
  3702. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3703. }
  3704. TEST_F(ServerTest, GetMethod302Redirect) {
  3705. cli_.set_follow_location(true);
  3706. auto res = cli_.Get("/");
  3707. ASSERT_TRUE(res);
  3708. EXPECT_EQ(StatusCode::OK_200, res->status);
  3709. EXPECT_EQ("Hello World!", res->body);
  3710. EXPECT_EQ("/hi", res->location);
  3711. }
  3712. TEST_F(ServerTest, GetMethod404) {
  3713. auto res = cli_.Get("/invalid");
  3714. ASSERT_TRUE(res);
  3715. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3716. }
  3717. TEST_F(ServerTest, HeadMethod200) {
  3718. auto res = cli_.Head("/hi");
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::OK_200, res->status);
  3721. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3722. EXPECT_TRUE(res->body.empty());
  3723. }
  3724. TEST_F(ServerTest, HeadMethod200Static) {
  3725. auto res = cli_.Head("/mount/dir/index.html");
  3726. ASSERT_TRUE(res);
  3727. EXPECT_EQ(StatusCode::OK_200, res->status);
  3728. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3729. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3730. EXPECT_TRUE(res->body.empty());
  3731. }
  3732. TEST_F(ServerTest, HeadMethod404) {
  3733. auto res = cli_.Head("/invalid");
  3734. ASSERT_TRUE(res);
  3735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3736. EXPECT_TRUE(res->body.empty());
  3737. }
  3738. TEST_F(ServerTest, GetMethodPersonJohn) {
  3739. auto res = cli_.Get("/person/john");
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::OK_200, res->status);
  3742. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3743. EXPECT_EQ("programmer", res->body);
  3744. }
  3745. TEST_F(ServerTest, PostMethod1) {
  3746. auto res = cli_.Get("/person/john1");
  3747. ASSERT_TRUE(res);
  3748. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3749. res = cli_.Post("/person", "name=john1&note=coder",
  3750. "application/x-www-form-urlencoded");
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(StatusCode::OK_200, res->status);
  3753. res = cli_.Get("/person/john1");
  3754. ASSERT_TRUE(res);
  3755. ASSERT_EQ(StatusCode::OK_200, res->status);
  3756. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3757. ASSERT_EQ("coder", res->body);
  3758. }
  3759. TEST_F(ServerTest, PostMethod2) {
  3760. auto res = cli_.Get("/person/john2");
  3761. ASSERT_TRUE(res);
  3762. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3763. Params params;
  3764. params.emplace("name", "john2");
  3765. params.emplace("note", "coder");
  3766. res = cli_.Post("/person", params);
  3767. ASSERT_TRUE(res);
  3768. ASSERT_EQ(StatusCode::OK_200, res->status);
  3769. res = cli_.Get("/person/john2");
  3770. ASSERT_TRUE(res);
  3771. ASSERT_EQ(StatusCode::OK_200, res->status);
  3772. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3773. ASSERT_EQ("coder", res->body);
  3774. }
  3775. TEST_F(ServerTest, PutMethod3) {
  3776. auto res = cli_.Get("/person/john3");
  3777. ASSERT_TRUE(res);
  3778. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3779. Params params;
  3780. params.emplace("name", "john3");
  3781. params.emplace("note", "coder");
  3782. res = cli_.Put("/person", params);
  3783. ASSERT_TRUE(res);
  3784. ASSERT_EQ(StatusCode::OK_200, res->status);
  3785. res = cli_.Get("/person/john3");
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::OK_200, res->status);
  3788. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3789. ASSERT_EQ("coder", res->body);
  3790. }
  3791. TEST_F(ServerTest, DeleteMethod1) {
  3792. auto res = cli_.Get("/person/john4");
  3793. ASSERT_TRUE(res);
  3794. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3795. Params params;
  3796. params.emplace("name", "john4");
  3797. params.emplace("note", "coder");
  3798. res = cli_.Post("/person", params);
  3799. ASSERT_TRUE(res);
  3800. ASSERT_EQ(StatusCode::OK_200, res->status);
  3801. res = cli_.Get("/person/john4");
  3802. ASSERT_TRUE(res);
  3803. ASSERT_EQ(StatusCode::OK_200, res->status);
  3804. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3805. ASSERT_EQ("coder", res->body);
  3806. Params delete_params;
  3807. delete_params.emplace("name", "john4");
  3808. res = cli_.Delete("/person", delete_params);
  3809. ASSERT_TRUE(res);
  3810. ASSERT_EQ(StatusCode::OK_200, res->status);
  3811. ASSERT_EQ("DELETED", res->body);
  3812. res = cli_.Get("/person/john4");
  3813. ASSERT_TRUE(res);
  3814. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3815. }
  3816. TEST_F(ServerTest, DeleteMethod2) {
  3817. auto res = cli_.Get("/person/john5");
  3818. ASSERT_TRUE(res);
  3819. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3820. Params params;
  3821. params.emplace("name", "john5");
  3822. params.emplace("note", "developer");
  3823. res = cli_.Post("/person", params);
  3824. ASSERT_TRUE(res);
  3825. ASSERT_EQ(StatusCode::OK_200, res->status);
  3826. res = cli_.Get("/person/john5");
  3827. ASSERT_TRUE(res);
  3828. ASSERT_EQ(StatusCode::OK_200, res->status);
  3829. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3830. ASSERT_EQ("developer", res->body);
  3831. Params delete_params;
  3832. delete_params.emplace("name", "john5");
  3833. Headers headers;
  3834. headers.emplace("Custom-Header", "test-value");
  3835. res = cli_.Delete("/person", headers, delete_params);
  3836. ASSERT_TRUE(res);
  3837. ASSERT_EQ(StatusCode::OK_200, res->status);
  3838. ASSERT_EQ("DELETED", res->body);
  3839. res = cli_.Get("/person/john5");
  3840. ASSERT_TRUE(res);
  3841. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3842. }
  3843. TEST_F(ServerTest, DeleteMethod3) {
  3844. auto res = cli_.Get("/person/john6");
  3845. ASSERT_TRUE(res);
  3846. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3847. Params params;
  3848. params.emplace("name", "john6");
  3849. params.emplace("note", "tester");
  3850. res = cli_.Post("/person", params);
  3851. ASSERT_TRUE(res);
  3852. ASSERT_EQ(StatusCode::OK_200, res->status);
  3853. res = cli_.Get("/person/john6");
  3854. ASSERT_TRUE(res);
  3855. ASSERT_EQ(StatusCode::OK_200, res->status);
  3856. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3857. ASSERT_EQ("tester", res->body);
  3858. Params delete_params;
  3859. delete_params.emplace("name", "john6");
  3860. Headers headers;
  3861. headers.emplace("Custom-Header", "test-value");
  3862. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3863. ASSERT_TRUE(res);
  3864. ASSERT_EQ(StatusCode::OK_200, res->status);
  3865. ASSERT_EQ("DELETED", res->body);
  3866. res = cli_.Get("/person/john6");
  3867. ASSERT_TRUE(res);
  3868. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3869. }
  3870. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3871. Params params;
  3872. params.emplace("json", JSON_DATA);
  3873. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3874. ASSERT_TRUE(res);
  3875. ASSERT_EQ(StatusCode::OK_200, res->status);
  3876. ASSERT_EQ(JSON_DATA, res->body);
  3877. }
  3878. TEST_F(ServerTest, PostEmptyContent) {
  3879. auto res = cli_.Post("/empty", "", "text/plain");
  3880. ASSERT_TRUE(res);
  3881. ASSERT_EQ(StatusCode::OK_200, res->status);
  3882. ASSERT_EQ("empty", res->body);
  3883. }
  3884. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3885. auto res = cli_.Post("/empty-no-content-type");
  3886. ASSERT_TRUE(res);
  3887. ASSERT_EQ(StatusCode::OK_200, res->status);
  3888. ASSERT_EQ("empty-no-content-type", res->body);
  3889. }
  3890. TEST_F(ServerTest, PostPathOnly) {
  3891. auto res = cli_.Post("/path-only");
  3892. ASSERT_TRUE(res);
  3893. ASSERT_EQ(StatusCode::OK_200, res->status);
  3894. ASSERT_EQ("path-only", res->body);
  3895. }
  3896. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3897. auto res = cli_.Post("/path-headers-only",
  3898. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3899. ASSERT_TRUE(res);
  3900. ASSERT_EQ(StatusCode::OK_200, res->status);
  3901. ASSERT_EQ("path-headers-only", res->body);
  3902. }
  3903. TEST_F(ServerTest, PostLarge) {
  3904. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3905. ASSERT_TRUE(res);
  3906. ASSERT_EQ(StatusCode::OK_200, res->status);
  3907. EXPECT_EQ(LARGE_DATA, res->body);
  3908. }
  3909. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3910. auto res = cli_.Put("/empty-no-content-type");
  3911. ASSERT_TRUE(res);
  3912. ASSERT_EQ(StatusCode::OK_200, res->status);
  3913. ASSERT_EQ("empty-no-content-type", res->body);
  3914. }
  3915. TEST_F(ServerTest, GetMethodDir) {
  3916. auto res = cli_.Get("/dir/");
  3917. ASSERT_TRUE(res);
  3918. EXPECT_EQ(StatusCode::OK_200, res->status);
  3919. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3920. auto body = R"(<html>
  3921. <head>
  3922. </head>
  3923. <body>
  3924. <a href="/dir/test.html">Test</a>
  3925. <a href="/hi">hi</a>
  3926. </body>
  3927. </html>
  3928. )";
  3929. EXPECT_EQ(body, res->body);
  3930. }
  3931. TEST_F(ServerTest, GetMethodDirTest) {
  3932. auto res = cli_.Get("/dir/test.html");
  3933. ASSERT_TRUE(res);
  3934. EXPECT_EQ(StatusCode::OK_200, res->status);
  3935. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3936. EXPECT_EQ("test.html", res->body);
  3937. }
  3938. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3939. auto res = cli_.Get("/dir/../dir/test.html");
  3940. ASSERT_TRUE(res);
  3941. EXPECT_EQ(StatusCode::OK_200, res->status);
  3942. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3943. EXPECT_EQ("test.html", res->body);
  3944. }
  3945. TEST_F(ServerTest, GetMethodInvalidPath) {
  3946. auto res = cli_.Get("/dir/../test.html");
  3947. ASSERT_TRUE(res);
  3948. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3949. }
  3950. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3951. auto res = cli_.Get("/../www/dir/test.html");
  3952. ASSERT_TRUE(res);
  3953. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3954. }
  3955. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3956. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3957. ASSERT_TRUE(res);
  3958. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3959. }
  3960. TEST_F(ServerTest, GetMethodDirMountTest) {
  3961. auto res = cli_.Get("/mount/dir/test.html");
  3962. ASSERT_TRUE(res);
  3963. EXPECT_EQ(StatusCode::OK_200, res->status);
  3964. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3965. EXPECT_EQ("test.html", res->body);
  3966. }
  3967. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3968. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3969. ASSERT_TRUE(res);
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3972. EXPECT_EQ("test.html", res->body);
  3973. }
  3974. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3975. auto res = cli_.Get("/mount/dir/../test.html");
  3976. ASSERT_TRUE(res);
  3977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3978. }
  3979. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3980. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3981. ASSERT_TRUE(res);
  3982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3983. }
  3984. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3985. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3986. ASSERT_TRUE(res);
  3987. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3988. }
  3989. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3990. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3993. }
  3994. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3995. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3996. ASSERT_TRUE(res);
  3997. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3998. }
  3999. TEST_F(ServerTest, PostMethod303) {
  4000. auto res = cli_.Post("/1", "body", "text/plain");
  4001. ASSERT_TRUE(res);
  4002. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  4003. EXPECT_EQ("/2", res->get_header_value("Location"));
  4004. }
  4005. TEST_F(ServerTest, PostMethod303Redirect) {
  4006. cli_.set_follow_location(true);
  4007. auto res = cli_.Post("/1", "body", "text/plain");
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(StatusCode::OK_200, res->status);
  4010. EXPECT_EQ("redirected.", res->body);
  4011. EXPECT_EQ("/2", res->location);
  4012. }
  4013. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  4014. auto res = cli_.Get("/dir/test.abcde");
  4015. ASSERT_TRUE(res);
  4016. EXPECT_EQ(StatusCode::OK_200, res->status);
  4017. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4018. EXPECT_EQ("abcde", res->body);
  4019. }
  4020. TEST_F(ServerTest, StaticFileRange) {
  4021. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4022. ASSERT_TRUE(res);
  4023. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4024. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4025. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4026. EXPECT_EQ(true, res->has_header("Content-Range"));
  4027. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4028. EXPECT_EQ(std::string("cd"), res->body);
  4029. }
  4030. TEST_F(ServerTest, StaticFileRanges) {
  4031. auto res =
  4032. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  4033. ASSERT_TRUE(res);
  4034. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4035. EXPECT_TRUE(
  4036. res->get_header_value("Content-Type")
  4037. .find(
  4038. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  4039. 0);
  4040. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  4041. }
  4042. TEST_F(ServerTest, StaticFileRangeHead) {
  4043. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  4044. ASSERT_TRUE(res);
  4045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4046. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  4047. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4048. EXPECT_EQ(true, res->has_header("Content-Range"));
  4049. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  4050. }
  4051. TEST_F(ServerTest, StaticFileRangeBigFile) {
  4052. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4055. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4056. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  4057. EXPECT_EQ(true, res->has_header("Content-Range"));
  4058. EXPECT_EQ("bytes 1048571-1048575/1048576",
  4059. res->get_header_value("Content-Range"));
  4060. EXPECT_EQ("LAST\n", res->body);
  4061. }
  4062. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  4063. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  4064. ASSERT_TRUE(res);
  4065. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4067. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  4068. EXPECT_EQ(true, res->has_header("Content-Range"));
  4069. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  4070. }
  4071. TEST_F(ServerTest, StaticFileBigFile) {
  4072. auto res = cli_.Get("/dir/1MB.txt");
  4073. ASSERT_TRUE(res);
  4074. EXPECT_EQ(StatusCode::OK_200, res->status);
  4075. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4076. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  4077. }
  4078. TEST_F(ServerTest, InvalidBaseDirMount) {
  4079. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  4080. }
  4081. TEST_F(ServerTest, Binary) {
  4082. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  4083. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  4084. "application/octet-stream");
  4085. ASSERT_TRUE(res);
  4086. ASSERT_EQ(StatusCode::OK_200, res->status);
  4087. ASSERT_EQ(4U, res->body.size());
  4088. res = cli_.Put("/binary", binary.data(), binary.size(),
  4089. "application/octet-stream");
  4090. ASSERT_TRUE(res);
  4091. ASSERT_EQ(StatusCode::OK_200, res->status);
  4092. ASSERT_EQ(4U, res->body.size());
  4093. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4094. "application/octet-stream");
  4095. ASSERT_TRUE(res);
  4096. ASSERT_EQ(StatusCode::OK_200, res->status);
  4097. ASSERT_EQ(4U, res->body.size());
  4098. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4099. "application/octet-stream");
  4100. ASSERT_TRUE(res);
  4101. ASSERT_EQ(StatusCode::OK_200, res->status);
  4102. ASSERT_EQ(4U, res->body.size());
  4103. }
  4104. TEST_F(ServerTest, BinaryString) {
  4105. auto binary = std::string("\x00\x01\x02\x03", 4);
  4106. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4107. ASSERT_TRUE(res);
  4108. ASSERT_EQ(StatusCode::OK_200, res->status);
  4109. ASSERT_EQ(4U, res->body.size());
  4110. res = cli_.Put("/binary", binary, "application/octet-stream");
  4111. ASSERT_TRUE(res);
  4112. ASSERT_EQ(StatusCode::OK_200, res->status);
  4113. ASSERT_EQ(4U, res->body.size());
  4114. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4115. ASSERT_TRUE(res);
  4116. ASSERT_EQ(StatusCode::OK_200, res->status);
  4117. ASSERT_EQ(4U, res->body.size());
  4118. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4119. ASSERT_TRUE(res);
  4120. ASSERT_EQ(StatusCode::OK_200, res->status);
  4121. ASSERT_EQ(4U, res->body.size());
  4122. }
  4123. TEST_F(ServerTest, EmptyRequest) {
  4124. auto res = cli_.Get("");
  4125. ASSERT_TRUE(!res);
  4126. EXPECT_EQ(Error::Connection, res.error());
  4127. }
  4128. TEST_F(ServerTest, LongRequest) {
  4129. std::string request;
  4130. for (size_t i = 0; i < 545; i++) {
  4131. request += "/TooLongRequest";
  4132. }
  4133. request += "OK";
  4134. auto res = cli_.Get(request.c_str());
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4137. }
  4138. TEST_F(ServerTest, TooLongRequest) {
  4139. std::string request;
  4140. for (size_t i = 0; i < 546; i++) {
  4141. request += "/TooLongRequest";
  4142. }
  4143. request += "_NG";
  4144. auto start = std::chrono::high_resolution_clock::now();
  4145. cli_.set_keep_alive(true);
  4146. auto res = cli_.Get(request.c_str());
  4147. auto end = std::chrono::high_resolution_clock::now();
  4148. auto elapsed =
  4149. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4150. .count();
  4151. ASSERT_TRUE(res);
  4152. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4153. EXPECT_LE(elapsed, 1000);
  4154. EXPECT_EQ("close", res->get_header_value("Connection"));
  4155. EXPECT_FALSE(cli_.is_socket_open());
  4156. }
  4157. TEST_F(ServerTest, AlmostTooLongRequest) {
  4158. // test for #2046 - URI length check shouldn't include other content on req
  4159. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4160. // leading /, space, HTTP/1.1)
  4161. std::string request =
  4162. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4163. auto res = cli_.Get(request.c_str());
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4166. }
  4167. TEST_F(ServerTest, LongHeader) {
  4168. Request req;
  4169. req.method = "GET";
  4170. req.path = "/hi";
  4171. std::string host_and_port;
  4172. host_and_port += HOST;
  4173. host_and_port += ":";
  4174. host_and_port += std::to_string(PORT);
  4175. req.headers.emplace("Host", host_and_port.c_str());
  4176. req.headers.emplace("Accept", "*/*");
  4177. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4178. req.headers.emplace(
  4179. "Header-Name",
  4180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4181. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4182. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4183. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4184. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4185. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4186. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4187. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4188. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4208. "@@@@@@@@@@@@@@@@");
  4209. auto res = std::make_shared<Response>();
  4210. auto error = Error::Success;
  4211. auto ret = cli_.send(req, *res, error);
  4212. ASSERT_TRUE(ret);
  4213. EXPECT_EQ(StatusCode::OK_200, res->status);
  4214. }
  4215. TEST_F(ServerTest, LongQueryValue) {
  4216. auto start = std::chrono::high_resolution_clock::now();
  4217. cli_.set_keep_alive(true);
  4218. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4219. auto end = std::chrono::high_resolution_clock::now();
  4220. auto elapsed =
  4221. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4222. .count();
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4225. EXPECT_LE(elapsed, 1000);
  4226. EXPECT_EQ("close", res->get_header_value("Connection"));
  4227. EXPECT_FALSE(cli_.is_socket_open());
  4228. }
  4229. TEST_F(ServerTest, TooLongQueryValue) {
  4230. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4231. ASSERT_FALSE(res);
  4232. EXPECT_EQ(Error::Read, res.error());
  4233. }
  4234. TEST_F(ServerTest, TooLongHeader) {
  4235. Request req;
  4236. req.method = "GET";
  4237. req.path = "/hi";
  4238. std::string host_and_port;
  4239. host_and_port += HOST;
  4240. host_and_port += ":";
  4241. host_and_port += std::to_string(PORT);
  4242. req.headers.emplace("Host", host_and_port.c_str());
  4243. req.headers.emplace("Accept", "*/*");
  4244. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4245. req.headers.emplace(
  4246. "Header-Name",
  4247. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4275. "@@@@@@@@@@@@@@@@@");
  4276. auto res = std::make_shared<Response>();
  4277. auto error = Error::Success;
  4278. auto ret = cli_.send(req, *res, error);
  4279. ASSERT_TRUE(ret);
  4280. EXPECT_EQ(StatusCode::OK_200, res->status);
  4281. }
  4282. TEST_F(ServerTest, HeaderCountAtLimit) {
  4283. // Test with headers just under the 100 limit
  4284. httplib::Headers headers;
  4285. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4286. // This should keep us just under the 100 header limit
  4287. for (int i = 0; i < 95; i++) {
  4288. std::string name = "X-Test-Header-" + std::to_string(i);
  4289. std::string value = "value" + std::to_string(i);
  4290. headers.emplace(name, value);
  4291. }
  4292. // This should work fine as we're under the limit
  4293. auto res = cli_.Get("/hi", headers);
  4294. EXPECT_TRUE(res);
  4295. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4296. }
  4297. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4298. // Test with many headers to exceed the 100 limit
  4299. httplib::Headers headers;
  4300. // Add 150 headers to definitely exceed the 100 limit
  4301. for (int i = 0; i < 150; i++) {
  4302. std::string name = "X-Test-Header-" + std::to_string(i);
  4303. std::string value = "value" + std::to_string(i);
  4304. headers.emplace(name, value);
  4305. }
  4306. // This should fail due to exceeding header count limit
  4307. cli_.set_keep_alive(true);
  4308. auto res = cli_.Get("/hi", headers);
  4309. // The server should respond with 400 Bad Request
  4310. ASSERT_TRUE(res);
  4311. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4312. EXPECT_EQ("close", res->get_header_value("Connection"));
  4313. EXPECT_FALSE(cli_.is_socket_open());
  4314. }
  4315. TEST_F(ServerTest, PercentEncoding) {
  4316. auto res = cli_.Get("/e%6edwith%");
  4317. ASSERT_TRUE(res);
  4318. EXPECT_EQ(StatusCode::OK_200, res->status);
  4319. }
  4320. TEST_F(ServerTest, PercentEncodingUnicode) {
  4321. auto res = cli_.Get("/e%u006edwith%");
  4322. ASSERT_TRUE(res);
  4323. EXPECT_EQ(StatusCode::OK_200, res->status);
  4324. }
  4325. TEST_F(ServerTest, InvalidPercentEncoding) {
  4326. auto res = cli_.Get("/%endwith%");
  4327. ASSERT_TRUE(res);
  4328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4329. }
  4330. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4331. auto res = cli_.Get("/%uendwith%");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4334. }
  4335. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4336. auto res = cli_.Get("/hello?aaa=bbb%");
  4337. ASSERT_TRUE(res);
  4338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4339. }
  4340. TEST_F(ServerTest, PlusSignEncoding) {
  4341. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4342. ASSERT_TRUE(res);
  4343. EXPECT_EQ(StatusCode::OK_200, res->status);
  4344. EXPECT_EQ("a +b", res->body);
  4345. }
  4346. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4347. // This test simulates a potential DoS attack using many headers
  4348. // to verify our security fix prevents memory exhaustion
  4349. httplib::Headers attack_headers;
  4350. // Attempt to add many headers like an attacker would (200 headers to far
  4351. // exceed limit)
  4352. for (int i = 0; i < 200; i++) {
  4353. std::string name = "X-Attack-Header-" + std::to_string(i);
  4354. std::string value = "attack_payload_" + std::to_string(i);
  4355. attack_headers.emplace(name, value);
  4356. }
  4357. // Try to POST with excessive headers
  4358. cli_.set_keep_alive(true);
  4359. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4360. // Should either fail or return 400 Bad Request due to security limit
  4361. if (res) {
  4362. // If we get a response, it should be 400 Bad Request
  4363. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4364. EXPECT_EQ("close", res->get_header_value("Connection"));
  4365. }
  4366. EXPECT_FALSE(cli_.is_socket_open());
  4367. }
  4368. TEST_F(ServerTest, MultipartFormData) {
  4369. UploadFormDataItems items = {
  4370. {"text1", "text default", "", ""},
  4371. {"text2", "aωb", "", ""},
  4372. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4373. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4374. {"file3", "", "", "application/octet-stream"},
  4375. {"file4", "", "", " application/json tmp-string "}};
  4376. auto res = cli_.Post("/multipart", items);
  4377. ASSERT_TRUE(res);
  4378. EXPECT_EQ(StatusCode::OK_200, res->status);
  4379. }
  4380. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4381. UploadFormDataItems items = {
  4382. {"text", "default text", "", ""},
  4383. {"multi_text1", "aaaaa", "", ""},
  4384. {"multi_text1", "bbbbb", "", ""},
  4385. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4386. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4387. "application/json"},
  4388. };
  4389. auto res = cli_.Post("/multipart/multi_file_values", items);
  4390. ASSERT_TRUE(res);
  4391. EXPECT_EQ(StatusCode::OK_200, res->status);
  4392. }
  4393. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4394. auto res = cli_.Get("/hi");
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4398. EXPECT_EQ("Hello World!", res->body);
  4399. }
  4400. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4401. Request req;
  4402. req.method = "POST";
  4403. req.path = "/chunked";
  4404. std::string host_and_port;
  4405. host_and_port += HOST;
  4406. host_and_port += ":";
  4407. host_and_port += std::to_string(PORT);
  4408. req.headers.emplace("Host", host_and_port.c_str());
  4409. req.headers.emplace("Accept", "*/*");
  4410. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4411. req.headers.emplace("Content-Type", "text/plain");
  4412. req.headers.emplace("Content-Length", "0");
  4413. req.headers.emplace(
  4414. "Transfer-Encoding",
  4415. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4416. // Client does not chunk, so make a chunked body manually.
  4417. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4418. auto res = std::make_shared<Response>();
  4419. auto error = Error::Success;
  4420. auto ret = cli_.send(req, *res, error);
  4421. ASSERT_TRUE(ret);
  4422. EXPECT_EQ(StatusCode::OK_200, res->status);
  4423. }
  4424. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  4425. // rather than treat them as valid lengths.
  4426. template <typename ClientT>
  4427. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  4428. Request req;
  4429. req.method = "POST";
  4430. req.path = "/chunked";
  4431. std::string host_and_port;
  4432. host_and_port += HOST;
  4433. host_and_port += ":";
  4434. host_and_port += std::to_string(PORT);
  4435. req.headers.emplace("Host", host_and_port.c_str());
  4436. req.headers.emplace("Content-Length", "0");
  4437. req.headers.emplace("Transfer-Encoding", "chunked");
  4438. req.body = body;
  4439. auto res = std::make_shared<Response>();
  4440. auto error = Error::Success;
  4441. ASSERT_TRUE(cli.send(req, *res, error));
  4442. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4443. }
  4444. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  4445. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  4446. }
  4447. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  4448. expect_chunked_body_rejected(
  4449. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  4450. }
  4451. TEST_F(ServerTest, GetStreamed2) {
  4452. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4453. ASSERT_TRUE(res);
  4454. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4455. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4456. EXPECT_EQ(true, res->has_header("Content-Range"));
  4457. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4458. EXPECT_EQ(std::string("ab"), res->body);
  4459. }
  4460. TEST_F(ServerTest, GetStreamed) {
  4461. auto res = cli_.Get("/streamed");
  4462. ASSERT_TRUE(res);
  4463. EXPECT_EQ(StatusCode::OK_200, res->status);
  4464. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4465. EXPECT_EQ(std::string("aaabbb"), res->body);
  4466. }
  4467. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  4468. auto res =
  4469. cli_.Get("/streamed-without-length", {make_range_header({{0, -1}})});
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::OK_200, res->status);
  4472. EXPECT_EQ(false, res->has_header("Content-Length"));
  4473. EXPECT_EQ(false, res->has_header("Content-Range"));
  4474. EXPECT_EQ(std::string("abcdefg"), res->body);
  4475. }
  4476. TEST_F(ServerTest, GetStreamedWithRange1) {
  4477. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4478. ASSERT_TRUE(res);
  4479. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4480. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4481. EXPECT_EQ(true, res->has_header("Content-Range"));
  4482. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4483. EXPECT_EQ(std::string("def"), res->body);
  4484. }
  4485. TEST_F(ServerTest, GetStreamedWithRange2) {
  4486. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4487. ASSERT_TRUE(res);
  4488. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4489. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4490. EXPECT_EQ(true, res->has_header("Content-Range"));
  4491. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4492. EXPECT_EQ(std::string("bcdefg"), res->body);
  4493. }
  4494. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4495. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4496. ASSERT_TRUE(res);
  4497. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4498. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4499. EXPECT_EQ(true, res->has_header("Content-Range"));
  4500. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4501. EXPECT_EQ(std::string("efg"), res->body);
  4502. }
  4503. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4504. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4505. ASSERT_TRUE(res);
  4506. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4507. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4508. EXPECT_EQ(false, res->has_header("Content-Range"));
  4509. EXPECT_EQ(0U, res->body.size());
  4510. }
  4511. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4512. auto res = cli_.Get("/streamed-with-range",
  4513. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4514. "92233720368547758079223372036854775807"}});
  4515. ASSERT_TRUE(res);
  4516. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4517. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4518. EXPECT_EQ(false, res->has_header("Content-Range"));
  4519. EXPECT_EQ(0U, res->body.size());
  4520. }
  4521. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4522. auto res = cli_.Get(
  4523. "/with-range",
  4524. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4525. {"Accept-Encoding", ""}});
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4528. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4529. EXPECT_EQ(true, res->has_header("Content-Range"));
  4530. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4531. EXPECT_EQ(std::string("abcdefg"), res->body);
  4532. }
  4533. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4534. auto res = cli_.Get("/with-range", {
  4535. {"Range", "bytes=0-"},
  4536. {"Accept-Encoding", ""},
  4537. });
  4538. ASSERT_TRUE(res);
  4539. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4540. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4541. EXPECT_EQ(true, res->has_header("Content-Range"));
  4542. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4543. EXPECT_EQ(std::string("abcdefg"), res->body);
  4544. }
  4545. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4546. auto res =
  4547. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4548. ASSERT_TRUE(res);
  4549. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4550. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4551. EXPECT_EQ(false, res->has_header("Content-Range"));
  4552. EXPECT_EQ(267U, res->body.size());
  4553. // Check that both range contents are present
  4554. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4555. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4556. // Check that Content-Range headers are present for both ranges
  4557. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4558. std::string::npos);
  4559. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4560. std::string::npos);
  4561. }
  4562. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4563. Ranges ranges;
  4564. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4565. ranges.emplace_back(0, -1);
  4566. }
  4567. auto res =
  4568. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4569. ASSERT_TRUE(res);
  4570. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4571. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4572. EXPECT_EQ(false, res->has_header("Content-Range"));
  4573. EXPECT_EQ(0U, res->body.size());
  4574. }
  4575. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4576. auto res =
  4577. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4580. EXPECT_EQ(5U, res->body.size());
  4581. // Check that overlapping ranges are coalesced into a single range
  4582. EXPECT_EQ("bcdef", res->body);
  4583. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4584. // Should be single range, not multipart
  4585. EXPECT_TRUE(res->has_header("Content-Range"));
  4586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4587. }
  4588. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4589. auto res =
  4590. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4593. EXPECT_EQ(268U, res->body.size());
  4594. // Check that both range contents are present
  4595. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4596. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4597. // Check that Content-Range headers are present for both ranges
  4598. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4599. std::string::npos);
  4600. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4601. std::string::npos);
  4602. }
  4603. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4604. auto res =
  4605. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4608. EXPECT_EQ(269U, res->body.size());
  4609. // Check that both duplicate range contents are present
  4610. size_t first_abc = res->body.find("abc\r\n");
  4611. EXPECT_TRUE(first_abc != std::string::npos);
  4612. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4613. EXPECT_TRUE(second_abc != std::string::npos);
  4614. // Check that Content-Range headers are present for both ranges
  4615. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4616. EXPECT_TRUE(first_range != std::string::npos);
  4617. size_t second_range =
  4618. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4619. EXPECT_TRUE(second_range != std::string::npos);
  4620. }
  4621. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4622. auto res = cli_.Get("/streamed-with-range?error",
  4623. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4624. ASSERT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4626. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4627. EXPECT_EQ(false, res->has_header("Content-Range"));
  4628. EXPECT_EQ(0U, res->body.size());
  4629. }
  4630. TEST_F(ServerTest, GetStreamedEndless) {
  4631. uint64_t offset = 0;
  4632. auto res = cli_.Get("/streamed-cancel",
  4633. [&](const char * /*data*/, uint64_t data_length) {
  4634. if (offset < 100) {
  4635. offset += data_length;
  4636. return true;
  4637. }
  4638. return false;
  4639. });
  4640. ASSERT_TRUE(!res);
  4641. EXPECT_EQ(Error::Canceled, res.error());
  4642. }
  4643. TEST_F(ServerTest, ClientStop) {
  4644. std::atomic_size_t count{4};
  4645. std::vector<std::thread> threads;
  4646. for (auto i = count.load(); i != 0; --i) {
  4647. threads.emplace_back([&]() {
  4648. auto res = cli_.Get("/streamed-cancel",
  4649. [&](const char *, uint64_t) { return true; });
  4650. --count;
  4651. ASSERT_TRUE(!res);
  4652. EXPECT_TRUE(res.error() == Error::Canceled ||
  4653. res.error() == Error::Read || res.error() == Error::Write);
  4654. });
  4655. }
  4656. std::this_thread::sleep_for(std::chrono::seconds(2));
  4657. while (count != 0) {
  4658. cli_.stop();
  4659. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4660. }
  4661. for (auto &t : threads) {
  4662. t.join();
  4663. }
  4664. }
  4665. TEST_F(ServerTest, GetWithRange1) {
  4666. auto res = cli_.Get("/with-range", {
  4667. make_range_header({{3, 5}}),
  4668. {"Accept-Encoding", ""},
  4669. });
  4670. ASSERT_TRUE(res);
  4671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4672. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4673. EXPECT_EQ(true, res->has_header("Content-Range"));
  4674. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4675. EXPECT_EQ(std::string("def"), res->body);
  4676. }
  4677. TEST_F(ServerTest, GetWithRange2) {
  4678. auto res = cli_.Get("/with-range", {
  4679. make_range_header({{1, -1}}),
  4680. {"Accept-Encoding", ""},
  4681. });
  4682. ASSERT_TRUE(res);
  4683. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4684. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4685. EXPECT_EQ(true, res->has_header("Content-Range"));
  4686. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4687. EXPECT_EQ(std::string("bcdefg"), res->body);
  4688. }
  4689. TEST_F(ServerTest, GetWithRange3) {
  4690. auto res = cli_.Get("/with-range", {
  4691. make_range_header({{0, 0}}),
  4692. {"Accept-Encoding", ""},
  4693. });
  4694. ASSERT_TRUE(res);
  4695. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4696. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4697. EXPECT_EQ(true, res->has_header("Content-Range"));
  4698. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4699. EXPECT_EQ(std::string("a"), res->body);
  4700. }
  4701. TEST_F(ServerTest, GetWithRange4) {
  4702. auto res = cli_.Get("/with-range", {
  4703. make_range_header({{-1, 2}}),
  4704. {"Accept-Encoding", ""},
  4705. });
  4706. ASSERT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4708. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4709. EXPECT_EQ(true, res->has_header("Content-Range"));
  4710. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4711. EXPECT_EQ(std::string("fg"), res->body);
  4712. }
  4713. TEST_F(ServerTest, GetWithRange5) {
  4714. auto res = cli_.Get("/with-range", {
  4715. make_range_header({{0, 5}}),
  4716. {"Accept-Encoding", ""},
  4717. });
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4720. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4721. EXPECT_EQ(true, res->has_header("Content-Range"));
  4722. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4723. EXPECT_EQ(std::string("abcdef"), res->body);
  4724. }
  4725. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4726. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4727. ASSERT_TRUE(res);
  4728. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4729. }
  4730. TEST_F(ServerTest, GetWithRangeMultipart) {
  4731. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4732. ASSERT_TRUE(res);
  4733. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4734. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4735. EXPECT_EQ(false, res->has_header("Content-Range"));
  4736. EXPECT_EQ(267U, res->body.size());
  4737. }
  4738. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4739. auto res =
  4740. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4743. }
  4744. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4745. auto res = cli_.Get("/with-range-customized-response",
  4746. {{make_range_header({{1, 2}})}});
  4747. ASSERT_TRUE(res);
  4748. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4749. EXPECT_EQ(true, res->has_header("Content-Length"));
  4750. EXPECT_EQ(false, res->has_header("Content-Range"));
  4751. EXPECT_EQ(JSON_DATA, res->body);
  4752. }
  4753. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4754. auto res = cli_.Get("/with-range-customized-response",
  4755. {{make_range_header({{1, 2}, {4, 5}})}});
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4758. EXPECT_EQ(true, res->has_header("Content-Length"));
  4759. EXPECT_EQ(false, res->has_header("Content-Range"));
  4760. EXPECT_EQ(JSON_DATA, res->body);
  4761. }
  4762. TEST_F(ServerTest, Issue1772) {
  4763. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4764. ASSERT_TRUE(res);
  4765. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4766. }
  4767. TEST_F(ServerTest, Issue609) {
  4768. auto res = cli_.Delete("/issue609");
  4769. ASSERT_TRUE(res);
  4770. EXPECT_EQ(StatusCode::OK_200, res->status);
  4771. EXPECT_EQ(std::string("ok"), res->body);
  4772. }
  4773. TEST_F(ServerTest, GetStreamedChunked) {
  4774. auto res = cli_.Get("/streamed-chunked");
  4775. ASSERT_TRUE(res);
  4776. EXPECT_EQ(StatusCode::OK_200, res->status);
  4777. EXPECT_EQ(std::string("123456789"), res->body);
  4778. }
  4779. TEST_F(ServerTest, GetStreamedChunked2) {
  4780. auto res = cli_.Get("/streamed-chunked2");
  4781. ASSERT_TRUE(res);
  4782. EXPECT_EQ(StatusCode::OK_200, res->status);
  4783. EXPECT_EQ(std::string("123456789"), res->body);
  4784. }
  4785. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4786. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4787. ASSERT_TRUE(res);
  4788. EXPECT_EQ(StatusCode::OK_200, res->status);
  4789. EXPECT_EQ(std::string("123456789"), res->body);
  4790. EXPECT_TRUE(res->has_header("Trailer"));
  4791. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4792. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4793. // Trailers are now stored separately from headers (security fix)
  4794. EXPECT_EQ(2U, res->trailers.size());
  4795. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4796. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4797. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4798. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4799. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4800. // Verify trailers are NOT in headers (security verification)
  4801. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4802. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4803. }
  4804. TEST_F(ServerTest, LargeChunkedPost) {
  4805. Request req;
  4806. req.method = "POST";
  4807. req.path = "/large-chunked";
  4808. std::string host_and_port;
  4809. host_and_port += HOST;
  4810. host_and_port += ":";
  4811. host_and_port += std::to_string(PORT);
  4812. req.headers.emplace("Host", host_and_port.c_str());
  4813. req.headers.emplace("Accept", "*/*");
  4814. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4815. req.headers.emplace("Content-Type", "text/plain");
  4816. req.headers.emplace("Content-Length", "0");
  4817. req.headers.emplace("Transfer-Encoding", "chunked");
  4818. std::string long_string(30 * 1024u, 'a');
  4819. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4820. // Attempt to make a large enough post to exceed OS buffers, to test that
  4821. // the server handles short reads if the full chunk data isn't available.
  4822. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4823. auto res = std::make_shared<Response>();
  4824. auto error = Error::Success;
  4825. auto ret = cli_.send(req, *res, error);
  4826. ASSERT_TRUE(ret);
  4827. EXPECT_EQ(StatusCode::OK_200, res->status);
  4828. }
  4829. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4830. auto res = cli_.Get("/remote_addr");
  4831. ASSERT_TRUE(res);
  4832. EXPECT_EQ(StatusCode::OK_200, res->status);
  4833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4834. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4835. }
  4836. TEST_F(ServerTest, GetMethodLocalAddr) {
  4837. auto res = cli_.Get("/local_addr");
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4841. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4842. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4843. }
  4844. TEST_F(ServerTest, HTTPResponseSplitting) {
  4845. auto res = cli_.Get("/http_response_splitting");
  4846. ASSERT_TRUE(res);
  4847. EXPECT_EQ(StatusCode::OK_200, res->status);
  4848. }
  4849. TEST_F(ServerTest, SlowRequest) {
  4850. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4851. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4852. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4853. }
  4854. #if 0
  4855. TEST_F(ServerTest, SlowPost) {
  4856. char buffer[64 * 1024];
  4857. memset(buffer, 0x42, sizeof(buffer));
  4858. auto res = cli_.Post(
  4859. "/slowpost", 64 * 1024 * 1024,
  4860. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4861. auto ret = sink.write(buffer, sizeof(buffer));
  4862. EXPECT_TRUE(ret);
  4863. return true;
  4864. },
  4865. "text/plain");
  4866. ASSERT_TRUE(res);
  4867. EXPECT_EQ(StatusCode::OK_200, res->status);
  4868. }
  4869. TEST_F(ServerTest, SlowPostFail) {
  4870. char buffer[64 * 1024];
  4871. memset(buffer, 0x42, sizeof(buffer));
  4872. cli_.set_write_timeout(std::chrono::seconds(0));
  4873. auto res = cli_.Post(
  4874. "/slowpost", 64 * 1024 * 1024,
  4875. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4876. sink.write(buffer, sizeof(buffer));
  4877. return true;
  4878. },
  4879. "text/plain");
  4880. ASSERT_TRUE(!res);
  4881. EXPECT_EQ(Error::Write, res.error());
  4882. }
  4883. #endif
  4884. TEST_F(ServerTest, Put) {
  4885. auto res = cli_.Put("/put", "PUT", "text/plain");
  4886. ASSERT_TRUE(res);
  4887. EXPECT_EQ(StatusCode::OK_200, res->status);
  4888. EXPECT_EQ("PUT", res->body);
  4889. }
  4890. TEST_F(ServerTest, PutWithContentProvider) {
  4891. auto res = cli_.Put(
  4892. "/put", 3,
  4893. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4894. sink.os << "PUT";
  4895. return true;
  4896. },
  4897. "text/plain");
  4898. ASSERT_TRUE(res);
  4899. EXPECT_EQ(StatusCode::OK_200, res->status);
  4900. EXPECT_EQ("PUT", res->body);
  4901. }
  4902. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4903. auto res = cli_.Post(
  4904. "/post", 42,
  4905. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4906. return false;
  4907. },
  4908. "text/plain");
  4909. ASSERT_TRUE(!res);
  4910. EXPECT_EQ(Error::Canceled, res.error());
  4911. }
  4912. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4913. auto res = cli_.Put(
  4914. "/put",
  4915. [](size_t /*offset*/, DataSink &sink) {
  4916. sink.os << "PUT";
  4917. sink.done();
  4918. return true;
  4919. },
  4920. "text/plain");
  4921. ASSERT_TRUE(res);
  4922. EXPECT_EQ(StatusCode::OK_200, res->status);
  4923. EXPECT_EQ("PUT", res->body);
  4924. }
  4925. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4926. auto res = cli_.Post(
  4927. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4928. "text/plain");
  4929. ASSERT_TRUE(!res);
  4930. EXPECT_EQ(Error::Canceled, res.error());
  4931. }
  4932. TEST_F(ServerTest, PostLoopBack) {
  4933. std::string body;
  4934. auto res = cli_.Post(
  4935. "/post-loopback", 9,
  4936. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4937. EXPECT_EQ(9u, length);
  4938. sink.write("123", 3);
  4939. sink.write("456", 3);
  4940. sink.write("789", 3);
  4941. return true;
  4942. },
  4943. "text/plain",
  4944. [&body](const char *data, size_t data_length) {
  4945. body.append(data, data_length);
  4946. return true;
  4947. });
  4948. ASSERT_TRUE(res);
  4949. EXPECT_EQ(StatusCode::OK_200, res->status);
  4950. EXPECT_EQ("123456789", body);
  4951. }
  4952. TEST_F(ServerTest, PutLoopBack) {
  4953. std::string body;
  4954. auto res = cli_.Put(
  4955. "/put-loopback", 9,
  4956. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4957. EXPECT_EQ(9u, length);
  4958. sink.write("123", 3);
  4959. sink.write("456", 3);
  4960. sink.write("789", 3);
  4961. return true;
  4962. },
  4963. "text/plain",
  4964. [&body](const char *data, size_t data_length) {
  4965. body.append(data, data_length);
  4966. return true;
  4967. });
  4968. ASSERT_TRUE(res);
  4969. EXPECT_EQ(StatusCode::OK_200, res->status);
  4970. EXPECT_EQ("123456789", body);
  4971. }
  4972. TEST_F(ServerTest, PatchLoopBack) {
  4973. std::string body;
  4974. auto res = cli_.Patch(
  4975. "/patch-loopback", 9,
  4976. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4977. EXPECT_EQ(9u, length);
  4978. sink.write("123", 3);
  4979. sink.write("456", 3);
  4980. sink.write("789", 3);
  4981. return true;
  4982. },
  4983. "text/plain",
  4984. [&body](const char *data, size_t data_length) {
  4985. body.append(data, data_length);
  4986. return true;
  4987. });
  4988. ASSERT_TRUE(res);
  4989. EXPECT_EQ(StatusCode::OK_200, res->status);
  4990. EXPECT_EQ("123456789", body);
  4991. }
  4992. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4993. std::string body;
  4994. auto res = cli_.Post(
  4995. "/post-loopback",
  4996. [](size_t /*offset*/, DataSink &sink) {
  4997. sink.write("123", 3);
  4998. sink.write("456", 3);
  4999. sink.write("789", 3);
  5000. sink.done();
  5001. return true;
  5002. },
  5003. "text/plain",
  5004. [&body](const char *data, size_t data_length) {
  5005. body.append(data, data_length);
  5006. return true;
  5007. });
  5008. ASSERT_TRUE(res);
  5009. EXPECT_EQ(StatusCode::OK_200, res->status);
  5010. EXPECT_EQ("123456789", body);
  5011. }
  5012. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5013. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  5014. cli_.set_compress(true);
  5015. auto res = cli_.Put(
  5016. "/put", 3,
  5017. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5018. sink.os << "PUT";
  5019. return true;
  5020. },
  5021. "text/plain");
  5022. ASSERT_TRUE(res);
  5023. EXPECT_EQ(StatusCode::OK_200, res->status);
  5024. EXPECT_EQ("PUT", res->body);
  5025. }
  5026. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  5027. cli_.set_compress(true);
  5028. auto res = cli_.Post(
  5029. "/post", 42,
  5030. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  5031. return false;
  5032. },
  5033. "text/plain");
  5034. ASSERT_TRUE(!res);
  5035. EXPECT_EQ(Error::Canceled, res.error());
  5036. }
  5037. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  5038. cli_.set_compress(true);
  5039. auto res = cli_.Put(
  5040. "/put",
  5041. [](size_t /*offset*/, DataSink &sink) {
  5042. sink.os << "PUT";
  5043. sink.done();
  5044. return true;
  5045. },
  5046. "text/plain");
  5047. ASSERT_TRUE(res);
  5048. EXPECT_EQ(StatusCode::OK_200, res->status);
  5049. EXPECT_EQ("PUT", res->body);
  5050. }
  5051. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  5052. cli_.set_compress(true);
  5053. auto res = cli_.Post(
  5054. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  5055. "text/plain");
  5056. ASSERT_TRUE(!res);
  5057. EXPECT_EQ(Error::Canceled, res.error());
  5058. }
  5059. TEST_F(ServerTest, PutLargeFileWithGzip) {
  5060. cli_.set_compress(true);
  5061. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5062. ASSERT_TRUE(res);
  5063. EXPECT_EQ(StatusCode::OK_200, res->status);
  5064. EXPECT_EQ(LARGE_DATA, res->body);
  5065. }
  5066. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  5067. #ifdef CPPHTTPLIB_SSL_ENABLED
  5068. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  5069. Client cli(s.c_str());
  5070. cli.enable_server_certificate_verification(false);
  5071. #else
  5072. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  5073. Client cli(s.c_str());
  5074. #endif
  5075. cli.set_compress(true);
  5076. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  5077. ASSERT_TRUE(res);
  5078. EXPECT_EQ(StatusCode::OK_200, res->status);
  5079. EXPECT_EQ(LARGE_DATA, res->body);
  5080. // The compressed size should be less than a 10th of the original. May vary
  5081. // depending on the zlib library.
  5082. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  5083. static_cast<uint64_t>(10 * 1024 * 1024));
  5084. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5085. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5086. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5087. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  5088. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5089. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  5090. #endif
  5091. }
  5092. TEST_F(ServerTest, PutContentWithDeflate) {
  5093. cli_.set_compress(false);
  5094. Headers headers;
  5095. headers.emplace("Content-Encoding", "deflate");
  5096. // PUT in deflate format:
  5097. auto res = cli_.Put("/put", headers,
  5098. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  5099. ASSERT_TRUE(res);
  5100. EXPECT_EQ(StatusCode::OK_200, res->status);
  5101. EXPECT_EQ("PUT", res->body);
  5102. }
  5103. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  5104. Headers headers;
  5105. headers.emplace("Accept-Encoding", "gzip, deflate");
  5106. auto res = cli_.Get("/streamed-chunked", headers);
  5107. ASSERT_TRUE(res);
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. EXPECT_EQ(std::string("123456789"), res->body);
  5110. }
  5111. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  5112. Headers headers;
  5113. headers.emplace("Accept-Encoding", "gzip, deflate");
  5114. auto res = cli_.Get("/streamed-chunked2", headers);
  5115. ASSERT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. EXPECT_EQ(std::string("123456789"), res->body);
  5118. }
  5119. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  5120. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  5121. ASSERT_TRUE(res);
  5122. EXPECT_EQ(StatusCode::OK_200, res->status);
  5123. }
  5124. TEST(GzipDecompressor, ChunkedDecompression) {
  5125. std::string data;
  5126. for (size_t i = 0; i < 32 * 1024; ++i) {
  5127. data.push_back(static_cast<char>('a' + i % 26));
  5128. }
  5129. std::string compressed_data;
  5130. {
  5131. httplib::detail::gzip_compressor compressor;
  5132. bool result = compressor.compress(
  5133. data.data(), data.size(),
  5134. /*last=*/true,
  5135. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5136. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5137. compressed_data_size);
  5138. return true;
  5139. });
  5140. ASSERT_TRUE(result);
  5141. }
  5142. std::string decompressed_data;
  5143. {
  5144. httplib::detail::gzip_decompressor decompressor;
  5145. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5146. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5147. size_t chunk_size = 130;
  5148. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5149. chunk_begin += chunk_size) {
  5150. size_t current_chunk_size =
  5151. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5152. bool result = decompressor.decompress(
  5153. compressed_data.data() + chunk_begin, current_chunk_size,
  5154. [&](const char *decompressed_data_chunk,
  5155. size_t decompressed_data_chunk_size) {
  5156. decompressed_data.insert(decompressed_data.size(),
  5157. decompressed_data_chunk,
  5158. decompressed_data_chunk_size);
  5159. return true;
  5160. });
  5161. ASSERT_TRUE(result);
  5162. }
  5163. }
  5164. ASSERT_EQ(data, decompressed_data);
  5165. }
  5166. TEST(GzipDecompressor, DeflateDecompression) {
  5167. std::string original_text = "Raw deflate without gzip";
  5168. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5169. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5170. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5171. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5172. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5173. std::string decompressed_data;
  5174. {
  5175. httplib::detail::gzip_decompressor decompressor;
  5176. bool result = decompressor.decompress(
  5177. compressed_data.data(), compressed_data.size(),
  5178. [&](const char *decompressed_data_chunk,
  5179. size_t decompressed_data_chunk_size) {
  5180. decompressed_data.insert(decompressed_data.size(),
  5181. decompressed_data_chunk,
  5182. decompressed_data_chunk_size);
  5183. return true;
  5184. });
  5185. ASSERT_TRUE(result);
  5186. }
  5187. ASSERT_EQ(original_text, decompressed_data);
  5188. }
  5189. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5190. std::string original_text = "Raw deflate without gzip";
  5191. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5192. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5193. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5194. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5195. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5196. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5197. std::string decompressed_data;
  5198. {
  5199. httplib::detail::gzip_decompressor decompressor;
  5200. bool result = decompressor.decompress(
  5201. compressed_data.data(), compressed_data.size(),
  5202. [&](const char *decompressed_data_chunk,
  5203. size_t decompressed_data_chunk_size) {
  5204. decompressed_data.insert(decompressed_data.size(),
  5205. decompressed_data_chunk,
  5206. decompressed_data_chunk_size);
  5207. return true;
  5208. });
  5209. ASSERT_TRUE(result);
  5210. }
  5211. ASSERT_EQ(original_text, decompressed_data);
  5212. }
  5213. #endif
  5214. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5215. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5216. Headers headers;
  5217. headers.emplace("Accept-Encoding", "br");
  5218. auto res = cli_.Get("/streamed-chunked", headers);
  5219. ASSERT_TRUE(res);
  5220. EXPECT_EQ(StatusCode::OK_200, res->status);
  5221. EXPECT_EQ(std::string("123456789"), res->body);
  5222. }
  5223. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5224. Headers headers;
  5225. headers.emplace("Accept-Encoding", "br");
  5226. auto res = cli_.Get("/streamed-chunked2", headers);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(StatusCode::OK_200, res->status);
  5229. EXPECT_EQ(std::string("123456789"), res->body);
  5230. }
  5231. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5232. cli_.set_compress(true);
  5233. auto res = cli_.Put(
  5234. "/put", 3,
  5235. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5236. sink.os << "PUT";
  5237. return true;
  5238. },
  5239. "text/plain");
  5240. ASSERT_TRUE(res);
  5241. EXPECT_EQ(StatusCode::OK_200, res->status);
  5242. EXPECT_EQ("PUT", res->body);
  5243. }
  5244. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5245. cli_.set_compress(true);
  5246. auto res = cli_.Put(
  5247. "/put",
  5248. [](size_t /*offset*/, DataSink &sink) {
  5249. sink.os << "PUT";
  5250. sink.done();
  5251. return true;
  5252. },
  5253. "text/plain");
  5254. ASSERT_TRUE(res);
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("PUT", res->body);
  5257. }
  5258. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5259. cli_.set_compress(true);
  5260. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5261. ASSERT_TRUE(res);
  5262. EXPECT_EQ(StatusCode::OK_200, res->status);
  5263. EXPECT_EQ(LARGE_DATA, res->body);
  5264. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5265. }
  5266. #endif
  5267. TEST_F(ServerTest, Patch) {
  5268. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5269. ASSERT_TRUE(res);
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("PATCH", res->body);
  5272. }
  5273. TEST_F(ServerTest, Delete) {
  5274. auto res = cli_.Delete("/delete");
  5275. ASSERT_TRUE(res);
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("DELETE", res->body);
  5278. }
  5279. TEST_F(ServerTest, DeleteContentReceiver) {
  5280. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5281. ASSERT_TRUE(res);
  5282. EXPECT_EQ(StatusCode::OK_200, res->status);
  5283. EXPECT_EQ("content", res->body);
  5284. }
  5285. TEST_F(ServerTest, Options) {
  5286. auto res = cli_.Options("*");
  5287. ASSERT_TRUE(res);
  5288. EXPECT_EQ(StatusCode::OK_200, res->status);
  5289. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5290. EXPECT_TRUE(res->body.empty());
  5291. }
  5292. TEST_F(ServerTest, URL) {
  5293. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5294. ASSERT_TRUE(res);
  5295. EXPECT_EQ(StatusCode::OK_200, res->status);
  5296. }
  5297. TEST_F(ServerTest, ArrayParam) {
  5298. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5299. ASSERT_TRUE(res);
  5300. EXPECT_EQ(StatusCode::OK_200, res->status);
  5301. }
  5302. TEST_F(ServerTest, ArrayParamValues) {
  5303. auto res =
  5304. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5305. ASSERT_TRUE(res);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. }
  5308. TEST_F(ServerTest, NoMultipleHeaders) {
  5309. Headers headers = {{"Content-Length", "5"}};
  5310. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5311. "text/plain");
  5312. ASSERT_TRUE(res);
  5313. EXPECT_EQ(StatusCode::OK_200, res->status);
  5314. }
  5315. TEST_F(ServerTest, PostContentReceiver) {
  5316. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5317. ASSERT_TRUE(res);
  5318. ASSERT_EQ(StatusCode::OK_200, res->status);
  5319. ASSERT_EQ("content", res->body);
  5320. }
  5321. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5322. UploadFormDataItems items = {
  5323. {"text1", "text default", "", ""},
  5324. {"text2", "aωb", "", ""},
  5325. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5326. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5327. {"file3", "", "", "application/octet-stream"},
  5328. };
  5329. auto res = cli_.Post("/content_receiver", items);
  5330. ASSERT_TRUE(res);
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. }
  5333. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5334. UploadFormDataItems items = {
  5335. {"text1", "text default", "", ""},
  5336. {"text2", "aωb", "", ""},
  5337. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5338. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5339. {"file3", "", "", "application/octet-stream"},
  5340. };
  5341. auto boundary = std::string("+++++");
  5342. std::string body;
  5343. for (const auto &item : items) {
  5344. body += "--" + boundary + "\r\n";
  5345. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5346. if (!item.filename.empty()) {
  5347. body += "; filename=\"" + item.filename + "\"";
  5348. }
  5349. body += "\r\n";
  5350. if (!item.content_type.empty()) {
  5351. body += "Content-Type: " + item.content_type + "\r\n";
  5352. }
  5353. body += "\r\n";
  5354. body += item.content + "\r\n";
  5355. }
  5356. body += "--" + boundary + "--\r\n";
  5357. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5358. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5359. ASSERT_TRUE(res);
  5360. EXPECT_EQ(StatusCode::OK_200, res->status);
  5361. }
  5362. TEST_F(ServerTest, PostContentReceiverGzip) {
  5363. cli_.set_compress(true);
  5364. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5365. ASSERT_TRUE(res);
  5366. ASSERT_EQ(StatusCode::OK_200, res->status);
  5367. ASSERT_EQ("content", res->body);
  5368. }
  5369. TEST_F(ServerTest, PutContentReceiver) {
  5370. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5371. ASSERT_TRUE(res);
  5372. ASSERT_EQ(StatusCode::OK_200, res->status);
  5373. ASSERT_EQ("content", res->body);
  5374. }
  5375. TEST_F(ServerTest, PatchContentReceiver) {
  5376. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5377. ASSERT_TRUE(res);
  5378. ASSERT_EQ(StatusCode::OK_200, res->status);
  5379. ASSERT_EQ("content", res->body);
  5380. }
  5381. template <typename ClientType>
  5382. void TestWithHeadersAndContentReceiver(
  5383. ClientType &cli,
  5384. std::function<Result(ClientType &, const std::string &, const Headers &,
  5385. const std::string &, const std::string &,
  5386. ContentReceiver, DownloadProgress)>
  5387. request_func) {
  5388. Headers headers;
  5389. headers.emplace("X-Custom-Header", "test-value");
  5390. std::string received_body;
  5391. auto res = request_func(
  5392. cli, "/content_receiver", headers, "content", "application/json",
  5393. [&](const char *data, size_t data_length) {
  5394. received_body.append(data, data_length);
  5395. return true;
  5396. },
  5397. nullptr);
  5398. ASSERT_TRUE(res);
  5399. EXPECT_EQ(StatusCode::OK_200, res->status);
  5400. EXPECT_EQ("content", received_body);
  5401. }
  5402. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5403. #ifdef CPPHTTPLIB_SSL_ENABLED
  5404. using ClientT = SSLClient;
  5405. #else
  5406. using ClientT = Client;
  5407. #endif
  5408. TestWithHeadersAndContentReceiver<ClientT>(
  5409. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5410. const std::string &body, const std::string &content_type,
  5411. ContentReceiver receiver, DownloadProgress progress) {
  5412. return cli.Post(path, headers, body, content_type, receiver, progress);
  5413. });
  5414. }
  5415. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5416. #ifdef CPPHTTPLIB_SSL_ENABLED
  5417. using ClientT = SSLClient;
  5418. #else
  5419. using ClientT = Client;
  5420. #endif
  5421. TestWithHeadersAndContentReceiver<ClientT>(
  5422. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5423. const std::string &body, const std::string &content_type,
  5424. ContentReceiver receiver, DownloadProgress progress) {
  5425. return cli.Put(path, headers, body, content_type, receiver, progress);
  5426. });
  5427. }
  5428. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5429. #ifdef CPPHTTPLIB_SSL_ENABLED
  5430. using ClientT = SSLClient;
  5431. #else
  5432. using ClientT = Client;
  5433. #endif
  5434. TestWithHeadersAndContentReceiver<ClientT>(
  5435. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5436. const std::string &body, const std::string &content_type,
  5437. ContentReceiver receiver, DownloadProgress progress) {
  5438. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5439. });
  5440. }
  5441. template <typename ClientType>
  5442. void TestWithHeadersAndContentReceiverWithProgress(
  5443. ClientType &cli,
  5444. std::function<Result(ClientType &, const std::string &, const Headers &,
  5445. const std::string &, const std::string &,
  5446. ContentReceiver, DownloadProgress)>
  5447. request_func) {
  5448. Headers headers;
  5449. headers.emplace("X-Test-Header", "progress-test");
  5450. std::string received_body;
  5451. auto progress_called = false;
  5452. auto res = request_func(
  5453. cli, "/content_receiver", headers, "content", "text/plain",
  5454. [&](const char *data, size_t data_length) {
  5455. received_body.append(data, data_length);
  5456. return true;
  5457. },
  5458. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5459. progress_called = true;
  5460. return true;
  5461. });
  5462. ASSERT_TRUE(res);
  5463. EXPECT_EQ(StatusCode::OK_200, res->status);
  5464. EXPECT_EQ("content", received_body);
  5465. EXPECT_TRUE(progress_called);
  5466. }
  5467. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5468. #ifdef CPPHTTPLIB_SSL_ENABLED
  5469. using ClientT = SSLClient;
  5470. #else
  5471. using ClientT = Client;
  5472. #endif
  5473. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5474. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5475. const std::string &body, const std::string &content_type,
  5476. ContentReceiver receiver, DownloadProgress progress) {
  5477. return cli.Post(path, headers, body, content_type, receiver, progress);
  5478. });
  5479. }
  5480. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5481. #ifdef CPPHTTPLIB_SSL_ENABLED
  5482. using ClientT = SSLClient;
  5483. #else
  5484. using ClientT = Client;
  5485. #endif
  5486. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5487. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5488. const std::string &body, const std::string &content_type,
  5489. ContentReceiver receiver, DownloadProgress progress) {
  5490. return cli.Put(path, headers, body, content_type, receiver, progress);
  5491. });
  5492. }
  5493. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5494. #ifdef CPPHTTPLIB_SSL_ENABLED
  5495. using ClientT = SSLClient;
  5496. #else
  5497. using ClientT = Client;
  5498. #endif
  5499. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5500. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5501. const std::string &body, const std::string &content_type,
  5502. ContentReceiver receiver, DownloadProgress progress) {
  5503. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5504. });
  5505. }
  5506. template <typename ClientType>
  5507. void TestWithHeadersAndContentReceiverError(
  5508. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5509. const Headers &, const std::string &,
  5510. const std::string &, ContentReceiver)>
  5511. request_func) {
  5512. Headers headers;
  5513. headers.emplace("X-Error-Test", "true");
  5514. std::string received_body;
  5515. auto receiver_failed = false;
  5516. auto res =
  5517. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5518. [&](const char *data, size_t data_length) {
  5519. received_body.append(data, data_length);
  5520. receiver_failed = true;
  5521. return false;
  5522. });
  5523. ASSERT_FALSE(res);
  5524. EXPECT_TRUE(receiver_failed);
  5525. }
  5526. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5527. #ifdef CPPHTTPLIB_SSL_ENABLED
  5528. using ClientT = SSLClient;
  5529. #else
  5530. using ClientT = Client;
  5531. #endif
  5532. TestWithHeadersAndContentReceiverError<ClientT>(
  5533. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5534. const std::string &body, const std::string &content_type,
  5535. ContentReceiver receiver) {
  5536. return cli.Post(path, headers, body, content_type, receiver);
  5537. });
  5538. }
  5539. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5540. #ifdef CPPHTTPLIB_SSL_ENABLED
  5541. using ClientT = SSLClient;
  5542. #else
  5543. using ClientT = Client;
  5544. #endif
  5545. TestWithHeadersAndContentReceiverError<ClientT>(
  5546. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5547. const std::string &body, const std::string &content_type,
  5548. ContentReceiver receiver) {
  5549. return cli.Put(path, headers, body, content_type, receiver);
  5550. });
  5551. }
  5552. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5553. #ifdef CPPHTTPLIB_SSL_ENABLED
  5554. using ClientT = SSLClient;
  5555. #else
  5556. using ClientT = Client;
  5557. #endif
  5558. TestWithHeadersAndContentReceiverError<ClientT>(
  5559. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5560. const std::string &body, const std::string &content_type,
  5561. ContentReceiver receiver) {
  5562. return cli.Patch(path, headers, body, content_type, receiver);
  5563. });
  5564. }
  5565. TEST_F(ServerTest, PostQueryStringAndBody) {
  5566. auto res =
  5567. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5568. ASSERT_TRUE(res);
  5569. ASSERT_EQ(StatusCode::OK_200, res->status);
  5570. }
  5571. TEST_F(ServerTest, HTTP2Magic) {
  5572. Request req;
  5573. req.method = "PRI";
  5574. req.path = "*";
  5575. req.body = "SM";
  5576. auto res = std::make_shared<Response>();
  5577. auto error = Error::Success;
  5578. auto ret = cli_.send(req, *res, error);
  5579. ASSERT_TRUE(ret);
  5580. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5581. }
  5582. TEST_F(ServerTest, KeepAlive) {
  5583. auto res = cli_.Get("/hi");
  5584. ASSERT_TRUE(res);
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5587. EXPECT_EQ("Hello World!", res->body);
  5588. res = cli_.Get("/hi");
  5589. ASSERT_TRUE(res);
  5590. EXPECT_EQ(StatusCode::OK_200, res->status);
  5591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5592. EXPECT_EQ("Hello World!", res->body);
  5593. res = cli_.Get("/hi");
  5594. ASSERT_TRUE(res);
  5595. EXPECT_EQ(StatusCode::OK_200, res->status);
  5596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5597. EXPECT_EQ("Hello World!", res->body);
  5598. res = cli_.Get("/not-exist");
  5599. ASSERT_TRUE(res);
  5600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5601. res = cli_.Post("/empty", "", "text/plain");
  5602. ASSERT_TRUE(res);
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5605. EXPECT_EQ("empty", res->body);
  5606. EXPECT_EQ("close", res->get_header_value("Connection"));
  5607. res = cli_.Post(
  5608. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5609. "text/plain");
  5610. ASSERT_TRUE(res);
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5613. EXPECT_EQ("empty", res->body);
  5614. cli_.set_keep_alive(false);
  5615. res = cli_.Get("/last-request");
  5616. ASSERT_TRUE(res);
  5617. EXPECT_EQ(StatusCode::OK_200, res->status);
  5618. EXPECT_EQ("close", res->get_header_value("Connection"));
  5619. }
  5620. TEST_F(ServerTest, TooManyRedirect) {
  5621. cli_.set_follow_location(true);
  5622. auto res = cli_.Get("/redirect/0");
  5623. ASSERT_TRUE(!res);
  5624. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5625. }
  5626. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5627. Request req;
  5628. req.method = "FOOBAR";
  5629. req.path = "/hi";
  5630. cli_.set_keep_alive(true);
  5631. auto res = cli_.send(req);
  5632. ASSERT_TRUE(res);
  5633. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5634. EXPECT_EQ("close", res->get_header_value("Connection"));
  5635. EXPECT_FALSE(cli_.is_socket_open());
  5636. }
  5637. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5638. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5639. TEST_F(ServerTest, Gzip) {
  5640. Headers headers;
  5641. headers.emplace("Accept-Encoding", "gzip, deflate");
  5642. auto res = cli_.Get("/compress", headers);
  5643. ASSERT_TRUE(res);
  5644. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5645. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5646. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5647. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5648. "7890123456789012345678901234567890",
  5649. res->body);
  5650. EXPECT_EQ(StatusCode::OK_200, res->status);
  5651. }
  5652. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5653. Headers headers;
  5654. headers.emplace("Accept-Encoding", "gzip, deflate");
  5655. auto res = cli_.Get("/compress-with-charset", headers);
  5656. ASSERT_TRUE(res);
  5657. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5658. EXPECT_EQ("application/json; charset=utf-8",
  5659. res->get_header_value("Content-Type"));
  5660. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5661. "7890123456789012345678901234567890",
  5662. res->body);
  5663. EXPECT_EQ(StatusCode::OK_200, res->status);
  5664. }
  5665. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5666. Headers headers;
  5667. headers.emplace("Accept-Encoding", "");
  5668. auto res = cli_.Get("/compress", headers);
  5669. ASSERT_TRUE(res);
  5670. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5671. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5672. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5673. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5674. "7890123456789012345678901234567890",
  5675. res->body);
  5676. EXPECT_EQ(StatusCode::OK_200, res->status);
  5677. }
  5678. TEST_F(ServerTest, GzipWithContentReceiver) {
  5679. Headers headers;
  5680. headers.emplace("Accept-Encoding", "gzip, deflate");
  5681. std::string body;
  5682. auto res = cli_.Get("/compress", headers,
  5683. [&](const char *data, uint64_t data_length) {
  5684. EXPECT_EQ(100U, data_length);
  5685. body.append(data, data_length);
  5686. return true;
  5687. });
  5688. ASSERT_TRUE(res);
  5689. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5690. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5691. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5692. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5693. "7890123456789012345678901234567890",
  5694. body);
  5695. EXPECT_EQ(StatusCode::OK_200, res->status);
  5696. }
  5697. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5698. Headers headers;
  5699. headers.emplace("Accept-Encoding", "gzip, deflate");
  5700. cli_.set_decompress(false);
  5701. auto res = cli_.Get("/compress", headers);
  5702. ASSERT_TRUE(res);
  5703. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5705. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5706. EXPECT_EQ(33U, res->body.size());
  5707. EXPECT_EQ(StatusCode::OK_200, res->status);
  5708. }
  5709. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5710. Headers headers;
  5711. headers.emplace("Accept-Encoding", "");
  5712. std::string body;
  5713. auto res = cli_.Get("/compress", headers,
  5714. [&](const char *data, uint64_t data_length) {
  5715. EXPECT_EQ(100U, data_length);
  5716. body.append(data, data_length);
  5717. return true;
  5718. });
  5719. ASSERT_TRUE(res);
  5720. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5721. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5722. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5723. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5724. "7890123456789012345678901234567890",
  5725. body);
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. }
  5728. TEST_F(ServerTest, NoGzip) {
  5729. Headers headers;
  5730. headers.emplace("Accept-Encoding", "gzip, deflate");
  5731. auto res = cli_.Get("/nocompress", headers);
  5732. ASSERT_TRUE(res);
  5733. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5734. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5735. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5736. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5737. "7890123456789012345678901234567890",
  5738. res->body);
  5739. EXPECT_EQ(StatusCode::OK_200, res->status);
  5740. }
  5741. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5742. Headers headers;
  5743. headers.emplace("Accept-Encoding", "gzip, deflate");
  5744. std::string body;
  5745. auto res = cli_.Get("/nocompress", headers,
  5746. [&](const char *data, uint64_t data_length) {
  5747. EXPECT_EQ(100U, data_length);
  5748. body.append(data, data_length);
  5749. return true;
  5750. });
  5751. ASSERT_TRUE(res);
  5752. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5753. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5754. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5755. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5756. "7890123456789012345678901234567890",
  5757. body);
  5758. EXPECT_EQ(StatusCode::OK_200, res->status);
  5759. }
  5760. TEST_F(ServerTest, MultipartFormDataGzip) {
  5761. UploadFormDataItems items = {
  5762. {"key1", "test", "", ""},
  5763. {"key2", "--abcdefg123", "", ""},
  5764. };
  5765. cli_.set_compress(true);
  5766. auto res = cli_.Post("/compress-multipart", items);
  5767. ASSERT_TRUE(res);
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. }
  5770. #endif
  5771. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5772. TEST_F(ServerTest, Brotli) {
  5773. Headers headers;
  5774. headers.emplace("Accept-Encoding", "br");
  5775. auto res = cli_.Get("/compress", headers);
  5776. ASSERT_TRUE(res);
  5777. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5778. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5779. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5780. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5781. "7890123456789012345678901234567890",
  5782. res->body);
  5783. EXPECT_EQ(StatusCode::OK_200, res->status);
  5784. }
  5785. #endif
  5786. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5787. TEST_F(ServerTest, Zstd) {
  5788. Headers headers;
  5789. headers.emplace("Accept-Encoding", "zstd");
  5790. auto res = cli_.Get("/compress", headers);
  5791. ASSERT_TRUE(res);
  5792. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5793. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5794. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5795. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5796. "7890123456789012345678901234567890",
  5797. res->body);
  5798. EXPECT_EQ(StatusCode::OK_200, res->status);
  5799. }
  5800. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5801. Headers headers;
  5802. headers.emplace("Accept-Encoding", "");
  5803. auto res = cli_.Get("/compress", headers);
  5804. ASSERT_TRUE(res);
  5805. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5807. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5808. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5809. "7890123456789012345678901234567890",
  5810. res->body);
  5811. EXPECT_EQ(StatusCode::OK_200, res->status);
  5812. }
  5813. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5814. Headers headers;
  5815. headers.emplace("Accept-Encoding", "zstd");
  5816. std::string body;
  5817. auto res = cli_.Get("/compress", headers,
  5818. [&](const char *data, uint64_t data_length) {
  5819. EXPECT_EQ(100U, data_length);
  5820. body.append(data, data_length);
  5821. return true;
  5822. });
  5823. ASSERT_TRUE(res);
  5824. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5826. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5827. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5828. "7890123456789012345678901234567890",
  5829. body);
  5830. EXPECT_EQ(StatusCode::OK_200, res->status);
  5831. }
  5832. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5833. Headers headers;
  5834. headers.emplace("Accept-Encoding", "zstd");
  5835. cli_.set_decompress(false);
  5836. auto res = cli_.Get("/compress", headers);
  5837. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5838. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5839. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5840. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5841. ASSERT_TRUE(res);
  5842. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5843. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5844. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5845. EXPECT_EQ(StatusCode::OK_200, res->status);
  5846. ASSERT_EQ(26U, res->body.size());
  5847. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5848. 0);
  5849. }
  5850. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5851. Headers headers;
  5852. headers.emplace("Accept-Encoding", "");
  5853. std::string body;
  5854. auto res = cli_.Get("/compress", headers,
  5855. [&](const char *data, uint64_t data_length) {
  5856. EXPECT_EQ(100U, data_length);
  5857. body.append(data, data_length);
  5858. return true;
  5859. });
  5860. ASSERT_TRUE(res);
  5861. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5863. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5864. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5865. "7890123456789012345678901234567890",
  5866. body);
  5867. EXPECT_EQ(StatusCode::OK_200, res->status);
  5868. }
  5869. TEST_F(ServerTest, NoZstd) {
  5870. Headers headers;
  5871. headers.emplace("Accept-Encoding", "zstd");
  5872. auto res = cli_.Get("/nocompress", headers);
  5873. ASSERT_TRUE(res);
  5874. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5875. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5876. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5877. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5878. "7890123456789012345678901234567890",
  5879. res->body);
  5880. EXPECT_EQ(StatusCode::OK_200, res->status);
  5881. }
  5882. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5883. Headers headers;
  5884. headers.emplace("Accept-Encoding", "zstd");
  5885. std::string body;
  5886. auto res = cli_.Get("/nocompress", headers,
  5887. [&](const char *data, uint64_t data_length) {
  5888. EXPECT_EQ(100U, data_length);
  5889. body.append(data, data_length);
  5890. return true;
  5891. });
  5892. ASSERT_TRUE(res);
  5893. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5894. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5895. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5896. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5897. "7890123456789012345678901234567890",
  5898. body);
  5899. EXPECT_EQ(StatusCode::OK_200, res->status);
  5900. }
  5901. // TODO: How to enable zstd ??
  5902. TEST_F(ServerTest, MultipartFormDataZstd) {
  5903. UploadFormDataItems items = {
  5904. {"key1", "test", "", ""},
  5905. {"key2", "--abcdefg123", "", ""},
  5906. };
  5907. Headers headers;
  5908. headers.emplace("Accept-Encoding", "zstd");
  5909. cli_.set_compress(true);
  5910. auto res = cli_.Post("/compress-multipart", headers, items);
  5911. ASSERT_TRUE(res);
  5912. EXPECT_EQ(StatusCode::OK_200, res->status);
  5913. }
  5914. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5915. Headers headers;
  5916. headers.emplace("Accept-Encoding", "zstd");
  5917. cli_.set_compress(true);
  5918. auto res = cli_.Put(
  5919. "/put", headers, 3,
  5920. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5921. sink.os << "PUT";
  5922. return true;
  5923. },
  5924. "text/plain");
  5925. ASSERT_TRUE(res);
  5926. EXPECT_EQ(StatusCode::OK_200, res->status);
  5927. EXPECT_EQ("PUT", res->body);
  5928. }
  5929. // Pre-compression logging tests
  5930. TEST_F(ServerTest, PreCompressionLogging) {
  5931. // Test data for compression (matches the actual /compress endpoint content)
  5932. const std::string test_content =
  5933. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5934. "3456789012345678901234567890";
  5935. // Variables to capture logging data
  5936. std::string pre_compression_body;
  5937. std::string pre_compression_content_type;
  5938. std::string pre_compression_content_encoding;
  5939. std::string post_compression_body;
  5940. std::string post_compression_content_type;
  5941. std::string post_compression_content_encoding;
  5942. // Set up pre-compression logger
  5943. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5944. const Response &res) {
  5945. pre_compression_body = res.body;
  5946. pre_compression_content_type = res.get_header_value("Content-Type");
  5947. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5948. });
  5949. // Set up post-compression logger
  5950. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5951. post_compression_body = res.body;
  5952. post_compression_content_type = res.get_header_value("Content-Type");
  5953. post_compression_content_encoding =
  5954. res.get_header_value("Content-Encoding");
  5955. });
  5956. // Test with gzip compression
  5957. Headers headers;
  5958. headers.emplace("Accept-Encoding", "gzip");
  5959. auto res = cli_.Get("/compress", headers);
  5960. // Verify response was compressed
  5961. ASSERT_TRUE(res);
  5962. EXPECT_EQ(StatusCode::OK_200, res->status);
  5963. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5964. // Verify pre-compression logger captured uncompressed content
  5965. EXPECT_EQ(test_content, pre_compression_body);
  5966. EXPECT_EQ("text/plain", pre_compression_content_type);
  5967. EXPECT_TRUE(pre_compression_content_encoding
  5968. .empty()); // No encoding header before compression
  5969. // Verify post-compression logger captured compressed content
  5970. EXPECT_NE(test_content,
  5971. post_compression_body); // Should be different after compression
  5972. EXPECT_EQ("text/plain", post_compression_content_type);
  5973. EXPECT_EQ("gzip", post_compression_content_encoding);
  5974. // Verify compressed content is smaller
  5975. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5976. }
  5977. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5978. const std::string test_content =
  5979. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5980. "3456789012345678901234567890";
  5981. std::string pre_compression_body;
  5982. std::string post_compression_body;
  5983. svr_.set_pre_compression_logger(
  5984. [&](const Request & /*req*/, const Response &res) {
  5985. pre_compression_body = res.body;
  5986. });
  5987. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5988. post_compression_body = res.body;
  5989. });
  5990. Headers headers;
  5991. headers.emplace("Accept-Encoding", "br");
  5992. auto res = cli_.Get("/compress", headers);
  5993. ASSERT_TRUE(res);
  5994. EXPECT_EQ(StatusCode::OK_200, res->status);
  5995. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5996. // Verify pre-compression content is uncompressed
  5997. EXPECT_EQ(test_content, pre_compression_body);
  5998. // Verify post-compression content is compressed
  5999. EXPECT_NE(test_content, post_compression_body);
  6000. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  6001. }
  6002. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  6003. const std::string test_content =
  6004. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6005. "3456789012345678901234567890";
  6006. std::string pre_compression_body;
  6007. std::string post_compression_body;
  6008. svr_.set_pre_compression_logger(
  6009. [&](const Request & /*req*/, const Response &res) {
  6010. pre_compression_body = res.body;
  6011. });
  6012. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  6013. post_compression_body = res.body;
  6014. });
  6015. // Request without compression (use /nocompress endpoint)
  6016. Headers headers;
  6017. auto res = cli_.Get("/nocompress", headers);
  6018. ASSERT_TRUE(res);
  6019. EXPECT_EQ(StatusCode::OK_200, res->status);
  6020. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  6021. // Pre-compression logger should not be called when no compression is applied
  6022. EXPECT_TRUE(
  6023. pre_compression_body.empty()); // Pre-compression logger not called
  6024. EXPECT_EQ(
  6025. test_content,
  6026. post_compression_body); // Post-compression logger captures final content
  6027. }
  6028. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  6029. const std::string test_content =
  6030. "123456789012345678901234567890123456789012345678901234567890123456789012"
  6031. "3456789012345678901234567890";
  6032. std::string pre_compression_body;
  6033. bool pre_logger_called = false;
  6034. // Set only pre-compression logger
  6035. svr_.set_pre_compression_logger(
  6036. [&](const Request & /*req*/, const Response &res) {
  6037. pre_compression_body = res.body;
  6038. pre_logger_called = true;
  6039. });
  6040. Headers headers;
  6041. headers.emplace("Accept-Encoding", "gzip");
  6042. auto res = cli_.Get("/compress", headers);
  6043. ASSERT_TRUE(res);
  6044. EXPECT_EQ(StatusCode::OK_200, res->status);
  6045. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  6046. // Verify pre-compression logger was called
  6047. EXPECT_TRUE(pre_logger_called);
  6048. EXPECT_EQ(test_content, pre_compression_body);
  6049. }
  6050. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  6051. {
  6052. // Test with Expect: 100-continue header - success case
  6053. // Server returns 100 Continue, client sends body, server returns 200 OK
  6054. Request req;
  6055. req.method = "POST";
  6056. req.path = "/post-large";
  6057. req.set_header("Expect", "100-continue");
  6058. req.body = LARGE_DATA;
  6059. Response res;
  6060. auto error = Error::Success;
  6061. cli_.set_keep_alive(true);
  6062. auto ret = cli_.send(req, res, error);
  6063. EXPECT_TRUE(ret);
  6064. EXPECT_EQ(StatusCode::OK_200, res.status);
  6065. EXPECT_EQ(LARGE_DATA, res.body);
  6066. }
  6067. {
  6068. // Test with Expect: 100-continue header - error case
  6069. // Client should not send the body when server returns an error
  6070. Request req;
  6071. req.method = "POST";
  6072. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  6073. req.set_header("Expect", "100-continue");
  6074. req.body = LARGE_DATA;
  6075. Response res;
  6076. auto error = Error::Success;
  6077. auto start = std::chrono::high_resolution_clock::now();
  6078. cli_.set_keep_alive(true);
  6079. auto ret = cli_.send(req, res, error);
  6080. auto end = std::chrono::high_resolution_clock::now();
  6081. auto elapsed =
  6082. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6083. .count();
  6084. // With Expect: 100-continue, request completes successfully but with error
  6085. EXPECT_TRUE(ret);
  6086. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  6087. EXPECT_EQ("close", res.get_header_value("Connection"));
  6088. EXPECT_FALSE(cli_.is_socket_open());
  6089. EXPECT_LE(elapsed, 2000);
  6090. }
  6091. {
  6092. // Send an extra GET request to ensure error recovery without hanging
  6093. Request req;
  6094. req.method = "GET";
  6095. req.path = "/hi";
  6096. auto start = std::chrono::high_resolution_clock::now();
  6097. auto res = cli_.send(req);
  6098. auto end = std::chrono::high_resolution_clock::now();
  6099. auto elapsed =
  6100. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6101. .count();
  6102. ASSERT_TRUE(res);
  6103. EXPECT_EQ(StatusCode::OK_200, res->status);
  6104. EXPECT_EQ("Hello World!", res->body);
  6105. EXPECT_LE(elapsed, 500);
  6106. }
  6107. }
  6108. TEST(ZstdDecompressor, ChunkedDecompression) {
  6109. std::string data;
  6110. for (size_t i = 0; i < 32 * 1024; ++i) {
  6111. data.push_back(static_cast<char>('a' + i % 26));
  6112. }
  6113. std::string compressed_data;
  6114. {
  6115. httplib::detail::zstd_compressor compressor;
  6116. bool result = compressor.compress(
  6117. data.data(), data.size(),
  6118. /*last=*/true,
  6119. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6120. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6121. compressed_data_size);
  6122. return true;
  6123. });
  6124. ASSERT_TRUE(result);
  6125. }
  6126. std::string decompressed_data;
  6127. {
  6128. httplib::detail::zstd_decompressor decompressor;
  6129. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6130. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6131. size_t chunk_size = 130;
  6132. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6133. chunk_begin += chunk_size) {
  6134. size_t current_chunk_size =
  6135. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6136. bool result = decompressor.decompress(
  6137. compressed_data.data() + chunk_begin, current_chunk_size,
  6138. [&](const char *decompressed_data_chunk,
  6139. size_t decompressed_data_chunk_size) {
  6140. decompressed_data.insert(decompressed_data.size(),
  6141. decompressed_data_chunk,
  6142. decompressed_data_chunk_size);
  6143. return true;
  6144. });
  6145. ASSERT_TRUE(result);
  6146. }
  6147. }
  6148. ASSERT_EQ(data, decompressed_data);
  6149. }
  6150. TEST(ZstdDecompressor, Decompress) {
  6151. std::string original_text = "Compressed with ZSTD";
  6152. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6153. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6154. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6155. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6156. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6157. std::string decompressed_data;
  6158. {
  6159. httplib::detail::zstd_decompressor decompressor;
  6160. bool result = decompressor.decompress(
  6161. compressed_data.data(), compressed_data.size(),
  6162. [&](const char *decompressed_data_chunk,
  6163. size_t decompressed_data_chunk_size) {
  6164. decompressed_data.insert(decompressed_data.size(),
  6165. decompressed_data_chunk,
  6166. decompressed_data_chunk_size);
  6167. return true;
  6168. });
  6169. ASSERT_TRUE(result);
  6170. }
  6171. ASSERT_EQ(original_text, decompressed_data);
  6172. }
  6173. #endif
  6174. // Sends a raw request to a server listening at HOST:PORT.
  6175. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6176. std::string *resp = nullptr) {
  6177. auto error = Error::Success;
  6178. auto client_sock = detail::create_client_socket(
  6179. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6180. /*connection_timeout_sec=*/5, 0,
  6181. /*read_timeout_sec=*/5, 0,
  6182. /*write_timeout_sec=*/5, 0, std::string(), error);
  6183. if (client_sock == INVALID_SOCKET) { return false; }
  6184. auto ret = detail::process_client_socket(
  6185. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6186. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6187. if (req.size() !=
  6188. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6189. return false;
  6190. }
  6191. char buf[512];
  6192. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6193. while (line_reader.getline()) {
  6194. if (resp) { *resp += line_reader.ptr(); }
  6195. }
  6196. return true;
  6197. });
  6198. detail::close_socket(client_sock);
  6199. return ret;
  6200. }
  6201. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6202. Server svr;
  6203. std::string header_value;
  6204. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6205. header_value = req.get_header_value("foo");
  6206. res.set_content("ok", "text/plain");
  6207. });
  6208. thread t = thread([&] { svr.listen(HOST, PORT); });
  6209. auto se = detail::scope_exit([&] {
  6210. svr.stop();
  6211. t.join();
  6212. ASSERT_FALSE(svr.is_running());
  6213. });
  6214. svr.wait_until_ready();
  6215. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6216. // like characters are not treated the same - use vertical tab and escape.
  6217. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6218. "foo: \t \v bar \x1B\t \r\n"
  6219. "Connection: close\r\n"
  6220. "\r\n";
  6221. std::string res;
  6222. ASSERT_TRUE(send_request(5, req, &res));
  6223. EXPECT_EQ(header_value, "");
  6224. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6225. }
  6226. // Sends a raw request and verifies that there isn't a crash or exception.
  6227. static void test_raw_request(const std::string &req,
  6228. std::string *out = nullptr) {
  6229. Server svr;
  6230. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6231. res.set_content("ok", "text/plain");
  6232. });
  6233. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6234. res.set_content("ok", "text/plain");
  6235. });
  6236. svr.Get("/header_field_value_check",
  6237. [&](const Request & /*req*/, Response &res) {
  6238. res.set_content("ok", "text/plain");
  6239. });
  6240. // Server read timeout must be longer than the client read timeout for the
  6241. // bug to reproduce, probably to force the server to process a request
  6242. // without a trailing blank line.
  6243. const time_t client_read_timeout_sec = 1;
  6244. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6245. bool listen_thread_ok = false;
  6246. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6247. auto se = detail::scope_exit([&] {
  6248. svr.stop();
  6249. t.join();
  6250. ASSERT_FALSE(svr.is_running());
  6251. EXPECT_TRUE(listen_thread_ok);
  6252. });
  6253. svr.wait_until_ready();
  6254. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6255. }
  6256. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6257. // A certain header line causes an exception if the header property is parsed
  6258. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6259. test_raw_request(
  6260. "GET /hi HTTP/1.1\r\n"
  6261. " : "
  6262. " "
  6263. " ");
  6264. }
  6265. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6266. // A certain header line causes an exception if the header property *name* is
  6267. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6268. // greedy matcher and requires backtracking when there are a lot of ":"
  6269. // characters.
  6270. // This occurs with libc++ but not libstdc++.
  6271. test_raw_request(
  6272. "GET /hi HTTP/1.1\r\n"
  6273. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6274. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6275. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6276. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6277. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6278. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6279. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6280. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6281. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6282. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6283. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6284. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6285. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6286. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6287. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6288. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6289. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6290. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6291. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6292. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6293. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6294. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6295. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6296. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6297. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6298. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6299. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6300. "&&&%%%");
  6301. }
  6302. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6303. // Make sure this doesn't crash the server.
  6304. // In a previous version of the header line regex, the "\r" rendered the line
  6305. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6306. // a new position where the leading white space ended and the field value
  6307. // began.
  6308. // The crash occurs with libc++ but not libstdc++.
  6309. test_raw_request("GET /hi HTTP/1.1\r\n"
  6310. "a:" +
  6311. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6312. "\r\n"
  6313. "\r\n");
  6314. }
  6315. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6316. std::string out;
  6317. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6318. "Content-Type: text/plain\r\n"
  6319. "Transfer-Encoding: chunked\r\n"
  6320. "\r\n"
  6321. "nothex\r\n",
  6322. &out);
  6323. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6324. }
  6325. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6326. std::string out;
  6327. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6328. "Content-Type: text/plain\r\n"
  6329. "Transfer-Encoding: chunked\r\n"
  6330. "\r\n"
  6331. "3\r\n"
  6332. "xyz\r\n"
  6333. "NaN\r\n",
  6334. &out);
  6335. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6336. }
  6337. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6338. std::string out;
  6339. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6340. "Content-Type: text/plain\r\n"
  6341. "Transfer-Encoding: chunked\r\n"
  6342. "\r\n"
  6343. // Length is too large for 64 bits.
  6344. "1ffffffffffffffff\r\n"
  6345. "xyz\r\n",
  6346. &out);
  6347. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6348. }
  6349. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6350. test_raw_request("GET /hi HTTP/1.1\r\n"
  6351. "Content-Type: text/plain\r\n\r");
  6352. }
  6353. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6354. std::string out;
  6355. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6356. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6357. }
  6358. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6359. Server svr;
  6360. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6361. EXPECT_TRUE(!req.remote_addr.empty());
  6362. });
  6363. thread t = thread([&] { svr.listen(HOST, PORT); });
  6364. auto se = detail::scope_exit([&] {
  6365. svr.stop();
  6366. t.join();
  6367. ASSERT_FALSE(svr.is_running());
  6368. });
  6369. svr.wait_until_ready();
  6370. // Send an invalid request line to trigger Bad Request
  6371. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6372. std::string out;
  6373. ASSERT_TRUE(send_request(5, bad_req, &out));
  6374. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6375. }
  6376. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6377. std::string out;
  6378. std::string request(
  6379. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6380. test_raw_request(request, &out);
  6381. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6382. }
  6383. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6384. std::string out;
  6385. std::string request(
  6386. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6387. test_raw_request(request, &out);
  6388. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6389. }
  6390. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6391. std::string out;
  6392. std::string request(
  6393. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6394. test_raw_request(request, &out);
  6395. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6396. }
  6397. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6398. std::string out;
  6399. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6400. "Test: \r\n\r\n",
  6401. &out);
  6402. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6403. }
  6404. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  6405. Server svr;
  6406. std::string x_custom;
  6407. std::string cookie;
  6408. std::string xff;
  6409. std::string x_unicode;
  6410. std::string x_iis;
  6411. svr.Get("/check", [&](const Request &req, Response &res) {
  6412. x_custom = req.get_header_value("X-Custom");
  6413. cookie = req.get_header_value("Cookie");
  6414. xff = req.get_header_value("X-Forwarded-For");
  6415. x_unicode = req.get_header_value("X-Unicode");
  6416. x_iis = req.get_header_value("X-IIS");
  6417. res.set_content("ok", "text/plain");
  6418. });
  6419. thread t = thread([&] { svr.listen(HOST, PORT); });
  6420. auto se = detail::scope_exit([&] {
  6421. svr.stop();
  6422. t.join();
  6423. ASSERT_FALSE(svr.is_running());
  6424. });
  6425. svr.wait_until_ready();
  6426. const std::string req = "GET /check HTTP/1.1\r\n"
  6427. "Host: localhost\r\n"
  6428. "X-Custom: a%0D%0AInjected: b\r\n"
  6429. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  6430. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  6431. "X-Unicode: %E3%81%82\r\n"
  6432. "X-IIS: %u00E9\r\n"
  6433. "Connection: close\r\n"
  6434. "\r\n";
  6435. std::string res;
  6436. ASSERT_TRUE(send_request(5, req, &res));
  6437. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6438. // Every value must be returned verbatim (wire form), with no decoding.
  6439. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  6440. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  6441. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  6442. EXPECT_EQ("%E3%81%82", x_unicode);
  6443. EXPECT_EQ("%u00E9", x_iis);
  6444. }
  6445. // Applications that previously relied on automatic percent-decoding can
  6446. // reproduce the old behavior by explicitly calling decode_path_component()
  6447. // or, for RFC 3986 conformance, decode_uri_component().
  6448. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  6449. Server svr;
  6450. std::string decoded;
  6451. svr.Get("/check", [&](const Request &req, Response &res) {
  6452. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  6453. res.set_content("ok", "text/plain");
  6454. });
  6455. thread t = thread([&] { svr.listen(HOST, PORT); });
  6456. auto se = detail::scope_exit([&] {
  6457. svr.stop();
  6458. t.join();
  6459. ASSERT_FALSE(svr.is_running());
  6460. });
  6461. svr.wait_until_ready();
  6462. const std::string req = "GET /check HTTP/1.1\r\n"
  6463. "Host: localhost\r\n"
  6464. "X-Custom: hello%20world\r\n"
  6465. "Connection: close\r\n"
  6466. "\r\n";
  6467. std::string res;
  6468. ASSERT_TRUE(send_request(5, req, &res));
  6469. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6470. EXPECT_EQ("hello world", decoded);
  6471. }
  6472. // Regression test for #2033. Browsers send Referer values that include
  6473. // percent-encoded characters such as %0A inside the URL. Decoding the
  6474. // header value would either trip the post-decode CR/LF/NUL guard (the
  6475. // original bug, returning 400) or, after that guard was relaxed, silently
  6476. // store a literal LF — both unacceptable. The wire form must round-trip.
  6477. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  6478. Server svr;
  6479. std::string referer;
  6480. svr.Get("/check", [&](const Request &req, Response &res) {
  6481. referer = req.get_header_value("Referer");
  6482. res.set_content("ok", "text/plain");
  6483. });
  6484. thread t = thread([&] { svr.listen(HOST, PORT); });
  6485. auto se = detail::scope_exit([&] {
  6486. svr.stop();
  6487. t.join();
  6488. ASSERT_FALSE(svr.is_running());
  6489. });
  6490. svr.wait_until_ready();
  6491. const std::string req = "GET /check HTTP/1.1\r\n"
  6492. "Host: localhost\r\n"
  6493. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  6494. "Connection: close\r\n"
  6495. "\r\n";
  6496. std::string res;
  6497. ASSERT_TRUE(send_request(5, req, &res));
  6498. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  6499. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  6500. }
  6501. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6502. Server svr;
  6503. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6504. res.set_header("Cache-Control", "no-cache");
  6505. res.set_chunked_content_provider(
  6506. "text/event-stream", [](size_t offset, DataSink &sink) {
  6507. std::string s = "data:";
  6508. s += std::to_string(offset);
  6509. s += "\n\n";
  6510. auto ret = sink.write(s.data(), s.size());
  6511. EXPECT_TRUE(ret);
  6512. std::this_thread::sleep_for(std::chrono::seconds(1));
  6513. return true;
  6514. });
  6515. });
  6516. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6517. svr.wait_until_ready();
  6518. Client client(HOST, PORT);
  6519. const Headers headers = {{"Accept", "text/event-stream"}};
  6520. auto get_thread = std::thread([&client, &headers]() {
  6521. auto res = client.Get(
  6522. "/events", headers,
  6523. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6524. });
  6525. auto se = detail::scope_exit([&] {
  6526. svr.stop();
  6527. get_thread.join();
  6528. listen_thread.join();
  6529. ASSERT_FALSE(svr.is_running());
  6530. });
  6531. // Give GET time to get a few messages.
  6532. std::this_thread::sleep_for(std::chrono::seconds(2));
  6533. }
  6534. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6535. httplib::Server svr;
  6536. svr.Post("/hi",
  6537. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6538. res.status = StatusCode::OK_200;
  6539. });
  6540. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6541. svr.wait_until_ready();
  6542. Client cli(HOST, PORT);
  6543. auto res = cli.Post("/hi", "data", "text/plain");
  6544. ASSERT_TRUE(res);
  6545. EXPECT_EQ(StatusCode::OK_200, res->status);
  6546. svr.stop();
  6547. thread.join();
  6548. ASSERT_FALSE(svr.is_running());
  6549. res = cli.Post("/hi", "data", "text/plain");
  6550. ASSERT_FALSE(res);
  6551. }
  6552. TEST(ServerStopTest, ListenFailure) {
  6553. Server svr;
  6554. auto t = thread([&]() {
  6555. auto ret = svr.listen("????", PORT);
  6556. EXPECT_FALSE(ret);
  6557. });
  6558. svr.wait_until_ready();
  6559. svr.stop();
  6560. t.join();
  6561. }
  6562. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6563. TEST(ServerStopTest, Decommision) {
  6564. Server svr;
  6565. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6566. for (int i = 0; i < 4; i++) {
  6567. auto is_even = !(i % 2);
  6568. std::thread t{[&] {
  6569. try {
  6570. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6571. if (is_even) {
  6572. throw std::runtime_error("Some thing that happens to go wrong.");
  6573. }
  6574. svr.listen(HOST, PORT);
  6575. } catch (...) { svr.decommission(); }
  6576. }};
  6577. svr.wait_until_ready();
  6578. // Server is up
  6579. {
  6580. Client cli(HOST, PORT);
  6581. auto res = cli.Get("/hi");
  6582. if (is_even) {
  6583. EXPECT_FALSE(res);
  6584. } else {
  6585. EXPECT_TRUE(res);
  6586. EXPECT_EQ("hi...", res->body);
  6587. }
  6588. }
  6589. svr.stop();
  6590. t.join();
  6591. // Server is down...
  6592. {
  6593. Client cli(HOST, PORT);
  6594. auto res = cli.Get("/hi");
  6595. EXPECT_FALSE(res);
  6596. }
  6597. }
  6598. }
  6599. #endif
  6600. // Helper function for string body upload progress tests
  6601. template <typename SetupHandler, typename ClientCall>
  6602. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6603. ClientCall &&client_call,
  6604. const string &body) {
  6605. Server svr;
  6606. setup_handler(svr);
  6607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6608. auto se = detail::scope_exit([&] {
  6609. svr.stop();
  6610. t.join();
  6611. });
  6612. svr.wait_until_ready();
  6613. Client cli(HOST, PORT);
  6614. vector<uint64_t> progress_values;
  6615. bool progress_called = false;
  6616. auto res =
  6617. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6618. progress_values.push_back(current);
  6619. progress_called = true;
  6620. return true;
  6621. });
  6622. ASSERT_TRUE(res);
  6623. EXPECT_EQ(200, res->status);
  6624. EXPECT_TRUE(progress_called);
  6625. }
  6626. TEST(UploadProgressTest, PostStringBodyBasic) {
  6627. TestStringBodyUploadProgress(
  6628. [](Server &svr) {
  6629. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6630. res.set_content("received", "text/plain");
  6631. });
  6632. },
  6633. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6634. return cli.Post("/test", body, "text/plain", progress_callback);
  6635. },
  6636. "test data for upload progress");
  6637. }
  6638. TEST(UploadProgressTest, PutStringBodyBasic) {
  6639. TestStringBodyUploadProgress(
  6640. [](Server &svr) {
  6641. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6642. res.set_content("put received", "text/plain");
  6643. });
  6644. },
  6645. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6646. return cli.Put("/test", body, "text/plain", progress_callback);
  6647. },
  6648. "put test data for upload progress");
  6649. }
  6650. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6651. TestStringBodyUploadProgress(
  6652. [](Server &svr) {
  6653. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6654. res.set_content("patch received", "text/plain");
  6655. });
  6656. },
  6657. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6658. return cli.Patch("/test", body, "text/plain", progress_callback);
  6659. },
  6660. "patch test data for upload progress");
  6661. }
  6662. // Helper function for content provider upload progress tests
  6663. template <typename SetupHandler, typename ClientCall>
  6664. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6665. ClientCall &&client_call) {
  6666. Server svr;
  6667. setup_handler(svr);
  6668. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6669. auto se = detail::scope_exit([&] {
  6670. svr.stop();
  6671. t.join();
  6672. });
  6673. svr.wait_until_ready();
  6674. Client cli(HOST, PORT);
  6675. vector<uint64_t> progress_values;
  6676. auto res =
  6677. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6678. progress_values.push_back(current);
  6679. return true;
  6680. });
  6681. ASSERT_TRUE(res);
  6682. EXPECT_EQ(200, res->status);
  6683. EXPECT_FALSE(progress_values.empty());
  6684. }
  6685. TEST(UploadProgressTest, PostContentProviderProgress) {
  6686. TestContentProviderUploadProgress(
  6687. [](Server &svr) {
  6688. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6689. res.set_content("provider received", "text/plain");
  6690. });
  6691. },
  6692. [](Client &cli, UploadProgress progress_callback) {
  6693. return cli.Post(
  6694. "/test", 10,
  6695. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6696. sink.os << "test data";
  6697. return true;
  6698. },
  6699. "text/plain", progress_callback);
  6700. });
  6701. }
  6702. // Helper function for multipart upload progress tests
  6703. template <typename SetupHandler, typename ClientCall>
  6704. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6705. ClientCall &&client_call,
  6706. const string &endpoint) {
  6707. Server svr;
  6708. setup_handler(svr);
  6709. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6710. auto se = detail::scope_exit([&] {
  6711. svr.stop();
  6712. t.join();
  6713. });
  6714. svr.wait_until_ready();
  6715. Client cli(HOST, PORT);
  6716. vector<uint64_t> progress_values;
  6717. UploadFormDataItems items = {
  6718. {"field1", "value1", "", ""},
  6719. {"field2", "longer value for progress tracking test", "", ""},
  6720. {"file1", "file content data for upload progress", "test.txt",
  6721. "text/plain"}};
  6722. auto res = client_call(cli, endpoint, items,
  6723. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6724. progress_values.push_back(current);
  6725. return true;
  6726. });
  6727. ASSERT_TRUE(res);
  6728. EXPECT_EQ(200, res->status);
  6729. EXPECT_FALSE(progress_values.empty());
  6730. }
  6731. TEST(UploadProgressTest, PostMultipartProgress) {
  6732. TestMultipartUploadProgress(
  6733. [](Server &svr) {
  6734. svr.Post("/multipart", [](const Request &req, Response &res) {
  6735. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6736. res.set_content("multipart received", "text/plain");
  6737. });
  6738. },
  6739. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6740. UploadProgress progress_callback) {
  6741. return cli.Post(endpoint, items, progress_callback);
  6742. },
  6743. "/multipart");
  6744. }
  6745. // Helper function for basic download progress tests
  6746. template <typename SetupHandler, typename ClientCall>
  6747. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6748. ClientCall &&client_call, const string &endpoint,
  6749. size_t expected_content_size) {
  6750. Server svr;
  6751. setup_handler(svr);
  6752. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6753. auto se = detail::scope_exit([&] {
  6754. svr.stop();
  6755. t.join();
  6756. });
  6757. svr.wait_until_ready();
  6758. Client cli(HOST, PORT);
  6759. vector<uint64_t> progress_values;
  6760. auto res = client_call(cli, endpoint,
  6761. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6762. progress_values.push_back(current);
  6763. return true;
  6764. });
  6765. ASSERT_TRUE(res);
  6766. EXPECT_EQ(200, res->status);
  6767. EXPECT_FALSE(progress_values.empty());
  6768. EXPECT_EQ(expected_content_size, res->body.size());
  6769. }
  6770. TEST(DownloadProgressTest, GetBasic) {
  6771. TestBasicDownloadProgress(
  6772. [](Server &svr) {
  6773. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6774. string content(1000, 'D');
  6775. res.set_content(content, "text/plain");
  6776. });
  6777. },
  6778. [](Client &cli, const string &endpoint,
  6779. DownloadProgress progress_callback) {
  6780. return cli.Get(endpoint, progress_callback);
  6781. },
  6782. "/download", 1000u);
  6783. }
  6784. // Helper function for content receiver download progress tests
  6785. template <typename SetupHandler, typename ClientCall>
  6786. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6787. ClientCall &&client_call,
  6788. const string &endpoint,
  6789. size_t expected_content_size) {
  6790. Server svr;
  6791. setup_handler(svr);
  6792. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6793. auto se = detail::scope_exit([&] {
  6794. svr.stop();
  6795. t.join();
  6796. });
  6797. svr.wait_until_ready();
  6798. Client cli(HOST, PORT);
  6799. vector<uint64_t> progress_values;
  6800. string received_body;
  6801. auto res = client_call(
  6802. cli, endpoint,
  6803. [&](const char *data, size_t data_length) -> bool {
  6804. received_body.append(data, data_length);
  6805. return true;
  6806. },
  6807. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6808. progress_values.push_back(current);
  6809. return true;
  6810. });
  6811. ASSERT_TRUE(res);
  6812. EXPECT_EQ(200, res->status);
  6813. EXPECT_FALSE(progress_values.empty());
  6814. EXPECT_EQ(expected_content_size, received_body.size());
  6815. EXPECT_TRUE(res->body.empty());
  6816. }
  6817. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6818. TestContentReceiverDownloadProgress(
  6819. [](Server &svr) {
  6820. svr.Get("/download-receiver",
  6821. [](const Request & /*req*/, Response &res) {
  6822. string content(2000, 'R');
  6823. res.set_content(content, "text/plain");
  6824. });
  6825. },
  6826. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6827. DownloadProgress progress_callback) {
  6828. return cli.Get(endpoint, content_receiver, progress_callback);
  6829. },
  6830. "/download-receiver", 2000u);
  6831. }
  6832. TEST(StreamingTest, NoContentLengthStreaming) {
  6833. Server svr;
  6834. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6835. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6836. if (offset < 6) {
  6837. sink.os << (offset < 3 ? "a" : "b");
  6838. } else {
  6839. sink.done();
  6840. }
  6841. return true;
  6842. });
  6843. });
  6844. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6845. auto listen_se = detail::scope_exit([&] {
  6846. svr.stop();
  6847. listen_thread.join();
  6848. ASSERT_FALSE(svr.is_running());
  6849. });
  6850. svr.wait_until_ready();
  6851. Client client(HOST, PORT);
  6852. auto get_thread = std::thread([&client]() {
  6853. std::string s;
  6854. auto res =
  6855. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6856. s += std::string(data, len);
  6857. return true;
  6858. });
  6859. ASSERT_TRUE(res);
  6860. EXPECT_EQ(StatusCode::OK_200, res->status);
  6861. EXPECT_EQ("aaabbb", s);
  6862. });
  6863. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6864. // Give GET time to get a few messages.
  6865. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6866. }
  6867. TEST(MountTest, Unmount) {
  6868. Server svr;
  6869. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6870. auto se = detail::scope_exit([&] {
  6871. svr.stop();
  6872. listen_thread.join();
  6873. ASSERT_FALSE(svr.is_running());
  6874. });
  6875. svr.wait_until_ready();
  6876. Client cli("localhost", PORT);
  6877. svr.set_mount_point("/mount2", "./www2");
  6878. auto res = cli.Get("/");
  6879. ASSERT_TRUE(res);
  6880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6881. res = cli.Get("/mount2/dir/test.html");
  6882. ASSERT_TRUE(res);
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. svr.set_mount_point("/", "./www");
  6885. res = cli.Get("/dir/");
  6886. ASSERT_TRUE(res);
  6887. EXPECT_EQ(StatusCode::OK_200, res->status);
  6888. svr.remove_mount_point("/");
  6889. res = cli.Get("/dir/");
  6890. ASSERT_TRUE(res);
  6891. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6892. svr.remove_mount_point("/mount2");
  6893. res = cli.Get("/mount2/dir/test.html");
  6894. ASSERT_TRUE(res);
  6895. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6896. }
  6897. TEST(MountTest, Redicect) {
  6898. Server svr;
  6899. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6900. auto se = detail::scope_exit([&] {
  6901. svr.stop();
  6902. listen_thread.join();
  6903. ASSERT_FALSE(svr.is_running());
  6904. });
  6905. svr.set_mount_point("/", "./www");
  6906. svr.wait_until_ready();
  6907. Client cli("localhost", PORT);
  6908. auto res = cli.Get("/dir/");
  6909. ASSERT_TRUE(res);
  6910. EXPECT_EQ(StatusCode::OK_200, res->status);
  6911. res = cli.Get("/dir");
  6912. ASSERT_TRUE(res);
  6913. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6914. res = cli.Get("/file");
  6915. ASSERT_TRUE(res);
  6916. EXPECT_EQ(StatusCode::OK_200, res->status);
  6917. res = cli.Get("/file/");
  6918. ASSERT_TRUE(res);
  6919. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6920. cli.set_follow_location(true);
  6921. res = cli.Get("/dir");
  6922. ASSERT_TRUE(res);
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. }
  6925. TEST(MountTest, MultibytesPathName) {
  6926. Server svr;
  6927. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6928. auto se = detail::scope_exit([&] {
  6929. svr.stop();
  6930. listen_thread.join();
  6931. ASSERT_FALSE(svr.is_running());
  6932. });
  6933. svr.set_mount_point("/", "./www");
  6934. svr.wait_until_ready();
  6935. Client cli("localhost", PORT);
  6936. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6937. ASSERT_TRUE(res);
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6940. }
  6941. #ifdef _WIN32
  6942. // Issue #2435: mmap::open() must succeed even when another handle holds
  6943. // the file open for writing (e.g. an active log file).
  6944. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6945. const char *path = "mmap_concurrent_writer_test.txt";
  6946. const char *content = "hello";
  6947. {
  6948. std::ofstream f(path, std::ios::binary);
  6949. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6950. }
  6951. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6952. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6953. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6954. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6955. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6956. detail::mmap m(path);
  6957. ASSERT_TRUE(m.is_open());
  6958. EXPECT_EQ(strlen(content), m.size());
  6959. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6960. }
  6961. #endif
  6962. TEST(KeepAliveTest, ReadTimeout) {
  6963. Server svr;
  6964. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6965. std::this_thread::sleep_for(std::chrono::seconds(2));
  6966. res.set_content("a", "text/plain");
  6967. });
  6968. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6969. res.set_content("b", "text/plain");
  6970. });
  6971. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6972. auto se = detail::scope_exit([&] {
  6973. svr.stop();
  6974. listen_thread.join();
  6975. ASSERT_FALSE(svr.is_running());
  6976. });
  6977. svr.wait_until_ready();
  6978. Client cli("localhost", PORT);
  6979. cli.set_keep_alive(true);
  6980. cli.set_read_timeout(std::chrono::seconds(1));
  6981. auto resa = cli.Get("/a");
  6982. ASSERT_FALSE(resa);
  6983. EXPECT_EQ(Error::Read, resa.error());
  6984. auto resb = cli.Get("/b");
  6985. ASSERT_TRUE(resb);
  6986. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6987. EXPECT_EQ("b", resb->body);
  6988. }
  6989. TEST(KeepAliveTest, MaxCount) {
  6990. size_t keep_alive_max_count = 3;
  6991. Server svr;
  6992. svr.set_keep_alive_max_count(keep_alive_max_count);
  6993. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6994. res.set_content("Hello World!", "text/plain");
  6995. });
  6996. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6997. auto se = detail::scope_exit([&] {
  6998. svr.stop();
  6999. listen_thread.join();
  7000. ASSERT_FALSE(svr.is_running());
  7001. });
  7002. svr.wait_until_ready();
  7003. Client cli(HOST, PORT);
  7004. cli.set_keep_alive(true);
  7005. for (size_t i = 0; i < 5; i++) {
  7006. auto result = cli.Get("/hi");
  7007. ASSERT_TRUE(result);
  7008. EXPECT_EQ(StatusCode::OK_200, result->status);
  7009. if (i == keep_alive_max_count - 1) {
  7010. EXPECT_EQ("close", result->get_header_value("Connection"));
  7011. } else {
  7012. EXPECT_FALSE(result->has_header("Connection"));
  7013. }
  7014. }
  7015. }
  7016. TEST(KeepAliveTest, Issue1041) {
  7017. Server svr;
  7018. svr.set_keep_alive_timeout(3);
  7019. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7020. res.set_content("Hello World!", "text/plain");
  7021. });
  7022. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7023. auto se = detail::scope_exit([&] {
  7024. svr.stop();
  7025. listen_thread.join();
  7026. ASSERT_FALSE(svr.is_running());
  7027. });
  7028. svr.wait_until_ready();
  7029. Client cli(HOST, PORT);
  7030. cli.set_keep_alive(true);
  7031. auto result = cli.Get("/hi");
  7032. ASSERT_TRUE(result);
  7033. EXPECT_EQ(StatusCode::OK_200, result->status);
  7034. std::this_thread::sleep_for(std::chrono::seconds(5));
  7035. result = cli.Get("/hi");
  7036. ASSERT_TRUE(result);
  7037. EXPECT_EQ(StatusCode::OK_200, result->status);
  7038. }
  7039. TEST(KeepAliveTest, Issue1959) {
  7040. Server svr;
  7041. svr.set_keep_alive_timeout(5);
  7042. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7043. res.set_content("a", "text/plain");
  7044. });
  7045. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7046. auto se = detail::scope_exit([&] {
  7047. if (!svr.is_running()) return;
  7048. svr.stop();
  7049. listen_thread.join();
  7050. ASSERT_FALSE(svr.is_running());
  7051. });
  7052. svr.wait_until_ready();
  7053. Client cli("localhost", PORT);
  7054. cli.set_keep_alive(true);
  7055. using namespace std::chrono;
  7056. auto start = steady_clock::now();
  7057. cli.Get("/a");
  7058. svr.stop();
  7059. listen_thread.join();
  7060. auto end = steady_clock::now();
  7061. auto elapsed = duration_cast<milliseconds>(end - start).count();
  7062. EXPECT_LT(elapsed, 5000);
  7063. }
  7064. #ifdef CPPHTTPLIB_SSL_ENABLED
  7065. TEST(KeepAliveTest, SSLClientReconnection) {
  7066. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7067. ASSERT_TRUE(svr.is_valid());
  7068. svr.set_keep_alive_timeout(1);
  7069. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  7070. res.set_content("Hello World!", "text/plain");
  7071. });
  7072. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7073. auto se = detail::scope_exit([&] {
  7074. svr.stop();
  7075. listen_thread.join();
  7076. ASSERT_FALSE(svr.is_running());
  7077. });
  7078. svr.wait_until_ready();
  7079. SSLClient cli(HOST, PORT);
  7080. cli.enable_server_certificate_verification(false);
  7081. cli.set_keep_alive(true);
  7082. auto result = cli.Get("/hi");
  7083. ASSERT_TRUE(result);
  7084. EXPECT_EQ(StatusCode::OK_200, result->status);
  7085. result = cli.Get("/hi");
  7086. ASSERT_TRUE(result);
  7087. EXPECT_EQ(StatusCode::OK_200, result->status);
  7088. std::this_thread::sleep_for(std::chrono::seconds(2));
  7089. // Recoonect
  7090. result = cli.Get("/hi");
  7091. ASSERT_TRUE(result);
  7092. EXPECT_EQ(StatusCode::OK_200, result->status);
  7093. result = cli.Get("/hi");
  7094. ASSERT_TRUE(result);
  7095. EXPECT_EQ(StatusCode::OK_200, result->status);
  7096. }
  7097. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  7098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7099. ASSERT_TRUE(svr.is_valid());
  7100. svr.set_keep_alive_timeout(1);
  7101. std::string content = "reconnect";
  7102. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  7103. res.set_content("Hello World!", "text/plain");
  7104. });
  7105. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7106. auto se = detail::scope_exit([&] {
  7107. svr.stop();
  7108. listen_thread.join();
  7109. ASSERT_FALSE(svr.is_running());
  7110. });
  7111. svr.wait_until_ready();
  7112. SSLClient cli(HOST, PORT);
  7113. cli.enable_server_certificate_verification(false);
  7114. cli.set_keep_alive(true);
  7115. auto result = cli.Post(
  7116. "/hi", content.size(),
  7117. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7118. sink.write(content.c_str(), content.size());
  7119. return true;
  7120. },
  7121. "text/plain");
  7122. ASSERT_TRUE(result);
  7123. EXPECT_EQ(200, result->status);
  7124. std::this_thread::sleep_for(std::chrono::seconds(2));
  7125. // Recoonect
  7126. result = cli.Post(
  7127. "/hi", content.size(),
  7128. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7129. sink.write(content.c_str(), content.size());
  7130. return true;
  7131. },
  7132. "text/plain");
  7133. ASSERT_TRUE(result);
  7134. EXPECT_EQ(200, result->status);
  7135. result = cli.Post(
  7136. "/hi", content.size(),
  7137. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7138. sink.write(content.c_str(), content.size());
  7139. return true;
  7140. },
  7141. "text/plain");
  7142. ASSERT_TRUE(result);
  7143. EXPECT_EQ(200, result->status);
  7144. }
  7145. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  7146. using namespace httplib::tls;
  7147. {
  7148. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7149. ASSERT_TRUE(svr.is_valid());
  7150. svr.Get("/sni", [&](const Request &req, Response &res) {
  7151. std::string expected = req.sni();
  7152. EXPECT_EQ(expected, req.get_param_value("expected"));
  7153. res.set_content("ok", "text/plain");
  7154. });
  7155. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  7156. auto se = detail::scope_exit([&] {
  7157. svr.stop();
  7158. listen_thread.join();
  7159. ASSERT_FALSE(svr.is_running());
  7160. });
  7161. svr.wait_until_ready();
  7162. {
  7163. SSLClient cli("localhost", PORT);
  7164. cli.enable_server_certificate_verification(false);
  7165. auto res = cli.Get("/sni?expected=localhost");
  7166. ASSERT_TRUE(res);
  7167. }
  7168. {
  7169. SSLClient cli("::1", PORT);
  7170. cli.enable_server_certificate_verification(false);
  7171. auto res = cli.Get("/sni?expected=");
  7172. // NOTE: This may fail if the server is listening on IPv4 only
  7173. // (e.g., when localhost resolves to 127.0.0.1 only)
  7174. if (res) {
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. } else {
  7177. EXPECT_EQ(Error::Connection, res.error());
  7178. }
  7179. }
  7180. }
  7181. }
  7182. #endif
  7183. TEST(ClientProblemDetectionTest, ContentProvider) {
  7184. Server svr;
  7185. size_t content_length = 1024 * 1024;
  7186. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7187. res.set_content_provider(
  7188. content_length, "text/plain",
  7189. [&](size_t offset, size_t length, DataSink &sink) {
  7190. auto out_len = std::min(length, static_cast<size_t>(1024));
  7191. std::string out(out_len, '@');
  7192. sink.write(out.data(), out_len);
  7193. return offset < 4096;
  7194. },
  7195. [](bool success) { ASSERT_FALSE(success); });
  7196. });
  7197. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  7198. res.set_content_provider(
  7199. 0, "text/plain",
  7200. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  7201. EXPECT_TRUE(false);
  7202. return true;
  7203. },
  7204. [](bool success) { ASSERT_FALSE(success); });
  7205. });
  7206. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7207. auto se = detail::scope_exit([&] {
  7208. svr.stop();
  7209. listen_thread.join();
  7210. ASSERT_FALSE(svr.is_running());
  7211. });
  7212. svr.wait_until_ready();
  7213. Client cli("localhost", PORT);
  7214. {
  7215. auto res = cli.Get("/hi", [&](const char * /*data*/,
  7216. size_t /*data_length*/) { return false; });
  7217. ASSERT_FALSE(res);
  7218. }
  7219. {
  7220. auto res = cli.Get("/empty", [&](const char * /*data*/,
  7221. size_t /*data_length*/) { return false; });
  7222. ASSERT_TRUE(res);
  7223. }
  7224. }
  7225. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  7226. Server svr;
  7227. svr.set_error_handler([](Request const &, Response &res) -> void {
  7228. res.set_chunked_content_provider(
  7229. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7230. sink.os << "hello";
  7231. sink.os << "world";
  7232. sink.done();
  7233. return true;
  7234. });
  7235. });
  7236. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7237. auto se = detail::scope_exit([&] {
  7238. svr.stop();
  7239. listen_thread.join();
  7240. ASSERT_FALSE(svr.is_running());
  7241. });
  7242. svr.wait_until_ready();
  7243. Client cli("localhost", PORT);
  7244. auto res = cli.Get("/");
  7245. ASSERT_TRUE(res);
  7246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7247. EXPECT_EQ("helloworld", res->body);
  7248. }
  7249. TEST(LongPollingTest, ClientCloseDetection) {
  7250. Server svr;
  7251. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7252. res.set_chunked_content_provider(
  7253. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7254. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7255. sink.os << "hello";
  7256. auto count = 10;
  7257. while (count > 0 && sink.is_writable()) {
  7258. this_thread::sleep_for(chrono::milliseconds(10));
  7259. count--;
  7260. }
  7261. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7262. return true;
  7263. });
  7264. });
  7265. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7266. auto se = detail::scope_exit([&] {
  7267. svr.stop();
  7268. listen_thread.join();
  7269. ASSERT_FALSE(svr.is_running());
  7270. });
  7271. svr.wait_until_ready();
  7272. Client cli("localhost", PORT);
  7273. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7274. EXPECT_EQ("hello", string(data, data_length));
  7275. return false; // close the socket immediately.
  7276. });
  7277. ASSERT_FALSE(res);
  7278. }
  7279. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7280. Server svr;
  7281. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7282. res.set_chunked_content_provider(
  7283. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7284. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7285. sink.os << "hello";
  7286. EXPECT_TRUE(sink.os.good());
  7287. // Wait for the client to close the connection
  7288. auto count = 10;
  7289. while (count > 0 && sink.is_writable()) {
  7290. this_thread::sleep_for(chrono::milliseconds(10));
  7291. count--;
  7292. }
  7293. // After client disconnect, write repeatedly until the socket
  7294. // write actually fails (small writes may be absorbed by the
  7295. // kernel buffer)
  7296. std::string chunk(1024, 'x');
  7297. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7298. sink.os << chunk;
  7299. }
  7300. EXPECT_TRUE(sink.os.fail());
  7301. return true;
  7302. });
  7303. });
  7304. auto port = svr.bind_to_any_port("localhost");
  7305. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7306. auto se = detail::scope_exit([&] {
  7307. svr.stop();
  7308. listen_thread.join();
  7309. ASSERT_FALSE(svr.is_running());
  7310. });
  7311. svr.wait_until_ready();
  7312. Client cli("localhost", port);
  7313. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7314. EXPECT_EQ("hello", string(data, data_length));
  7315. return false; // close the socket immediately.
  7316. });
  7317. ASSERT_FALSE(res);
  7318. }
  7319. TEST(GetWithParametersTest, GetWithParameters) {
  7320. Server svr;
  7321. svr.Get("/", [&](const Request &req, Response &) {
  7322. EXPECT_EQ("world", req.get_param_value("hello"));
  7323. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7324. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7325. });
  7326. svr.Get("/params", [&](const Request &req, Response &) {
  7327. EXPECT_EQ("world", req.get_param_value("hello"));
  7328. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7329. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7330. });
  7331. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7332. EXPECT_EQ("resource-id", req.matches[1]);
  7333. EXPECT_EQ("foo", req.get_param_value("param1"));
  7334. EXPECT_EQ("bar", req.get_param_value("param2"));
  7335. });
  7336. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7337. EXPECT_EQ("user-id", req.path_params.at("id"));
  7338. EXPECT_EQ("foo", req.get_param_value("param1"));
  7339. EXPECT_EQ("bar", req.get_param_value("param2"));
  7340. });
  7341. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7342. auto se = detail::scope_exit([&] {
  7343. svr.stop();
  7344. listen_thread.join();
  7345. ASSERT_FALSE(svr.is_running());
  7346. });
  7347. svr.wait_until_ready();
  7348. {
  7349. Client cli(HOST, PORT);
  7350. Params params;
  7351. params.emplace("hello", "world");
  7352. params.emplace("hello2", "world2");
  7353. params.emplace("hello3", "world3");
  7354. auto res = cli.Get("/", params, Headers{});
  7355. ASSERT_TRUE(res);
  7356. EXPECT_EQ(StatusCode::OK_200, res->status);
  7357. }
  7358. {
  7359. Client cli(HOST, PORT);
  7360. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7361. ASSERT_TRUE(res);
  7362. EXPECT_EQ(StatusCode::OK_200, res->status);
  7363. }
  7364. {
  7365. Client cli(HOST, PORT);
  7366. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7367. ASSERT_TRUE(res);
  7368. EXPECT_EQ(StatusCode::OK_200, res->status);
  7369. }
  7370. {
  7371. Client cli(HOST, PORT);
  7372. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7373. ASSERT_TRUE(res);
  7374. EXPECT_EQ(StatusCode::OK_200, res->status);
  7375. }
  7376. }
  7377. TEST(GetWithParametersTest, GetWithParameters2) {
  7378. Server svr;
  7379. svr.Get("/", [&](const Request &req, Response &res) {
  7380. auto text = req.get_param_value("hello");
  7381. res.set_content(text, "text/plain");
  7382. });
  7383. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7384. auto se = detail::scope_exit([&] {
  7385. svr.stop();
  7386. listen_thread.join();
  7387. ASSERT_FALSE(svr.is_running());
  7388. });
  7389. svr.wait_until_ready();
  7390. Client cli("localhost", PORT);
  7391. Params params;
  7392. params.emplace("hello", "world");
  7393. std::string body;
  7394. auto res = cli.Get("/", params, Headers{},
  7395. [&](const char *data, size_t data_length) {
  7396. body.append(data, data_length);
  7397. return true;
  7398. });
  7399. ASSERT_TRUE(res);
  7400. EXPECT_EQ(StatusCode::OK_200, res->status);
  7401. EXPECT_EQ("world", body);
  7402. }
  7403. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7404. auto host = "httpbingo.org";
  7405. auto path = std::string{"/range/32"};
  7406. #ifdef CPPHTTPLIB_SSL_ENABLED
  7407. SSLClient cli(host);
  7408. #else
  7409. Client cli(host);
  7410. #endif
  7411. cli.set_default_headers({make_range_header({{1, 10}})});
  7412. cli.set_connection_timeout(5);
  7413. {
  7414. auto res = cli.Get(path);
  7415. ASSERT_TRUE(res);
  7416. EXPECT_EQ("bcdefghijk", res->body);
  7417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7418. }
  7419. {
  7420. auto res = cli.Get(path);
  7421. ASSERT_TRUE(res);
  7422. EXPECT_EQ("bcdefghijk", res->body);
  7423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7424. }
  7425. }
  7426. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7427. Server svr;
  7428. svr.set_default_headers({{"Hello", "World"}});
  7429. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7430. res.set_content("ok", "text/plain");
  7431. });
  7432. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7433. auto se = detail::scope_exit([&] {
  7434. svr.stop();
  7435. listen_thread.join();
  7436. ASSERT_FALSE(svr.is_running());
  7437. });
  7438. svr.wait_until_ready();
  7439. Client cli("localhost", PORT);
  7440. auto res = cli.Get("/");
  7441. ASSERT_TRUE(res);
  7442. EXPECT_EQ(StatusCode::OK_200, res->status);
  7443. EXPECT_EQ("ok", res->body);
  7444. EXPECT_EQ("World", res->get_header_value("Hello"));
  7445. }
  7446. #ifdef CPPHTTPLIB_SSL_ENABLED
  7447. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7449. ASSERT_TRUE(svr.is_valid());
  7450. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7451. std::this_thread::sleep_for(std::chrono::seconds(2));
  7452. res.set_content("a", "text/plain");
  7453. });
  7454. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7455. res.set_content("b", "text/plain");
  7456. });
  7457. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7458. auto se = detail::scope_exit([&] {
  7459. svr.stop();
  7460. listen_thread.join();
  7461. ASSERT_FALSE(svr.is_running());
  7462. });
  7463. svr.wait_until_ready();
  7464. SSLClient cli("localhost", PORT);
  7465. cli.enable_server_certificate_verification(false);
  7466. cli.set_keep_alive(true);
  7467. cli.set_read_timeout(std::chrono::seconds(1));
  7468. auto resa = cli.Get("/a");
  7469. ASSERT_TRUE(!resa);
  7470. EXPECT_EQ(Error::Read, resa.error());
  7471. auto resb = cli.Get("/b");
  7472. ASSERT_TRUE(resb);
  7473. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7474. EXPECT_EQ("b", resb->body);
  7475. }
  7476. #endif
  7477. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7478. protected:
  7479. ServerTestWithAI_PASSIVE()
  7480. : cli_(HOST, PORT)
  7481. #ifdef CPPHTTPLIB_SSL_ENABLED
  7482. ,
  7483. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7484. #endif
  7485. {
  7486. #ifdef CPPHTTPLIB_SSL_ENABLED
  7487. cli_.enable_server_certificate_verification(false);
  7488. #endif
  7489. }
  7490. virtual void SetUp() {
  7491. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7492. res.set_content("Hello World!", "text/plain");
  7493. });
  7494. t_ = thread(
  7495. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7496. svr_.wait_until_ready();
  7497. }
  7498. virtual void TearDown() {
  7499. svr_.stop();
  7500. t_.join();
  7501. }
  7502. #ifdef CPPHTTPLIB_SSL_ENABLED
  7503. SSLClient cli_;
  7504. SSLServer svr_;
  7505. #else
  7506. Client cli_;
  7507. Server svr_;
  7508. #endif
  7509. thread t_;
  7510. };
  7511. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7512. auto res = cli_.Get("/hi");
  7513. ASSERT_TRUE(res);
  7514. EXPECT_EQ(StatusCode::OK_200, res->status);
  7515. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7516. EXPECT_EQ("Hello World!", res->body);
  7517. }
  7518. class ServerUpDownTest : public ::testing::Test {
  7519. protected:
  7520. ServerUpDownTest() : cli_(HOST, PORT) {}
  7521. virtual void SetUp() {
  7522. t_ = thread([&]() {
  7523. svr_.bind_to_any_port(HOST);
  7524. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7525. ASSERT_TRUE(svr_.listen_after_bind());
  7526. });
  7527. svr_.wait_until_ready();
  7528. }
  7529. virtual void TearDown() {
  7530. svr_.stop();
  7531. t_.join();
  7532. }
  7533. Client cli_;
  7534. Server svr_;
  7535. thread t_;
  7536. };
  7537. TEST_F(ServerUpDownTest, QuickStartStop) {
  7538. // Should not crash, especially when run with
  7539. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7540. }
  7541. class PayloadMaxLengthTest : public ::testing::Test {
  7542. protected:
  7543. PayloadMaxLengthTest()
  7544. : cli_(HOST, PORT)
  7545. #ifdef CPPHTTPLIB_SSL_ENABLED
  7546. ,
  7547. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7548. #endif
  7549. {
  7550. #ifdef CPPHTTPLIB_SSL_ENABLED
  7551. cli_.enable_server_certificate_verification(false);
  7552. #endif
  7553. }
  7554. virtual void SetUp() {
  7555. svr_.set_payload_max_length(8);
  7556. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7557. res.set_content("test", "text/plain");
  7558. });
  7559. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7560. svr_.wait_until_ready();
  7561. }
  7562. virtual void TearDown() {
  7563. svr_.stop();
  7564. t_.join();
  7565. }
  7566. #ifdef CPPHTTPLIB_SSL_ENABLED
  7567. SSLClient cli_;
  7568. SSLServer svr_;
  7569. #else
  7570. Client cli_;
  7571. Server svr_;
  7572. #endif
  7573. thread t_;
  7574. };
  7575. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7576. auto res = cli_.Post("/test", "123456789", "text/plain");
  7577. ASSERT_TRUE(res);
  7578. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7579. res = cli_.Post("/test", "12345678", "text/plain");
  7580. ASSERT_TRUE(res);
  7581. EXPECT_EQ(StatusCode::OK_200, res->status);
  7582. }
  7583. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7584. // Test chunked encoding with payload exceeding the 8-byte limit
  7585. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7586. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7587. ASSERT_TRUE(res);
  7588. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7589. }
  7590. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7591. // Test chunked encoding with payload within the 8-byte limit
  7592. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7593. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7594. ASSERT_TRUE(res);
  7595. EXPECT_EQ(StatusCode::OK_200, res->status);
  7596. }
  7597. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7598. // Test using send_request to send chunked data exceeding payload limit
  7599. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7600. "Host: " +
  7601. std::string(HOST) + ":" + std::to_string(PORT) +
  7602. "\r\n"
  7603. "Transfer-Encoding: chunked\r\n"
  7604. "Connection: close\r\n"
  7605. "\r\n"
  7606. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7607. "0123456789\r\n"
  7608. "0\r\n" // End chunk
  7609. "\r\n";
  7610. std::string response;
  7611. bool result = send_request(1, chunked_request, &response);
  7612. if (!result) {
  7613. // If send_request fails, it might be because the server closed the
  7614. // connection due to payload limit enforcement, which is acceptable
  7615. SUCCEED()
  7616. << "Server rejected oversized chunked request (connection closed)";
  7617. } else {
  7618. // If we got a response, check if it's an error response or connection was
  7619. // closed early Short response length indicates connection was closed due to
  7620. // payload limit
  7621. if (response.length() <= 10) {
  7622. SUCCEED() << "Server closed connection for oversized chunked request";
  7623. } else {
  7624. // Check for error status codes
  7625. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7626. response.find("Payload Too Large") != std::string::npos ||
  7627. response.find("400") != std::string::npos);
  7628. }
  7629. }
  7630. }
  7631. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7632. // Test request without Content-Length header exceeding payload limit
  7633. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7634. "Host: " +
  7635. std::string(HOST) + ":" +
  7636. std::to_string(PORT) +
  7637. "\r\n"
  7638. "Connection: close\r\n"
  7639. "\r\n";
  7640. // Add payload exceeding the 8-byte limit
  7641. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7642. request_without_content_length += large_payload;
  7643. std::string response;
  7644. bool result = send_request(1, request_without_content_length, &response);
  7645. if (!result) {
  7646. // If send_request fails, server likely closed connection due to payload
  7647. // limit
  7648. SUCCEED() << "Server rejected oversized request without Content-Length "
  7649. "(connection closed)";
  7650. } else {
  7651. // Check if server responded with error or closed connection early
  7652. if (response.length() <= 10) {
  7653. SUCCEED() << "Server closed connection for oversized request without "
  7654. "Content-Length";
  7655. } else {
  7656. // Check for error status codes
  7657. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7658. response.find("Payload Too Large") != std::string::npos ||
  7659. response.find("400") != std::string::npos);
  7660. }
  7661. }
  7662. }
  7663. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7664. // Test request without Content-Length header within payload limit
  7665. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7666. "Host: " +
  7667. std::string(HOST) + ":" +
  7668. std::to_string(PORT) +
  7669. "\r\n"
  7670. "Connection: close\r\n"
  7671. "\r\n";
  7672. // Add payload within the 8-byte limit
  7673. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7674. request_without_content_length += small_payload;
  7675. std::string response;
  7676. bool result = send_request(1, request_without_content_length, &response);
  7677. // For requests without Content-Length, the server may have different behavior
  7678. // The key is that it should not reject due to payload limit for small
  7679. // payloads
  7680. if (result) {
  7681. // Check for any HTTP response (success or error, but not connection closed)
  7682. if (response.length() > 10) {
  7683. SUCCEED()
  7684. << "Server processed request without Content-Length within limit";
  7685. } else {
  7686. // Short response might indicate connection closed, which is acceptable
  7687. SUCCEED() << "Server closed connection for request without "
  7688. "Content-Length (acceptable behavior)";
  7689. }
  7690. } else {
  7691. // Connection failure might be due to protocol requirements
  7692. SUCCEED() << "Connection issue with request without Content-Length "
  7693. "(environment-specific)";
  7694. }
  7695. }
  7696. class LargePayloadMaxLengthTest : public ::testing::Test {
  7697. protected:
  7698. LargePayloadMaxLengthTest()
  7699. : cli_(HOST, PORT)
  7700. #ifdef CPPHTTPLIB_SSL_ENABLED
  7701. ,
  7702. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7703. #endif
  7704. {
  7705. #ifdef CPPHTTPLIB_SSL_ENABLED
  7706. cli_.enable_server_certificate_verification(false);
  7707. #endif
  7708. }
  7709. virtual void SetUp() {
  7710. // Set 10MB payload limit
  7711. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7712. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7713. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7714. res.set_content("Large payload test", "text/plain");
  7715. });
  7716. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7717. svr_.wait_until_ready();
  7718. }
  7719. virtual void TearDown() {
  7720. svr_.stop();
  7721. t_.join();
  7722. }
  7723. #ifdef CPPHTTPLIB_SSL_ENABLED
  7724. SSLClient cli_;
  7725. SSLServer svr_;
  7726. #else
  7727. Client cli_;
  7728. Server svr_;
  7729. #endif
  7730. thread t_;
  7731. };
  7732. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7733. // Test chunked encoding with payload within 10MB limit
  7734. std::string medium_payload(5 * 1024 * 1024,
  7735. 'A'); // 5MB payload, within 10MB limit
  7736. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7737. ASSERT_TRUE(res);
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. }
  7740. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7741. // Test chunked encoding with payload exceeding 10MB limit
  7742. std::string large_payload(12 * 1024 * 1024,
  7743. 'B'); // 12MB payload, exceeds 10MB limit
  7744. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7745. // Server may either return 413 or close the connection
  7746. if (res) {
  7747. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7748. } else {
  7749. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7750. }
  7751. }
  7752. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7753. // Test request without Content-Length header within 10MB limit
  7754. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7755. "Host: " +
  7756. std::string(HOST) + ":" +
  7757. std::to_string(PORT) +
  7758. "\r\n"
  7759. "Connection: close\r\n"
  7760. "\r\n";
  7761. // Add 1MB payload (within 10MB limit)
  7762. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7763. request_without_content_length += medium_payload;
  7764. std::string response;
  7765. bool result = send_request(5, request_without_content_length, &response);
  7766. if (result) {
  7767. // Should get a proper HTTP response for payloads within limit
  7768. if (response.length() > 10) {
  7769. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7770. "10MB limit";
  7771. } else {
  7772. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7773. "Content-Length)";
  7774. }
  7775. } else {
  7776. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7777. }
  7778. }
  7779. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7780. // Test request without Content-Length header exceeding 10MB limit
  7781. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7782. "Host: " +
  7783. std::string(HOST) + ":" +
  7784. std::to_string(PORT) +
  7785. "\r\n"
  7786. "Connection: close\r\n"
  7787. "\r\n";
  7788. // Add 12MB payload (exceeds 10MB limit)
  7789. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7790. request_without_content_length += large_payload;
  7791. std::string response;
  7792. bool result = send_request(10, request_without_content_length, &response);
  7793. if (!result) {
  7794. // Server should close connection due to payload limit
  7795. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7796. "(connection closed)";
  7797. } else {
  7798. // Check for error response
  7799. if (response.length() <= 10) {
  7800. SUCCEED()
  7801. << "Server closed connection for 12MB request exceeding 10MB limit";
  7802. } else {
  7803. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7804. response.find("Payload Too Large") != std::string::npos ||
  7805. response.find("400") != std::string::npos);
  7806. }
  7807. }
  7808. }
  7809. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7810. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7811. // path.
  7812. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7813. Server svr;
  7814. const size_t LIMIT = 64 * 1024; // 64KB
  7815. svr.set_payload_max_length(LIMIT);
  7816. size_t total = 0;
  7817. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7818. const ContentReader &content_reader) {
  7819. content_reader([&](const char * /*data*/, size_t len) {
  7820. total += len;
  7821. return true;
  7822. });
  7823. res.status = 200;
  7824. res.set_content("stream_ok", "text/plain");
  7825. });
  7826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7827. auto se = detail::scope_exit([&] {
  7828. svr.stop();
  7829. thread.join();
  7830. ASSERT_FALSE(svr.is_running());
  7831. });
  7832. svr.wait_until_ready();
  7833. // Prepare 256KB raw data and gzip-compress it
  7834. std::string raw(256 * 1024, 'A');
  7835. std::string gz;
  7836. {
  7837. z_stream zs{};
  7838. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7839. Z_DEFAULT_STRATEGY);
  7840. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7841. zs.avail_in = static_cast<uInt>(raw.size());
  7842. char outbuf[4096];
  7843. int ret;
  7844. do {
  7845. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7846. zs.avail_out = sizeof(outbuf);
  7847. ret = deflate(&zs, Z_FINISH);
  7848. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7849. } while (ret != Z_STREAM_END);
  7850. deflateEnd(&zs);
  7851. }
  7852. Client cli(HOST, PORT);
  7853. cli.set_connection_timeout(std::chrono::seconds(5));
  7854. Headers headers = {{"Content-Encoding", "gzip"}};
  7855. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7856. "application/octet-stream");
  7857. ASSERT_TRUE(res);
  7858. // Server must reject oversized decompressed payloads with 413.
  7859. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7860. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7861. EXPECT_LE(total, LIMIT);
  7862. }
  7863. #endif
  7864. // Regression test for DoS vulnerability: a malicious server sending a response
  7865. // without Content-Length header must not cause unbounded memory consumption on
  7866. // the client side. The client should stop reading after a reasonable limit,
  7867. // similar to the server-side set_payload_max_length protection.
  7868. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7869. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7870. #ifndef _WIN32
  7871. signal(SIGPIPE, SIG_IGN);
  7872. #endif
  7873. auto server_thread = std::thread([] {
  7874. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7875. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7876. default_socket_options(srv);
  7877. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7878. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7879. sockaddr_in addr{};
  7880. addr.sin_family = AF_INET;
  7881. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7882. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7883. int opt = 1;
  7884. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7885. #ifdef _WIN32
  7886. reinterpret_cast<const char *>(&opt),
  7887. #else
  7888. &opt,
  7889. #endif
  7890. sizeof(opt));
  7891. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7892. ::listen(srv, 1);
  7893. sockaddr_in cli_addr{};
  7894. socklen_t cli_len = sizeof(cli_addr);
  7895. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7896. if (cli != INVALID_SOCKET) {
  7897. char buf[4096];
  7898. ::recv(cli, buf, sizeof(buf), 0);
  7899. // Malicious response: no Content-Length, no chunked encoding
  7900. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7901. "Connection: close\r\n"
  7902. "\r\n";
  7903. ::send(cli,
  7904. #ifdef _WIN32
  7905. static_cast<const char *>(response_header.c_str()),
  7906. static_cast<int>(response_header.size()),
  7907. #else
  7908. response_header.c_str(), response_header.size(),
  7909. #endif
  7910. 0);
  7911. // Send 10MB of data
  7912. std::string chunk(64 * 1024, 'A');
  7913. size_t total_sent = 0;
  7914. while (total_sent < MALICIOUS_DATA_SIZE) {
  7915. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7916. auto sent = ::send(cli,
  7917. #ifdef _WIN32
  7918. static_cast<const char *>(chunk.c_str()),
  7919. static_cast<int>(to_send),
  7920. #else
  7921. chunk.c_str(), to_send,
  7922. #endif
  7923. 0);
  7924. if (sent <= 0) break;
  7925. total_sent += static_cast<size_t>(sent);
  7926. }
  7927. detail::close_socket(cli);
  7928. }
  7929. detail::close_socket(srv);
  7930. });
  7931. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7932. size_t total_read = 0;
  7933. {
  7934. Client cli("127.0.0.1", PORT + 2);
  7935. cli.set_read_timeout(5, 0);
  7936. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7937. auto stream = cli.open_stream("GET", "/malicious");
  7938. ASSERT_TRUE(stream.is_valid());
  7939. char buffer[64 * 1024];
  7940. ssize_t n;
  7941. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7942. total_read += static_cast<size_t>(n);
  7943. }
  7944. } // StreamHandle and Client destroyed here, closing the socket
  7945. server_thread.join();
  7946. // With set_payload_max_length, the client must stop reading before consuming
  7947. // all 10MB. The read loop should be cut off at or near the configured limit.
  7948. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7949. << "Client read " << total_read << " bytes, exceeding the configured "
  7950. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7951. }
  7952. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7953. // the entire response body without truncation.
  7954. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7955. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7956. #ifndef _WIN32
  7957. signal(SIGPIPE, SIG_IGN);
  7958. #endif
  7959. auto server_thread = std::thread([] {
  7960. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7961. default_socket_options(srv);
  7962. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7963. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7964. sockaddr_in addr{};
  7965. addr.sin_family = AF_INET;
  7966. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7967. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7968. int opt = 1;
  7969. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7970. #ifdef _WIN32
  7971. reinterpret_cast<const char *>(&opt),
  7972. #else
  7973. &opt,
  7974. #endif
  7975. sizeof(opt));
  7976. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7977. ::listen(srv, 1);
  7978. sockaddr_in cli_addr{};
  7979. socklen_t cli_len = sizeof(cli_addr);
  7980. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7981. if (cli != INVALID_SOCKET) {
  7982. char buf[4096];
  7983. ::recv(cli, buf, sizeof(buf), 0);
  7984. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7985. "Connection: close\r\n"
  7986. "\r\n";
  7987. ::send(cli,
  7988. #ifdef _WIN32
  7989. static_cast<const char *>(response_header.c_str()),
  7990. static_cast<int>(response_header.size()),
  7991. #else
  7992. response_header.c_str(), response_header.size(),
  7993. #endif
  7994. 0);
  7995. std::string chunk(64 * 1024, 'A');
  7996. size_t total_sent = 0;
  7997. while (total_sent < DATA_SIZE) {
  7998. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7999. auto sent = ::send(cli,
  8000. #ifdef _WIN32
  8001. static_cast<const char *>(chunk.c_str()),
  8002. static_cast<int>(to_send),
  8003. #else
  8004. chunk.c_str(), to_send,
  8005. #endif
  8006. 0);
  8007. if (sent <= 0) break;
  8008. total_sent += static_cast<size_t>(sent);
  8009. }
  8010. #ifdef _WIN32
  8011. ::shutdown(cli, SD_SEND);
  8012. #else
  8013. ::shutdown(cli, SHUT_WR);
  8014. #endif
  8015. // Drain until the client closes its end, ensuring all data is delivered
  8016. char drain[1024];
  8017. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8018. detail::close_socket(cli);
  8019. }
  8020. detail::close_socket(srv);
  8021. });
  8022. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8023. size_t total_read = 0;
  8024. {
  8025. Client cli("127.0.0.1", PORT + 2);
  8026. cli.set_read_timeout(5, 0);
  8027. cli.set_payload_max_length(0); // 0 means no limit
  8028. auto stream = cli.open_stream("GET", "/data");
  8029. ASSERT_TRUE(stream.is_valid());
  8030. char buffer[64 * 1024];
  8031. ssize_t n;
  8032. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8033. total_read += static_cast<size_t>(n);
  8034. }
  8035. }
  8036. server_thread.join();
  8037. EXPECT_EQ(total_read, DATA_SIZE)
  8038. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  8039. << " bytes without truncation, but only read " << total_read << " bytes.";
  8040. }
  8041. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  8042. // enormous Content-Length must not cause the client to pre-allocate a huge
  8043. // response body buffer. The reservation is capped at payload_max_length_, and
  8044. // the read itself fails when the body exceeds the limit.
  8045. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  8046. #ifndef _WIN32
  8047. signal(SIGPIPE, SIG_IGN);
  8048. #endif
  8049. auto server_thread = std::thread([] {
  8050. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8051. default_socket_options(srv);
  8052. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8053. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8054. sockaddr_in addr{};
  8055. addr.sin_family = AF_INET;
  8056. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8057. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8058. int opt = 1;
  8059. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8060. #ifdef _WIN32
  8061. reinterpret_cast<const char *>(&opt),
  8062. #else
  8063. &opt,
  8064. #endif
  8065. sizeof(opt));
  8066. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8067. ::listen(srv, 1);
  8068. sockaddr_in cli_addr{};
  8069. socklen_t cli_len = sizeof(cli_addr);
  8070. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8071. if (cli != INVALID_SOCKET) {
  8072. char buf[4096];
  8073. ::recv(cli, buf, sizeof(buf), 0);
  8074. // Malicious response: claim a 20GB body but send only a tiny payload.
  8075. std::string response = "HTTP/1.1 200 OK\r\n"
  8076. "Content-Length: 20000000000\r\n"
  8077. "\r\n"
  8078. "abc";
  8079. ::send(cli,
  8080. #ifdef _WIN32
  8081. static_cast<const char *>(response.c_str()),
  8082. static_cast<int>(response.size()),
  8083. #else
  8084. response.c_str(), response.size(),
  8085. #endif
  8086. 0);
  8087. detail::close_socket(cli);
  8088. }
  8089. detail::close_socket(srv);
  8090. });
  8091. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8092. {
  8093. Client cli("127.0.0.1", PORT + 2);
  8094. cli.set_read_timeout(5, 0);
  8095. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  8096. // result in a 20GB pre-allocation. The Get() call is expected to fail
  8097. // (server claims more bytes than payload_max_length permits), but it must
  8098. // not exhaust memory before getting there.
  8099. auto res = cli.Get("/malicious");
  8100. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  8101. }
  8102. server_thread.join();
  8103. }
  8104. // Verify that content_receiver bypasses the default payload_max_length,
  8105. // allowing streaming downloads larger than 100MB without requiring an explicit
  8106. // set_payload_max_length call.
  8107. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  8108. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8109. #ifndef _WIN32
  8110. signal(SIGPIPE, SIG_IGN);
  8111. #endif
  8112. auto server_thread = std::thread([] {
  8113. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8114. default_socket_options(srv);
  8115. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8116. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8117. sockaddr_in addr{};
  8118. addr.sin_family = AF_INET;
  8119. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8120. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8121. int opt = 1;
  8122. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8123. #ifdef _WIN32
  8124. reinterpret_cast<const char *>(&opt),
  8125. #else
  8126. &opt,
  8127. #endif
  8128. sizeof(opt));
  8129. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8130. ::listen(srv, 1);
  8131. sockaddr_in cli_addr{};
  8132. socklen_t cli_len = sizeof(cli_addr);
  8133. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8134. if (cli != INVALID_SOCKET) {
  8135. char buf[4096];
  8136. ::recv(cli, buf, sizeof(buf), 0);
  8137. // Response with Content-Length larger than default 100MB limit
  8138. auto content_length = std::to_string(DATA_SIZE);
  8139. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8140. "Content-Length: " +
  8141. content_length +
  8142. "\r\n"
  8143. "Connection: close\r\n"
  8144. "\r\n";
  8145. ::send(cli,
  8146. #ifdef _WIN32
  8147. static_cast<const char *>(response_header.c_str()),
  8148. static_cast<int>(response_header.size()),
  8149. #else
  8150. response_header.c_str(), response_header.size(),
  8151. #endif
  8152. 0);
  8153. std::string chunk(64 * 1024, 'A');
  8154. size_t total_sent = 0;
  8155. while (total_sent < DATA_SIZE) {
  8156. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8157. auto sent = ::send(cli,
  8158. #ifdef _WIN32
  8159. static_cast<const char *>(chunk.c_str()),
  8160. static_cast<int>(to_send),
  8161. #else
  8162. chunk.c_str(), to_send,
  8163. #endif
  8164. 0);
  8165. if (sent <= 0) break;
  8166. total_sent += static_cast<size_t>(sent);
  8167. }
  8168. detail::close_socket(cli);
  8169. }
  8170. detail::close_socket(srv);
  8171. });
  8172. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8173. size_t total_received = 0;
  8174. {
  8175. Client cli("127.0.0.1", PORT + 2);
  8176. cli.set_read_timeout(10, 0);
  8177. // Do NOT call set_payload_max_length — use the default 100MB limit
  8178. auto res =
  8179. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8180. total_received += data_length;
  8181. return true;
  8182. });
  8183. ASSERT_TRUE(res);
  8184. EXPECT_EQ(StatusCode::OK_200, res->status);
  8185. }
  8186. server_thread.join();
  8187. EXPECT_EQ(total_received, DATA_SIZE)
  8188. << "With content_receiver, the client should read all " << DATA_SIZE
  8189. << " bytes despite the default 100MB payload_max_length, but only read "
  8190. << total_received << " bytes.";
  8191. }
  8192. // Verify that an explicit set_payload_max_length smaller than the response is
  8193. // enforced even when a content_receiver is used.
  8194. TEST(ClientVulnerabilityTest,
  8195. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  8196. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8197. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  8198. #ifndef _WIN32
  8199. signal(SIGPIPE, SIG_IGN);
  8200. #endif
  8201. auto server_thread = std::thread([] {
  8202. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8203. default_socket_options(srv);
  8204. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8205. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8206. sockaddr_in addr{};
  8207. addr.sin_family = AF_INET;
  8208. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8209. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8210. int opt = 1;
  8211. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8212. #ifdef _WIN32
  8213. reinterpret_cast<const char *>(&opt),
  8214. #else
  8215. &opt,
  8216. #endif
  8217. sizeof(opt));
  8218. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8219. ::listen(srv, 1);
  8220. sockaddr_in cli_addr{};
  8221. socklen_t cli_len = sizeof(cli_addr);
  8222. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8223. if (cli != INVALID_SOCKET) {
  8224. char buf[4096];
  8225. ::recv(cli, buf, sizeof(buf), 0);
  8226. auto content_length = std::to_string(DATA_SIZE);
  8227. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8228. "Content-Length: " +
  8229. content_length +
  8230. "\r\n"
  8231. "Connection: close\r\n"
  8232. "\r\n";
  8233. ::send(cli,
  8234. #ifdef _WIN32
  8235. static_cast<const char *>(response_header.c_str()),
  8236. static_cast<int>(response_header.size()),
  8237. #else
  8238. response_header.c_str(), response_header.size(),
  8239. #endif
  8240. 0);
  8241. std::string chunk(64 * 1024, 'A');
  8242. size_t total_sent = 0;
  8243. while (total_sent < DATA_SIZE) {
  8244. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8245. auto sent = ::send(cli,
  8246. #ifdef _WIN32
  8247. static_cast<const char *>(chunk.c_str()),
  8248. static_cast<int>(to_send),
  8249. #else
  8250. chunk.c_str(), to_send,
  8251. #endif
  8252. 0);
  8253. if (sent <= 0) break;
  8254. total_sent += static_cast<size_t>(sent);
  8255. }
  8256. detail::close_socket(cli);
  8257. }
  8258. detail::close_socket(srv);
  8259. });
  8260. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8261. size_t total_received = 0;
  8262. {
  8263. Client cli("127.0.0.1", PORT + 2);
  8264. cli.set_read_timeout(10, 0);
  8265. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  8266. auto res =
  8267. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8268. total_received += data_length;
  8269. return true;
  8270. });
  8271. // Should fail because 200MB exceeds the explicit 150MB limit
  8272. EXPECT_FALSE(res);
  8273. }
  8274. server_thread.join();
  8275. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  8276. << "Client with content_receiver should respect the explicit "
  8277. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  8278. << total_received << " bytes.";
  8279. }
  8280. // Verify that an explicit set_payload_max_length larger than the response
  8281. // allows the content_receiver to read all data successfully.
  8282. TEST(ClientVulnerabilityTest,
  8283. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  8284. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  8285. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  8286. #ifndef _WIN32
  8287. signal(SIGPIPE, SIG_IGN);
  8288. #endif
  8289. auto server_thread = std::thread([] {
  8290. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8291. default_socket_options(srv);
  8292. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8293. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8294. sockaddr_in addr{};
  8295. addr.sin_family = AF_INET;
  8296. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8297. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8298. int opt = 1;
  8299. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8300. #ifdef _WIN32
  8301. reinterpret_cast<const char *>(&opt),
  8302. #else
  8303. &opt,
  8304. #endif
  8305. sizeof(opt));
  8306. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8307. ::listen(srv, 1);
  8308. sockaddr_in cli_addr{};
  8309. socklen_t cli_len = sizeof(cli_addr);
  8310. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8311. if (cli != INVALID_SOCKET) {
  8312. char buf[4096];
  8313. ::recv(cli, buf, sizeof(buf), 0);
  8314. auto content_length = std::to_string(DATA_SIZE);
  8315. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8316. "Content-Length: " +
  8317. content_length +
  8318. "\r\n"
  8319. "Connection: close\r\n"
  8320. "\r\n";
  8321. ::send(cli,
  8322. #ifdef _WIN32
  8323. static_cast<const char *>(response_header.c_str()),
  8324. static_cast<int>(response_header.size()),
  8325. #else
  8326. response_header.c_str(), response_header.size(),
  8327. #endif
  8328. 0);
  8329. std::string chunk(64 * 1024, 'A');
  8330. size_t total_sent = 0;
  8331. while (total_sent < DATA_SIZE) {
  8332. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8333. auto sent = ::send(cli,
  8334. #ifdef _WIN32
  8335. static_cast<const char *>(chunk.c_str()),
  8336. static_cast<int>(to_send),
  8337. #else
  8338. chunk.c_str(), to_send,
  8339. #endif
  8340. 0);
  8341. if (sent <= 0) break;
  8342. total_sent += static_cast<size_t>(sent);
  8343. }
  8344. #ifdef _WIN32
  8345. ::shutdown(cli, SD_SEND);
  8346. #else
  8347. ::shutdown(cli, SHUT_WR);
  8348. #endif
  8349. char drain[1024];
  8350. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8351. detail::close_socket(cli);
  8352. }
  8353. detail::close_socket(srv);
  8354. });
  8355. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8356. size_t total_received = 0;
  8357. {
  8358. Client cli("127.0.0.1", PORT + 2);
  8359. cli.set_read_timeout(10, 0);
  8360. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8361. auto res =
  8362. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8363. total_received += data_length;
  8364. return true;
  8365. });
  8366. ASSERT_TRUE(res);
  8367. EXPECT_EQ(StatusCode::OK_200, res->status);
  8368. }
  8369. server_thread.join();
  8370. EXPECT_EQ(total_received, DATA_SIZE)
  8371. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8372. << " bytes (larger than " << DATA_SIZE
  8373. << " bytes response), content_receiver should read all data, but only "
  8374. "read "
  8375. << total_received << " bytes.";
  8376. }
  8377. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8378. // Regression test for "zip bomb" attack on the client side: a malicious server
  8379. // sends a small gzip-compressed response that decompresses to a huge payload.
  8380. // The client must enforce payload_max_length on the decompressed size.
  8381. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8382. constexpr size_t DECOMPRESSED_SIZE =
  8383. 10 * 1024 * 1024; // 10MB after decompression
  8384. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8385. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8386. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8387. std::string compressed;
  8388. {
  8389. httplib::detail::gzip_compressor compressor;
  8390. bool ok =
  8391. compressor.compress(uncompressed.data(), uncompressed.size(),
  8392. /*last=*/true, [&](const char *buf, size_t len) {
  8393. compressed.append(buf, len);
  8394. return true;
  8395. });
  8396. ASSERT_TRUE(ok);
  8397. }
  8398. // Sanity: compressed data should be much smaller than the decompressed size
  8399. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8400. #ifndef _WIN32
  8401. signal(SIGPIPE, SIG_IGN);
  8402. #endif
  8403. // Set up the listening socket in the main thread so the server is guaranteed
  8404. // to be ready before the client connects (eliminates race condition).
  8405. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8406. default_socket_options(srv);
  8407. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8408. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8409. sockaddr_in addr{};
  8410. addr.sin_family = AF_INET;
  8411. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8412. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8413. int opt = 1;
  8414. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8415. #ifdef _WIN32
  8416. reinterpret_cast<const char *>(&opt),
  8417. #else
  8418. &opt,
  8419. #endif
  8420. sizeof(opt));
  8421. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8422. ASSERT_EQ(0, ::listen(srv, 1));
  8423. auto server_thread = std::thread([&compressed, srv] {
  8424. sockaddr_in cli_addr{};
  8425. socklen_t cli_len = sizeof(cli_addr);
  8426. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8427. if (cli != INVALID_SOCKET) {
  8428. // Read the full HTTP request (until \r\n\r\n)
  8429. char buf[4096];
  8430. size_t total = 0;
  8431. while (total < sizeof(buf)) {
  8432. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8433. if (n <= 0) break;
  8434. total += static_cast<size_t>(n);
  8435. // Check for end of headers
  8436. if (total >= 4) {
  8437. std::string req(buf, total);
  8438. if (req.find("\r\n\r\n") != std::string::npos) break;
  8439. }
  8440. }
  8441. // Malicious response: gzip-compressed body, no Content-Length
  8442. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8443. "Content-Encoding: gzip\r\n"
  8444. "Connection: close\r\n"
  8445. "\r\n";
  8446. ::send(cli,
  8447. #ifdef _WIN32
  8448. static_cast<const char *>(response_header.c_str()),
  8449. static_cast<int>(response_header.size()),
  8450. #else
  8451. response_header.c_str(), response_header.size(),
  8452. #endif
  8453. 0);
  8454. // Send the compressed payload (small on the wire, huge when decompressed)
  8455. size_t total_sent = 0;
  8456. while (total_sent < compressed.size()) {
  8457. auto to_send = std::min(compressed.size() - total_sent,
  8458. static_cast<size_t>(64 * 1024));
  8459. auto sent =
  8460. ::send(cli,
  8461. #ifdef _WIN32
  8462. static_cast<const char *>(compressed.c_str() + total_sent),
  8463. static_cast<int>(to_send),
  8464. #else
  8465. compressed.c_str() + total_sent, to_send,
  8466. #endif
  8467. 0);
  8468. if (sent <= 0) break;
  8469. total_sent += static_cast<size_t>(sent);
  8470. }
  8471. detail::close_socket(cli);
  8472. }
  8473. });
  8474. auto se = detail::scope_exit([&] {
  8475. detail::close_socket(srv);
  8476. server_thread.join();
  8477. });
  8478. size_t total_decompressed = 0;
  8479. {
  8480. Client cli("127.0.0.1", PORT + 3);
  8481. cli.set_read_timeout(5, 0);
  8482. cli.set_decompress(true);
  8483. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8484. auto stream = cli.open_stream("GET", "/zipbomb");
  8485. ASSERT_TRUE(stream.is_valid());
  8486. char buffer[64 * 1024];
  8487. ssize_t n;
  8488. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8489. total_decompressed += static_cast<size_t>(n);
  8490. }
  8491. }
  8492. // The decompressed size must be capped by payload_max_length. Without
  8493. // protection, the client would decompress the full 10MB from a tiny
  8494. // compressed payload, enabling a zip bomb DoS attack.
  8495. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8496. << "Client decompressed " << total_decompressed
  8497. << " bytes from a gzip response. The decompressed size should be "
  8498. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8499. }
  8500. #endif
  8501. TEST(HostAndPortPropertiesTest, NoSSL) {
  8502. httplib::Client cli("www.google.com", 1234);
  8503. ASSERT_EQ("www.google.com", cli.host());
  8504. ASSERT_EQ(1234, cli.port());
  8505. }
  8506. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8507. httplib::Client cli("www.google.com:1234");
  8508. ASSERT_EQ("www.google.com", cli.host());
  8509. ASSERT_EQ(1234, cli.port());
  8510. }
  8511. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8512. // Port number that overflows int — should not crash, client becomes invalid
  8513. httplib::Client cli("http://www.google.com:99999999999999999999");
  8514. ASSERT_FALSE(cli.is_valid());
  8515. }
  8516. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8517. // Port 99999 exceeds valid range (1-65535) — should not crash
  8518. httplib::Client cli("http://www.google.com:99999");
  8519. ASSERT_FALSE(cli.is_valid());
  8520. }
  8521. #ifdef CPPHTTPLIB_SSL_ENABLED
  8522. TEST(HostAndPortPropertiesTest, SSL) {
  8523. httplib::SSLClient cli("www.google.com");
  8524. ASSERT_EQ("www.google.com", cli.host());
  8525. ASSERT_EQ(443, cli.port());
  8526. }
  8527. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8528. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8529. std::string cert;
  8530. read_file(CA_CERT_FILE, cert);
  8531. httplib::SSLClient httplib_client("www.google.com");
  8532. // Load CA store first time
  8533. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8534. // Load CA store second time (update)
  8535. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8536. // Verify client is still valid and can make connections
  8537. httplib_client.enable_server_certificate_verification(true);
  8538. auto res = httplib_client.Get("/");
  8539. ASSERT_TRUE(res);
  8540. // Google may return 200 or 301 depending on various factors
  8541. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8542. res->status == StatusCode::MovedPermanently_301);
  8543. }
  8544. TEST(SSLClientTest, ServerNameIndication_Online) {
  8545. auto host = "httpbingo.org";
  8546. auto path = std::string{"/get"};
  8547. SSLClient cli(host, 443);
  8548. auto res = cli.Get(path);
  8549. ASSERT_TRUE(res);
  8550. ASSERT_EQ(StatusCode::OK_200, res->status);
  8551. }
  8552. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8553. // Use a site that will cause SSL verification failure due to self-signed cert
  8554. SSLClient cli("self-signed.badssl.com", 443);
  8555. cli.enable_server_certificate_verification(true);
  8556. auto res = cli.Get("/");
  8557. ASSERT_TRUE(!res);
  8558. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8559. // Verify backend error is captured for SSLServerVerification
  8560. // This occurs when certificate verification fails
  8561. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8562. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8563. EXPECT_NE(0UL, res.ssl_backend_error());
  8564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8565. // For OpenSSL, ssl_error is 0 for verification errors
  8566. EXPECT_EQ(0, res.ssl_error());
  8567. #if !defined(_WIN32) || \
  8568. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8569. // On non-Windows or when Windows Schannel is disabled, the error comes
  8570. // from OpenSSL's verification
  8571. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8572. res.ssl_backend_error());
  8573. #endif
  8574. #endif
  8575. }
  8576. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8577. // Use a site where hostname doesn't match the certificate
  8578. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8579. SSLClient cli("wrong.host.badssl.com", 443);
  8580. cli.enable_server_certificate_verification(true);
  8581. cli.enable_server_hostname_verification(true);
  8582. auto res = cli.Get("/");
  8583. ASSERT_TRUE(!res);
  8584. // The error type depends on when hostname verification occurs:
  8585. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8586. // - Mbed TLS: SSLServerVerification (during handshake)
  8587. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8588. res.error() == Error::SSLServerVerification);
  8589. // Verify backend error is captured for hostname verification failure
  8590. EXPECT_NE(0UL, res.ssl_backend_error());
  8591. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8592. // For OpenSSL, ssl_error is 0 for verification errors
  8593. EXPECT_EQ(0, res.ssl_error());
  8594. #if !defined(_WIN32) || \
  8595. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8596. // On non-Windows or when Windows Schannel is disabled, the error comes
  8597. // from OpenSSL's hostname verification
  8598. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8599. res.ssl_backend_error());
  8600. #endif
  8601. #endif
  8602. }
  8603. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8604. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8605. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8606. SSLClient cli("www.google.com", 443);
  8607. cli.enable_server_certificate_verification(true);
  8608. auto res = cli.Get("/");
  8609. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8610. }
  8611. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8612. SSLClient cli("www.google.com", 443);
  8613. cli.enable_server_certificate_verification(true);
  8614. cli.enable_windows_certificate_verification(false);
  8615. auto res = cli.Get("/");
  8616. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8617. }
  8618. #endif
  8619. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8620. Client cli("https://google.com");
  8621. auto res = cli.Get("/");
  8622. ASSERT_TRUE(res);
  8623. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8624. }
  8625. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8626. SSLClient cli("google.com");
  8627. cli.set_ca_cert_path(CA_CERT_FILE);
  8628. auto res = cli.Get("/");
  8629. ASSERT_TRUE(res);
  8630. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8631. }
  8632. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8633. SSLClient cli("google.com");
  8634. cli.enable_server_certificate_verification(true);
  8635. cli.set_ca_cert_path("hello");
  8636. auto res = cli.Get("/");
  8637. ASSERT_TRUE(!res);
  8638. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8639. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8640. // should be set
  8641. EXPECT_EQ(0, res.ssl_error());
  8642. // Verify backend error is captured for SSLLoadingCerts
  8643. // This error occurs when loading CA certificates fails
  8644. EXPECT_NE(0UL, res.ssl_backend_error());
  8645. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8646. // OpenSSL specific error codes:
  8647. // > openssl errstr 0x80000002
  8648. // error:80000002:system library::No such file or directory
  8649. // > openssl errstr 0xA000126
  8650. // error:0A000126:SSL routines::unexpected eof while reading
  8651. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8652. res.ssl_backend_error() == 0xA000126);
  8653. #endif
  8654. }
  8655. TEST(SSLClientTest, ServerCertificateVerification4) {
  8656. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8657. ASSERT_TRUE(svr.is_valid());
  8658. svr.Get("/test", [&](const Request &, Response &res) {
  8659. res.set_content("test", "text/plain");
  8660. svr.stop();
  8661. ASSERT_TRUE(true);
  8662. });
  8663. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8664. auto se = detail::scope_exit([&] {
  8665. t.join();
  8666. ASSERT_FALSE(svr.is_running());
  8667. });
  8668. svr.wait_until_ready();
  8669. SSLClient cli("127.0.0.1", PORT);
  8670. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8671. cli.enable_server_certificate_verification(true);
  8672. cli.set_connection_timeout(30);
  8673. auto res = cli.Get("/test");
  8674. ASSERT_TRUE(res);
  8675. ASSERT_EQ(StatusCode::OK_200, res->status);
  8676. }
  8677. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8678. std::string cert;
  8679. read_file(CA_CERT_FILE, cert);
  8680. SSLClient cli("google.com");
  8681. cli.load_ca_cert_store(cert.data(), cert.size());
  8682. const auto res = cli.Get("/");
  8683. ASSERT_TRUE(res);
  8684. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8685. }
  8686. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8687. // clang-format off
  8688. static constexpr char cert[] =
  8689. "GlobalSign Root CA\n"
  8690. "==================\n"
  8691. "-----BEGIN CERTIFICATE-----\n"
  8692. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8693. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8694. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8695. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8696. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8697. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8698. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8699. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8700. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8701. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8702. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8703. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8704. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8705. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8706. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8707. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8708. "-----END CERTIFICATE-----\n";
  8709. // clang-format on
  8710. SSLClient cli("google.com");
  8711. cli.load_ca_cert_store(cert, sizeof(cert));
  8712. const auto res = cli.Get("/");
  8713. ASSERT_TRUE(res);
  8714. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8715. }
  8716. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8717. SSLClient cli("www.youtube.com");
  8718. cli.set_ca_cert_path(CA_CERT_FILE);
  8719. cli.enable_server_certificate_verification(true);
  8720. cli.set_follow_location(true);
  8721. auto res = cli.Get("/");
  8722. ASSERT_TRUE(res);
  8723. ASSERT_EQ(StatusCode::OK_200, res->status);
  8724. }
  8725. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8726. SSLClient cli("wWw.YouTube.Com");
  8727. cli.set_ca_cert_path(CA_CERT_FILE);
  8728. cli.enable_server_certificate_verification(true);
  8729. cli.enable_server_hostname_verification(true);
  8730. cli.set_follow_location(true);
  8731. auto res = cli.Get("/");
  8732. ASSERT_TRUE(res);
  8733. ASSERT_EQ(StatusCode::OK_200, res->status);
  8734. }
  8735. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8736. SSLClient cli("gOoGlE.COm");
  8737. cli.enable_server_certificate_verification(true);
  8738. cli.enable_server_hostname_verification(true);
  8739. cli.set_follow_location(true);
  8740. auto res = cli.Get("/");
  8741. ASSERT_TRUE(res);
  8742. ASSERT_EQ(StatusCode::OK_200, res->status);
  8743. }
  8744. TEST(SSLClientTest, Issue2004_Online) {
  8745. Client client("https://google.com");
  8746. client.set_follow_location(true);
  8747. auto res = client.Get("/");
  8748. ASSERT_TRUE(res);
  8749. ASSERT_EQ(StatusCode::OK_200, res->status);
  8750. auto body = res->body;
  8751. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8752. }
  8753. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8754. // Create SSLClient with invalid cert/key to make is_valid() return false
  8755. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8756. "nonexistent_key.pem");
  8757. // is_valid() should be false due to cert loading failure
  8758. ASSERT_FALSE(cli.is_valid());
  8759. auto res = cli.Get("/");
  8760. ASSERT_FALSE(res);
  8761. EXPECT_EQ(Error::SSLConnection, res.error());
  8762. }
  8763. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8764. // Test for Issue #2251: SSL error not properly reported when client cert
  8765. // and key paths are swapped or mismatched
  8766. // This simulates the scenario where user accidentally swaps the cert and key
  8767. // files
  8768. // Using client cert file as private key and vice versa (completely wrong)
  8769. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8770. // Should fail validation due to cert/key mismatch
  8771. ASSERT_FALSE(cli.is_valid());
  8772. // Attempt to make a request should fail with proper error
  8773. auto res = cli.Get("/");
  8774. ASSERT_FALSE(res);
  8775. EXPECT_EQ(Error::SSLConnection, res.error());
  8776. // SSL error should be recorded in the Result object (this is the key fix for
  8777. // Issue #2251)
  8778. auto backend_error = res.ssl_backend_error();
  8779. EXPECT_NE(0u, backend_error);
  8780. }
  8781. // Tests cert/key mismatch detection at the TLS context level
  8782. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8783. // Test that using mismatched cert/key causes connection failure.
  8784. // We verify this at the SSLClient level rather than through internal
  8785. // TLS API functions.
  8786. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8787. cli.enable_server_certificate_verification(false);
  8788. cli.set_connection_timeout(2);
  8789. // The mismatch should cause a connection or handshake error
  8790. auto res = cli.Get("/test");
  8791. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8792. // Either way, the request should fail
  8793. EXPECT_FALSE(res);
  8794. }
  8795. #endif
  8796. #if 0
  8797. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8798. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8799. ASSERT_TRUE(cli != nullptr);
  8800. cli->set_address_family(AF_INET6);
  8801. cli->set_interface("en0");
  8802. auto res = cli->Get("/get");
  8803. ASSERT_TRUE(res);
  8804. ASSERT_EQ(StatusCode::OK_200, res->status);
  8805. }
  8806. #endif
  8807. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8808. #ifdef CPPHTTPLIB_SSL_ENABLED
  8809. void ClientCertPresent(
  8810. const std::string &client_cert_file,
  8811. const std::string &client_private_key_file,
  8812. const std::string &client_encrypted_private_key_pass = std::string()) {
  8813. using namespace httplib::tls;
  8814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8815. CLIENT_CA_CERT_DIR);
  8816. ASSERT_TRUE(svr.is_valid());
  8817. svr.Get("/test", [&](const Request &req, Response &res) {
  8818. res.set_content("test", "text/plain");
  8819. auto cert = req.peer_cert();
  8820. ASSERT_TRUE(static_cast<bool>(cert));
  8821. std::string common_name = cert.subject_cn();
  8822. EXPECT_EQ("Common Name", common_name);
  8823. });
  8824. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8825. auto se = detail::scope_exit([&] {
  8826. svr.stop();
  8827. t.join();
  8828. ASSERT_FALSE(svr.is_running());
  8829. });
  8830. svr.wait_until_ready();
  8831. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8832. client_encrypted_private_key_pass);
  8833. cli.enable_server_certificate_verification(false);
  8834. cli.set_connection_timeout(30);
  8835. auto res = cli.Get("/test");
  8836. ASSERT_TRUE(res);
  8837. ASSERT_EQ(StatusCode::OK_200, res->status);
  8838. }
  8839. TEST(SSLClientServerTest, ClientCertPresent) {
  8840. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8841. }
  8842. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8843. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8844. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8845. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8846. }
  8847. // PEM memory-based constructor tests (works with all TLS backends)
  8848. void PemMemoryClientCertPresent(
  8849. const std::string &client_cert_file,
  8850. const std::string &client_private_key_file,
  8851. const std::string &client_encrypted_private_key_pass = std::string()) {
  8852. // Read PEM files into memory
  8853. std::string server_cert_pem, server_key_pem;
  8854. std::string client_ca_pem;
  8855. std::string client_cert_pem, client_key_pem;
  8856. read_file(SERVER_CERT_FILE, server_cert_pem);
  8857. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8858. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8859. read_file(client_cert_file, client_cert_pem);
  8860. read_file(client_private_key_file, client_key_pem);
  8861. // Create server with PEM memory
  8862. SSLServer::PemMemory server_pem = {
  8863. server_cert_pem.c_str(),
  8864. server_cert_pem.size(),
  8865. server_key_pem.c_str(),
  8866. server_key_pem.size(),
  8867. client_ca_pem.c_str(),
  8868. client_ca_pem.size(),
  8869. nullptr // no password for server key
  8870. };
  8871. SSLServer svr(server_pem);
  8872. ASSERT_TRUE(svr.is_valid());
  8873. svr.Get("/test", [&](const Request &, Response &res) {
  8874. res.set_content("test", "text/plain");
  8875. });
  8876. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8877. auto se = detail::scope_exit([&] {
  8878. svr.stop();
  8879. t.join();
  8880. ASSERT_FALSE(svr.is_running());
  8881. });
  8882. svr.wait_until_ready();
  8883. // Create client with PEM memory
  8884. const char *password = client_encrypted_private_key_pass.empty()
  8885. ? nullptr
  8886. : client_encrypted_private_key_pass.c_str();
  8887. SSLClient::PemMemory client_pem = {
  8888. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8889. client_key_pem.size(), password};
  8890. SSLClient cli(HOST, PORT, client_pem);
  8891. cli.enable_server_certificate_verification(false);
  8892. cli.set_connection_timeout(30);
  8893. auto res = cli.Get("/test");
  8894. ASSERT_TRUE(res);
  8895. ASSERT_EQ(StatusCode::OK_200, res->status);
  8896. }
  8897. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8898. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8899. }
  8900. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8901. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8902. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8903. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8904. }
  8905. TEST(SSLClientServerTest, ClientCertMissing) {
  8906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8907. CLIENT_CA_CERT_DIR);
  8908. ASSERT_TRUE(svr.is_valid());
  8909. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8910. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8911. auto se = detail::scope_exit([&] {
  8912. svr.stop();
  8913. t.join();
  8914. ASSERT_FALSE(svr.is_running());
  8915. });
  8916. svr.wait_until_ready();
  8917. SSLClient cli(HOST, PORT);
  8918. cli.set_connection_timeout(30);
  8919. auto res = cli.Get("/test");
  8920. ASSERT_TRUE(!res);
  8921. // When client cert is missing and server requires it, connection fails
  8922. // Error type depends on backend implementation
  8923. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8924. res.error() == Error::SSLConnection);
  8925. // Verify backend error is captured
  8926. // Note: This test may have different error codes depending on the exact
  8927. // verification failure
  8928. EXPECT_NE(0UL, res.ssl_backend_error());
  8929. }
  8930. TEST(SSLClientServerTest, TrustDirOptional) {
  8931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8932. ASSERT_TRUE(svr.is_valid());
  8933. svr.Get("/test", [&](const Request &, Response &res) {
  8934. res.set_content("test", "text/plain");
  8935. });
  8936. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8937. auto se = detail::scope_exit([&] {
  8938. svr.stop();
  8939. t.join();
  8940. ASSERT_FALSE(svr.is_running());
  8941. });
  8942. svr.wait_until_ready();
  8943. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8944. cli.enable_server_certificate_verification(false);
  8945. cli.set_connection_timeout(30);
  8946. auto res = cli.Get("/test");
  8947. ASSERT_TRUE(res);
  8948. ASSERT_EQ(StatusCode::OK_200, res->status);
  8949. }
  8950. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8951. class NoListenSSLServer : public SSLServer {
  8952. public:
  8953. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8954. const char *client_ca_cert_file_path,
  8955. const char *client_ca_cert_dir_path = nullptr)
  8956. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8957. client_ca_cert_dir_path),
  8958. stop_(false) {}
  8959. std::atomic_bool stop_;
  8960. private:
  8961. bool process_and_close_socket(socket_t /*sock*/) override {
  8962. // Don't create SSL context
  8963. while (!stop_.load()) {
  8964. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8965. }
  8966. return true;
  8967. }
  8968. };
  8969. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8970. CLIENT_CA_CERT_FILE);
  8971. ASSERT_TRUE(svr.is_valid());
  8972. svr.Get("/test", [&](const Request &, Response &res) {
  8973. res.set_content("test", "text/plain");
  8974. });
  8975. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8976. auto se = detail::scope_exit([&] {
  8977. svr.stop_ = true;
  8978. svr.stop();
  8979. t.join();
  8980. ASSERT_FALSE(svr.is_running());
  8981. });
  8982. svr.wait_until_ready();
  8983. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8984. cli.enable_server_certificate_verification(false);
  8985. cli.set_connection_timeout(1);
  8986. auto res = cli.Get("/test");
  8987. ASSERT_TRUE(!res);
  8988. EXPECT_EQ(Error::SSLConnection, res.error());
  8989. // Timeout results in WantRead error code (maps to backend-specific value)
  8990. EXPECT_NE(0, res.ssl_error());
  8991. }
  8992. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8993. // Test SSLServer with client certificate verification using the standard
  8994. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8996. CLIENT_CA_CERT_DIR);
  8997. ASSERT_TRUE(svr.is_valid());
  8998. svr.Get("/test", [&](const Request &req, Response &res) {
  8999. res.set_content("test", "text/plain");
  9000. auto cert = req.peer_cert();
  9001. ASSERT_TRUE(static_cast<bool>(cert));
  9002. auto common_name = cert.subject_cn();
  9003. EXPECT_EQ("Common Name", common_name);
  9004. });
  9005. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9006. auto se = detail::scope_exit([&] {
  9007. svr.stop();
  9008. t.join();
  9009. ASSERT_FALSE(svr.is_running());
  9010. });
  9011. svr.wait_until_ready();
  9012. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9013. cli.enable_server_certificate_verification(false);
  9014. cli.set_connection_timeout(30);
  9015. auto res = cli.Get("/test");
  9016. ASSERT_TRUE(res);
  9017. ASSERT_EQ(StatusCode::OK_200, res->status);
  9018. }
  9019. // Test verify_hostname for both OpenSSL and MbedTLS backends
  9020. // Verifies that wildcard matching and exact matching work consistently
  9021. TEST(SSLClientServerTest, TlsVerifyHostname) {
  9022. using namespace httplib::tls;
  9023. // We need a running server to test against
  9024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9025. ASSERT_TRUE(svr.is_valid());
  9026. svr.Get("/test", [](const Request &, Response &res) {
  9027. res.set_content("ok", "text/plain");
  9028. });
  9029. thread t([&]() { svr.listen(HOST, PORT); });
  9030. auto se = detail::scope_exit([&] {
  9031. svr.stop();
  9032. t.join();
  9033. });
  9034. svr.wait_until_ready();
  9035. bool verify_callback_called = false;
  9036. bool verify_result_wrong = false;
  9037. SSLClient cli(HOST, PORT);
  9038. cli.enable_server_certificate_verification(true);
  9039. cli.set_ca_cert_path(CA_CERT_FILE);
  9040. cli.set_connection_timeout(5);
  9041. // Note: Test certificate has CN="Common Name", not "localhost"
  9042. bool verify_result_cn = false;
  9043. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9044. verify_callback_called = true;
  9045. if (!ctx.cert) return false;
  9046. // Test 1: "Common Name" should match (our test server cert CN)
  9047. verify_result_cn = ctx.check_hostname("Common Name");
  9048. // Test 2: wrong hostname should not match
  9049. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  9050. return true; // Accept for the purpose of this test
  9051. });
  9052. auto res = cli.Get("/test");
  9053. // The request may succeed or fail depending on cert configuration
  9054. // but the callback should have been called
  9055. ASSERT_TRUE(verify_callback_called)
  9056. << "Verify callback should have been called";
  9057. // CN="Common Name" should match our test certificate
  9058. //
  9059. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  9060. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  9061. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  9062. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  9063. // <openssl/base.h>, which is included transitively when
  9064. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  9065. #if defined(OPENSSL_IS_BORINGSSL)
  9066. EXPECT_FALSE(verify_result_cn)
  9067. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  9068. #else
  9069. EXPECT_TRUE(verify_result_cn)
  9070. << "verify_hostname should match 'Common Name' (certificate CN)";
  9071. #endif
  9072. // Wrong hostname should not match
  9073. EXPECT_FALSE(verify_result_wrong)
  9074. << "verify_hostname should not match 'wronghost.example.com'";
  9075. }
  9076. #endif
  9077. // mbedTLS-specific callback constructor test
  9078. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  9079. #ifdef CPPHTTPLIB_SSL_ENABLED
  9080. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  9081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9082. ASSERT_TRUE(svr.is_valid());
  9083. // Set up a handler to verify client certificate is present
  9084. bool client_cert_verified = false;
  9085. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9086. // Verify that client certificate was provided
  9087. client_cert_verified = true;
  9088. res.set_content("success", "text/plain");
  9089. });
  9090. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9091. auto se = detail::scope_exit([&] {
  9092. svr.stop();
  9093. t.join();
  9094. ASSERT_FALSE(svr.is_running());
  9095. });
  9096. svr.wait_until_ready();
  9097. // Client with certificate
  9098. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9099. cli.enable_server_certificate_verification(false);
  9100. cli.set_connection_timeout(30);
  9101. auto res = cli.Get("/test");
  9102. ASSERT_TRUE(res);
  9103. ASSERT_EQ(StatusCode::OK_200, res->status);
  9104. ASSERT_TRUE(client_cert_verified);
  9105. EXPECT_EQ("success", res->body);
  9106. }
  9107. #endif
  9108. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  9109. // backends
  9110. #ifdef CPPHTTPLIB_SSL_ENABLED
  9111. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  9112. using namespace httplib::tls;
  9113. // Test that when client CA cert file is provided,
  9114. // the server properly requests and validates client certificates
  9115. // Create a server with client authentication
  9116. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  9117. ASSERT_TRUE(svr.is_valid());
  9118. bool handler_called = false;
  9119. svr.Get("/test", [&](const Request &req, Response &res) {
  9120. handler_called = true;
  9121. // Verify that a client certificate was provided
  9122. auto cert = req.peer_cert();
  9123. ASSERT_TRUE(static_cast<bool>(cert));
  9124. // Get the issuer name
  9125. std::string issuer_str = cert.issuer_name();
  9126. ASSERT_FALSE(issuer_str.empty());
  9127. // The client certificate should be issued by our test CA
  9128. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  9129. res.set_content("authenticated", "text/plain");
  9130. });
  9131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9132. auto se = detail::scope_exit([&] {
  9133. svr.stop();
  9134. t.join();
  9135. ASSERT_FALSE(svr.is_running());
  9136. });
  9137. svr.wait_until_ready();
  9138. // Connect with a client certificate issued by the CA
  9139. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9140. cli.enable_server_certificate_verification(false);
  9141. cli.set_connection_timeout(30);
  9142. auto res = cli.Get("/test");
  9143. ASSERT_TRUE(res);
  9144. ASSERT_EQ(StatusCode::OK_200, res->status);
  9145. ASSERT_TRUE(handler_called);
  9146. EXPECT_EQ("authenticated", res->body);
  9147. }
  9148. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  9149. using namespace httplib::tls;
  9150. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9151. ASSERT_TRUE(svr.is_valid());
  9152. svr.Get("/test", [](const Request &, Response &res) {
  9153. res.set_content("ok", "text/plain");
  9154. });
  9155. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9156. auto se = detail::scope_exit([&] {
  9157. svr.stop();
  9158. t.join();
  9159. });
  9160. svr.wait_until_ready();
  9161. SSLClient cli(HOST, PORT);
  9162. cli.enable_server_certificate_verification(false);
  9163. cli.set_connection_timeout(30);
  9164. bool cert_checked = false;
  9165. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9166. if (ctx.cert) {
  9167. auto sans = ctx.sans();
  9168. // Test certificate may or may not have SANs - just verify the API
  9169. // works If SANs exist, verify the types are valid
  9170. for (const auto &san : sans) {
  9171. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  9172. san.type == SanType::EMAIL || san.type == SanType::URI ||
  9173. san.type == SanType::OTHER);
  9174. EXPECT_FALSE(san.value.empty());
  9175. }
  9176. cert_checked = true;
  9177. }
  9178. return true;
  9179. });
  9180. auto res = cli.Get("/test");
  9181. ASSERT_TRUE(res);
  9182. EXPECT_TRUE(cert_checked);
  9183. }
  9184. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  9185. using namespace httplib::tls;
  9186. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9187. ASSERT_TRUE(svr.is_valid());
  9188. svr.Get("/test", [](const Request &, Response &res) {
  9189. res.set_content("ok", "text/plain");
  9190. });
  9191. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9192. auto se = detail::scope_exit([&] {
  9193. svr.stop();
  9194. t.join();
  9195. });
  9196. svr.wait_until_ready();
  9197. SSLClient cli(HOST, PORT);
  9198. cli.enable_server_certificate_verification(false);
  9199. cli.set_connection_timeout(30);
  9200. bool validity_checked = false;
  9201. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9202. if (ctx.cert) {
  9203. time_t not_before = 0, not_after = 0;
  9204. bool result = ctx.validity(not_before, not_after);
  9205. EXPECT_TRUE(result);
  9206. // Verify that not_before < now < not_after for a valid cert
  9207. time_t now = time(nullptr);
  9208. EXPECT_LT(not_before, now);
  9209. EXPECT_GT(not_after, now);
  9210. validity_checked = true;
  9211. }
  9212. return true;
  9213. });
  9214. auto res = cli.Get("/test");
  9215. ASSERT_TRUE(res);
  9216. EXPECT_TRUE(validity_checked);
  9217. }
  9218. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  9219. using namespace httplib::tls;
  9220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9221. ASSERT_TRUE(svr.is_valid());
  9222. svr.Get("/test", [](const Request &, Response &res) {
  9223. res.set_content("ok", "text/plain");
  9224. });
  9225. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9226. auto se = detail::scope_exit([&] {
  9227. svr.stop();
  9228. t.join();
  9229. });
  9230. svr.wait_until_ready();
  9231. SSLClient cli(HOST, PORT);
  9232. cli.enable_server_certificate_verification(false);
  9233. cli.set_connection_timeout(30);
  9234. bool serial_checked = false;
  9235. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9236. if (ctx.cert) {
  9237. std::string serial = ctx.serial();
  9238. EXPECT_FALSE(serial.empty());
  9239. // Serial should be a hex string
  9240. for (char c : serial) {
  9241. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  9242. (c >= 'a' && c <= 'f'));
  9243. }
  9244. serial_checked = true;
  9245. }
  9246. return true;
  9247. });
  9248. auto res = cli.Get("/test");
  9249. ASSERT_TRUE(res);
  9250. EXPECT_TRUE(serial_checked);
  9251. }
  9252. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  9253. // Test 1: Valid CA file - no error should be recorded
  9254. {
  9255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  9256. CLIENT_CA_CERT_FILE);
  9257. ASSERT_TRUE(svr.is_valid());
  9258. // With valid setup, last_ssl_error should be 0
  9259. EXPECT_EQ(0, svr.ssl_last_error());
  9260. }
  9261. // Test 2: Invalid CA file content
  9262. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  9263. {
  9264. // Create a temporary file with completely invalid content
  9265. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  9266. {
  9267. std::ofstream ofs(temp_invalid_ca);
  9268. ofs << "This is not a certificate file at all\n";
  9269. ofs << "Just plain text content\n";
  9270. }
  9271. // Create server with invalid CA file
  9272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  9273. // Clean up temporary file
  9274. std::remove(temp_invalid_ca);
  9275. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  9276. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  9277. // Note: SSL_CTX_load_verify_locations typically fails first,
  9278. // but our error handling code path is still exercised
  9279. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  9280. }
  9281. }
  9282. TEST(VerifyCallbackTest, VerifyContextFields) {
  9283. using namespace httplib::tls;
  9284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9285. ASSERT_TRUE(svr.is_valid());
  9286. svr.Get("/test", [](const Request &, Response &res) {
  9287. res.set_content("ok", "text/plain");
  9288. });
  9289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9290. auto se = detail::scope_exit([&] {
  9291. svr.stop();
  9292. t.join();
  9293. });
  9294. svr.wait_until_ready();
  9295. SSLClient cli(HOST, PORT);
  9296. cli.enable_server_certificate_verification(false);
  9297. cli.set_connection_timeout(30);
  9298. int callback_count = 0;
  9299. bool saw_leaf_cert = false;
  9300. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  9301. if (ctx.cert) {
  9302. callback_count++;
  9303. // We should see at least one certificate (the leaf)
  9304. std::string cn = ctx.subject_cn();
  9305. if (!cn.empty()) { saw_leaf_cert = true; }
  9306. // Verify context fields are populated
  9307. EXPECT_NE(ctx.session, nullptr);
  9308. EXPECT_GE(ctx.depth, 0);
  9309. }
  9310. return true;
  9311. });
  9312. auto res = cli.Get("/test");
  9313. ASSERT_TRUE(res);
  9314. EXPECT_GT(callback_count, 0);
  9315. EXPECT_TRUE(saw_leaf_cert);
  9316. }
  9317. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9318. using httplib::tls::TlsError;
  9319. // Test that verify_error_to_string returns empty for success
  9320. std::string success_str = TlsError::verify_error_to_string(0);
  9321. EXPECT_TRUE(success_str.empty());
  9322. // Test that verify_error_to_string returns non-empty for error codes
  9323. // Using a common error code (certificate expired)
  9324. std::string error_str =
  9325. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9326. EXPECT_FALSE(error_str.empty());
  9327. }
  9328. TEST(SessionVerifierTest, CertificateAccepted) {
  9329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9330. ASSERT_TRUE(svr.is_valid());
  9331. svr.Get("/test", [](const Request &, Response &res) {
  9332. res.set_content("ok", "text/plain");
  9333. });
  9334. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9335. auto se = detail::scope_exit([&] {
  9336. svr.stop();
  9337. t.join();
  9338. });
  9339. svr.wait_until_ready();
  9340. SSLClient cli(HOST, PORT);
  9341. cli.enable_server_certificate_verification(false);
  9342. cli.set_connection_timeout(30);
  9343. bool callback_called = false;
  9344. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9345. EXPECT_NE(session, nullptr);
  9346. callback_called = true;
  9347. return SSLVerifierResponse::CertificateAccepted;
  9348. });
  9349. auto res = cli.Get("/test");
  9350. ASSERT_TRUE(res);
  9351. EXPECT_EQ(200, res->status);
  9352. EXPECT_TRUE(callback_called);
  9353. }
  9354. TEST(SessionVerifierTest, CertificateRejected) {
  9355. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9356. ASSERT_TRUE(svr.is_valid());
  9357. svr.Get("/test", [](const Request &, Response &res) {
  9358. res.set_content("ok", "text/plain");
  9359. });
  9360. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9361. auto se = detail::scope_exit([&] {
  9362. svr.stop();
  9363. t.join();
  9364. });
  9365. svr.wait_until_ready();
  9366. SSLClient cli(HOST, PORT);
  9367. cli.enable_server_certificate_verification(false);
  9368. cli.set_connection_timeout(30);
  9369. bool callback_called = false;
  9370. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9371. EXPECT_NE(session, nullptr);
  9372. callback_called = true;
  9373. return SSLVerifierResponse::CertificateRejected;
  9374. });
  9375. auto res = cli.Get("/test");
  9376. EXPECT_FALSE(res);
  9377. EXPECT_TRUE(callback_called);
  9378. }
  9379. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9381. ASSERT_TRUE(svr.is_valid());
  9382. svr.Get("/test", [](const Request &, Response &res) {
  9383. res.set_content("ok", "text/plain");
  9384. });
  9385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9386. auto se = detail::scope_exit([&] {
  9387. svr.stop();
  9388. t.join();
  9389. });
  9390. svr.wait_until_ready();
  9391. // NoDecisionMade with verification disabled should succeed (no default check)
  9392. SSLClient cli(HOST, PORT);
  9393. cli.enable_server_certificate_verification(false);
  9394. cli.set_connection_timeout(30);
  9395. bool callback_called = false;
  9396. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9397. EXPECT_NE(session, nullptr);
  9398. callback_called = true;
  9399. return SSLVerifierResponse::NoDecisionMade;
  9400. });
  9401. auto res = cli.Get("/test");
  9402. ASSERT_TRUE(res);
  9403. EXPECT_EQ(200, res->status);
  9404. EXPECT_TRUE(callback_called);
  9405. }
  9406. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9407. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9408. ASSERT_TRUE(svr.is_valid());
  9409. svr.Get("/test", [](const Request &, Response &res) {
  9410. res.set_content("ok", "text/plain");
  9411. });
  9412. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9413. auto se = detail::scope_exit([&] {
  9414. svr.stop();
  9415. t.join();
  9416. });
  9417. svr.wait_until_ready();
  9418. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9419. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9420. // so we only check that the request fails, not whether the callback was
  9421. // called.
  9422. SSLClient cli(HOST, PORT);
  9423. cli.enable_server_certificate_verification(true);
  9424. cli.set_connection_timeout(30);
  9425. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9426. EXPECT_NE(session, nullptr);
  9427. return SSLVerifierResponse::NoDecisionMade;
  9428. });
  9429. auto res = cli.Get("/test");
  9430. EXPECT_FALSE(res);
  9431. }
  9432. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9433. // Test SSL server using PemMemory constructor with client CA certificates
  9434. // Read PEM files
  9435. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9436. read_file(SERVER_CERT_FILE, server_cert_pem);
  9437. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9438. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9439. // Create SSLServer with PemMemory constructor including client CA
  9440. SSLServer::PemMemory server_pem = {
  9441. server_cert_pem.c_str(),
  9442. server_cert_pem.size(),
  9443. server_key_pem.c_str(),
  9444. server_key_pem.size(),
  9445. client_ca_pem.c_str(),
  9446. client_ca_pem.size(),
  9447. nullptr // no password for server key
  9448. };
  9449. SSLServer svr(server_pem);
  9450. ASSERT_TRUE(svr.is_valid());
  9451. // No SSL error should be recorded for valid setup
  9452. EXPECT_EQ(0, svr.ssl_last_error());
  9453. // Set up server endpoints
  9454. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9455. res.set_content("ok", "text/plain");
  9456. });
  9457. // Start server in a thread
  9458. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9459. svr.wait_until_ready();
  9460. // Connect with client certificate (using constructor with paths)
  9461. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9462. cli.enable_server_certificate_verification(false);
  9463. auto res = cli.Get("/test-pem-ca");
  9464. ASSERT_TRUE(res);
  9465. EXPECT_EQ(200, res->status);
  9466. EXPECT_EQ("ok", res->body);
  9467. svr.stop();
  9468. server_thread.join();
  9469. }
  9470. #endif
  9471. #ifdef _WIN32
  9472. TEST(CleanupTest, WSACleanup) {
  9473. int ret = WSACleanup();
  9474. ASSERT_EQ(0, ret);
  9475. }
  9476. #endif
  9477. #ifndef CPPHTTPLIB_SSL_ENABLED
  9478. TEST(NoSSLSupport, SimpleInterface) {
  9479. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9480. }
  9481. #endif
  9482. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9483. TEST(InvalidScheme, SimpleInterface) {
  9484. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9485. }
  9486. #endif
  9487. TEST(NoScheme, SimpleInterface) {
  9488. Client cli("yahoo.com:80");
  9489. ASSERT_TRUE(cli.is_valid());
  9490. }
  9491. TEST(SendAPI, SimpleInterface_Online) {
  9492. Client cli("http://yahoo.com");
  9493. Request req;
  9494. req.method = "GET";
  9495. req.path = "/";
  9496. auto res = cli.send(req);
  9497. ASSERT_TRUE(res);
  9498. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9499. }
  9500. TEST(SendAPI, WithParamsInRequest) {
  9501. Server svr;
  9502. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9503. EXPECT_TRUE(req.has_param("test"));
  9504. EXPECT_EQ("test_value", req.get_param_value("test"));
  9505. });
  9506. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9507. auto se = detail::scope_exit([&] {
  9508. svr.stop();
  9509. t.join();
  9510. ASSERT_FALSE(svr.is_running());
  9511. });
  9512. svr.wait_until_ready();
  9513. Client cli(HOST, PORT);
  9514. {
  9515. Request req;
  9516. req.method = "GET";
  9517. req.path = "/";
  9518. req.params.emplace("test", "test_value");
  9519. auto res = cli.send(req);
  9520. ASSERT_TRUE(res);
  9521. }
  9522. {
  9523. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9524. ASSERT_TRUE(res);
  9525. }
  9526. }
  9527. TEST(ClientImplMethods, GetSocketTest) {
  9528. httplib::Server svr;
  9529. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9530. res.status = StatusCode::OK_200;
  9531. });
  9532. auto port = svr.bind_to_any_port("127.0.0.1");
  9533. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9534. auto se = detail::scope_exit([&] {
  9535. svr.stop();
  9536. thread.join();
  9537. ASSERT_FALSE(svr.is_running());
  9538. });
  9539. svr.wait_until_ready();
  9540. {
  9541. httplib::Client cli("127.0.0.1", port);
  9542. cli.set_keep_alive(true);
  9543. // Use the behavior of cpp-httplib of opening the connection
  9544. // only when the first request happens. If that changes,
  9545. // this test would be obsolete.
  9546. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9547. // This also implicitly tests the server. But other tests would fail much
  9548. // earlier than this one to be considered.
  9549. auto res = cli.Get("/");
  9550. ASSERT_TRUE(res);
  9551. EXPECT_EQ(StatusCode::OK_200, res->status);
  9552. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9553. }
  9554. }
  9555. #ifdef CPPHTTPLIB_SSL_ENABLED
  9556. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9557. Client cli("http://yahoo.com");
  9558. auto res = cli.Get("/");
  9559. ASSERT_TRUE(res);
  9560. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9561. cli.set_follow_location(true);
  9562. res = cli.Get("/");
  9563. ASSERT_TRUE(res);
  9564. EXPECT_EQ(StatusCode::OK_200, res->status);
  9565. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9566. }
  9567. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9568. Client cli("https://yahoo.com");
  9569. auto res = cli.Get("/");
  9570. ASSERT_TRUE(res);
  9571. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9572. cli.set_follow_location(true);
  9573. res = cli.Get("/");
  9574. ASSERT_TRUE(res);
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9577. }
  9578. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9579. Client cli("https://yahoo.com");
  9580. auto res = cli.Get("/");
  9581. ASSERT_TRUE(res);
  9582. ASSERT_FALSE(!res);
  9583. ASSERT_TRUE(res);
  9584. ASSERT_FALSE(res == nullptr);
  9585. ASSERT_TRUE(res != nullptr);
  9586. EXPECT_EQ(Error::Success, res.error());
  9587. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9588. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9589. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9590. cli.set_follow_location(true);
  9591. res = cli.Get("/");
  9592. ASSERT_TRUE(res);
  9593. EXPECT_EQ(Error::Success, res.error());
  9594. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9595. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9596. EXPECT_EQ(StatusCode::OK_200, res->status);
  9597. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9598. }
  9599. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9600. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9601. Client cli("https://cdnjs.cloudflare.com");
  9602. auto res =
  9603. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9604. ASSERT_TRUE(res);
  9605. EXPECT_EQ(StatusCode::OK_200, res->status);
  9606. EXPECT_EQ(287630U, res->body.size());
  9607. EXPECT_EQ("application/javascript; charset=utf-8",
  9608. res->get_header_value("Content-Type"));
  9609. }
  9610. #endif
  9611. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9612. #undef REDIR_HOST // Silence compiler warning
  9613. #define REDIR_HOST "https://httpbingo.org"
  9614. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9615. Client cli(REDIR_HOST);
  9616. cli.set_follow_location(true);
  9617. auto res =
  9618. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9619. ASSERT_TRUE(res);
  9620. EXPECT_EQ(StatusCode::OK_200, res->status);
  9621. }
  9622. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9623. Client cli(REDIR_HOST);
  9624. cli.set_follow_location(true);
  9625. Params params;
  9626. params.emplace("url", "http://example.com");
  9627. params.emplace("status_code", "302");
  9628. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9629. ASSERT_TRUE(res);
  9630. EXPECT_EQ(StatusCode::OK_200, res->status);
  9631. }
  9632. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9633. Client cli(REDIR_HOST);
  9634. cli.set_follow_location(true);
  9635. Params params;
  9636. params.emplace("url", "http://example.com");
  9637. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9638. ASSERT_TRUE(res);
  9639. EXPECT_EQ(StatusCode::OK_200, res->status);
  9640. }
  9641. TEST(HttpToHttpsRedirectTest, CertFile) {
  9642. auto ssl_port = PORT + 1;
  9643. Server svr;
  9644. ASSERT_TRUE(svr.is_valid());
  9645. svr.Get("/index", [&](const Request &, Response &res) {
  9646. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9647. "/index");
  9648. svr.stop();
  9649. });
  9650. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9651. ASSERT_TRUE(ssl_svr.is_valid());
  9652. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9653. res.set_content("test", "text/plain");
  9654. ssl_svr.stop();
  9655. });
  9656. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9657. thread t2 =
  9658. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9659. auto se = detail::scope_exit([&] {
  9660. t2.join();
  9661. t.join();
  9662. ASSERT_FALSE(svr.is_running());
  9663. });
  9664. svr.wait_until_ready();
  9665. ssl_svr.wait_until_ready();
  9666. Client cli("127.0.0.1", PORT);
  9667. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9668. cli.enable_server_certificate_verification(true);
  9669. cli.set_follow_location(true);
  9670. cli.set_connection_timeout(30);
  9671. auto res = cli.Get("/index");
  9672. ASSERT_TRUE(res);
  9673. ASSERT_EQ(StatusCode::OK_200, res->status);
  9674. }
  9675. TEST(SSLClientRedirectTest, CertFile) {
  9676. auto ssl_port = PORT + 1;
  9677. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9678. ASSERT_TRUE(ssl_svr1.is_valid());
  9679. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9680. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9681. "/index");
  9682. ssl_svr1.stop();
  9683. });
  9684. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9685. ASSERT_TRUE(ssl_svr2.is_valid());
  9686. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9687. res.set_content("test", "text/plain");
  9688. ssl_svr2.stop();
  9689. });
  9690. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9691. thread t2 =
  9692. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9693. auto se = detail::scope_exit([&] {
  9694. t2.join();
  9695. t.join();
  9696. ASSERT_FALSE(ssl_svr1.is_running());
  9697. });
  9698. ssl_svr1.wait_until_ready();
  9699. ssl_svr2.wait_until_ready();
  9700. SSLClient cli("127.0.0.1", PORT);
  9701. std::string cert;
  9702. read_file(SERVER_CERT2_FILE, cert);
  9703. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9704. cli.enable_server_certificate_verification(true);
  9705. cli.set_follow_location(true);
  9706. cli.set_connection_timeout(30);
  9707. auto res = cli.Get("/index");
  9708. ASSERT_TRUE(res);
  9709. ASSERT_EQ(StatusCode::OK_200, res->status);
  9710. }
  9711. #endif
  9712. #ifdef CPPHTTPLIB_SSL_ENABLED
  9713. // Test that set_ca_cert_store() skips system certs (consistent with
  9714. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9715. // should be trusted - system certs should NOT be loaded.
  9716. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9717. // Load a specific cert that is NOT a system CA cert
  9718. std::string cert;
  9719. read_file(SERVER_CERT2_FILE, cert);
  9720. SSLClient cli("google.com");
  9721. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9722. cli.enable_server_certificate_verification(true);
  9723. // This should FAIL because:
  9724. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9725. // 2. System certs should NOT be loaded when custom store is set
  9726. // If system certs WERE loaded, this would succeed
  9727. auto res = cli.Get("/");
  9728. ASSERT_FALSE(res);
  9729. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9730. }
  9731. TEST(MultipartFormDataTest, LargeData) {
  9732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9733. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9734. const ContentReader &content_reader) {
  9735. if (req.is_multipart_form_data()) {
  9736. std::vector<FormData> items;
  9737. content_reader(
  9738. [&](const FormData &file) {
  9739. items.push_back(file);
  9740. return true;
  9741. },
  9742. [&](const char *data, size_t data_length) {
  9743. items.back().content.append(data, data_length);
  9744. return true;
  9745. });
  9746. EXPECT_TRUE(std::string(items[0].name) == "document");
  9747. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9748. EXPECT_TRUE(items[0].filename == "2MB_data");
  9749. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9750. EXPECT_TRUE(items[1].name == "hello");
  9751. EXPECT_TRUE(items[1].content == "world");
  9752. EXPECT_TRUE(items[1].filename == "");
  9753. EXPECT_TRUE(items[1].content_type == "");
  9754. } else {
  9755. std::string body;
  9756. content_reader([&](const char *data, size_t data_length) {
  9757. body.append(data, data_length);
  9758. return true;
  9759. });
  9760. }
  9761. });
  9762. auto port = svr.bind_to_any_port(HOST);
  9763. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9764. auto se = detail::scope_exit([&] {
  9765. svr.stop();
  9766. t.join();
  9767. ASSERT_FALSE(svr.is_running());
  9768. });
  9769. svr.wait_until_ready();
  9770. {
  9771. std::string data(1024 * 1024 * 2, '.');
  9772. std::stringstream buffer;
  9773. buffer << data;
  9774. SSLClient cli(HOST, port);
  9775. cli.enable_server_certificate_verification(false);
  9776. UploadFormDataItems items{
  9777. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9778. {"hello", "world", "", ""},
  9779. };
  9780. auto res = cli.Post("/post", items);
  9781. ASSERT_TRUE(res);
  9782. ASSERT_EQ(StatusCode::OK_200, res->status);
  9783. }
  9784. }
  9785. TEST(MultipartFormDataTest, DataProviderItems) {
  9786. std::random_device seed_gen;
  9787. std::mt19937 random(seed_gen());
  9788. std::string rand1;
  9789. rand1.resize(1000);
  9790. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9791. std::string rand2;
  9792. rand2.resize(3000);
  9793. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9795. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9796. const ContentReader &content_reader) {
  9797. ASSERT_FALSE(req.is_multipart_form_data());
  9798. std::string body;
  9799. content_reader([&](const char *data, size_t data_length) {
  9800. body.append(data, data_length);
  9801. return true;
  9802. });
  9803. EXPECT_EQ(body, "");
  9804. });
  9805. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9806. const ContentReader &content_reader) {
  9807. ASSERT_TRUE(req.is_multipart_form_data());
  9808. std::vector<FormData> items;
  9809. content_reader(
  9810. [&](const FormData &file) {
  9811. items.push_back(file);
  9812. return true;
  9813. },
  9814. [&](const char *data, size_t data_length) {
  9815. items.back().content.append(data, data_length);
  9816. return true;
  9817. });
  9818. ASSERT_TRUE(items.size() == 2);
  9819. EXPECT_EQ(std::string(items[0].name), "name1");
  9820. EXPECT_EQ(items[0].content, "Testing123");
  9821. EXPECT_EQ(items[0].filename, "filename1");
  9822. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9823. EXPECT_EQ(items[1].name, "name2");
  9824. EXPECT_EQ(items[1].content, "Testing456");
  9825. EXPECT_EQ(items[1].filename, "");
  9826. EXPECT_EQ(items[1].content_type, "");
  9827. });
  9828. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9829. const ContentReader &content_reader) {
  9830. ASSERT_TRUE(req.is_multipart_form_data());
  9831. std::vector<FormData> items;
  9832. content_reader(
  9833. [&](const FormData &file) {
  9834. items.push_back(file);
  9835. return true;
  9836. },
  9837. [&](const char *data, size_t data_length) {
  9838. items.back().content.append(data, data_length);
  9839. return true;
  9840. });
  9841. ASSERT_TRUE(items.size() == 2);
  9842. EXPECT_EQ(items[0].name, "name3");
  9843. EXPECT_EQ(items[0].content, rand1);
  9844. EXPECT_EQ(items[0].filename, "filename3");
  9845. EXPECT_EQ(items[0].content_type, "");
  9846. EXPECT_EQ(items[1].name, "name4");
  9847. EXPECT_EQ(items[1].content, rand2);
  9848. EXPECT_EQ(items[1].filename, "filename4");
  9849. EXPECT_EQ(items[1].content_type, "");
  9850. });
  9851. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9852. const ContentReader &content_reader) {
  9853. ASSERT_TRUE(req.is_multipart_form_data());
  9854. std::vector<FormData> items;
  9855. content_reader(
  9856. [&](const FormData &file) {
  9857. items.push_back(file);
  9858. return true;
  9859. },
  9860. [&](const char *data, size_t data_length) {
  9861. items.back().content.append(data, data_length);
  9862. return true;
  9863. });
  9864. ASSERT_TRUE(items.size() == 4);
  9865. EXPECT_EQ(std::string(items[0].name), "name1");
  9866. EXPECT_EQ(items[0].content, "Testing123");
  9867. EXPECT_EQ(items[0].filename, "filename1");
  9868. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9869. EXPECT_EQ(items[1].name, "name2");
  9870. EXPECT_EQ(items[1].content, "Testing456");
  9871. EXPECT_EQ(items[1].filename, "");
  9872. EXPECT_EQ(items[1].content_type, "");
  9873. EXPECT_EQ(items[2].name, "name3");
  9874. EXPECT_EQ(items[2].content, rand1);
  9875. EXPECT_EQ(items[2].filename, "filename3");
  9876. EXPECT_EQ(items[2].content_type, "");
  9877. EXPECT_EQ(items[3].name, "name4");
  9878. EXPECT_EQ(items[3].content, rand2);
  9879. EXPECT_EQ(items[3].filename, "filename4");
  9880. EXPECT_EQ(items[3].content_type, "");
  9881. });
  9882. auto port = svr.bind_to_any_port("localhost");
  9883. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9884. auto se = detail::scope_exit([&] {
  9885. svr.stop();
  9886. t.join();
  9887. ASSERT_FALSE(svr.is_running());
  9888. });
  9889. svr.wait_until_ready();
  9890. {
  9891. SSLClient cli("localhost", port);
  9892. cli.enable_server_certificate_verification(false);
  9893. UploadFormDataItems items{
  9894. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9895. {"name2", "Testing456", "", ""}, // not a file
  9896. };
  9897. {
  9898. auto res = cli.Post("/post-none", {}, {}, {});
  9899. ASSERT_TRUE(res);
  9900. ASSERT_EQ(StatusCode::OK_200, res->status);
  9901. }
  9902. FormDataProviderItems providers;
  9903. {
  9904. auto res =
  9905. cli.Post("/post-items", {}, items, providers); // empty providers
  9906. ASSERT_TRUE(res);
  9907. ASSERT_EQ(StatusCode::OK_200, res->status);
  9908. }
  9909. providers.push_back({"name3",
  9910. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9911. // test the offset is given correctly at each step
  9912. if (!offset)
  9913. sink.os.write(rand1.data(), 30);
  9914. else if (offset == 30)
  9915. sink.os.write(rand1.data() + 30, 300);
  9916. else if (offset == 330)
  9917. sink.os.write(rand1.data() + 330, 670);
  9918. else if (offset == rand1.size())
  9919. sink.done();
  9920. return true;
  9921. },
  9922. "filename3",
  9923. {}});
  9924. providers.push_back({"name4",
  9925. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9926. // test the offset is given correctly at each step
  9927. if (!offset)
  9928. sink.os.write(rand2.data(), 2000);
  9929. else if (offset == 2000)
  9930. sink.os.write(rand2.data() + 2000, 1);
  9931. else if (offset == 2001)
  9932. sink.os.write(rand2.data() + 2001, 999);
  9933. else if (offset == rand2.size())
  9934. sink.done();
  9935. return true;
  9936. },
  9937. "filename4",
  9938. {}});
  9939. {
  9940. auto res = cli.Post("/post-providers", {}, {}, providers);
  9941. ASSERT_TRUE(res);
  9942. ASSERT_EQ(StatusCode::OK_200, res->status);
  9943. }
  9944. {
  9945. auto res = cli.Post("/post-both", {}, items, providers);
  9946. ASSERT_TRUE(res);
  9947. ASSERT_EQ(StatusCode::OK_200, res->status);
  9948. }
  9949. }
  9950. }
  9951. TEST(MultipartFormDataTest, BadHeader) {
  9952. Server svr;
  9953. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9954. res.set_content("ok", "text/plain");
  9955. });
  9956. thread t = thread([&] { svr.listen(HOST, PORT); });
  9957. auto se = detail::scope_exit([&] {
  9958. svr.stop();
  9959. t.join();
  9960. ASSERT_FALSE(svr.is_running());
  9961. });
  9962. svr.wait_until_ready();
  9963. const std::string body =
  9964. "This is the preamble. It is to be ignored, though it\r\n"
  9965. "is a handy place for composition agents to include an\r\n"
  9966. "explanatory note to non-MIME conformant readers.\r\n"
  9967. "\r\n"
  9968. "\r\n"
  9969. "--simple boundary\r\n"
  9970. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9971. ": BAD...\r\n"
  9972. "\r\n"
  9973. "value1\r\n"
  9974. "--simple boundary\r\n"
  9975. "Content-Disposition: form-data; name=\"field2\"; "
  9976. "filename=\"example.txt\"\r\n"
  9977. "\r\n"
  9978. "value2\r\n"
  9979. "--simple boundary--\r\n"
  9980. "This is the epilogue. It is also to be ignored.\r\n";
  9981. std::string content_type =
  9982. R"(multipart/form-data; boundary="simple boundary")";
  9983. Client cli(HOST, PORT);
  9984. auto res = cli.Post("/post", body, content_type.c_str());
  9985. ASSERT_TRUE(res);
  9986. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9987. }
  9988. TEST(MultipartFormDataTest, WithPreamble) {
  9989. Server svr;
  9990. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9991. res.set_content("ok", "text/plain");
  9992. });
  9993. thread t = thread([&] { svr.listen(HOST, PORT); });
  9994. auto se = detail::scope_exit([&] {
  9995. svr.stop();
  9996. t.join();
  9997. ASSERT_FALSE(svr.is_running());
  9998. });
  9999. svr.wait_until_ready();
  10000. const std::string body =
  10001. "This is the preamble. It is to be ignored, though it\r\n"
  10002. "is a handy place for composition agents to include an\r\n"
  10003. "explanatory note to non-MIME conformant readers.\r\n"
  10004. "\r\n"
  10005. "\r\n"
  10006. "--simple boundary\r\n"
  10007. "Content-Disposition: form-data; name=\"field1\"\r\n"
  10008. "\r\n"
  10009. "value1\r\n"
  10010. "--simple boundary\r\n"
  10011. "Content-Disposition: form-data; name=\"field2\"; "
  10012. "filename=\"example.txt\"\r\n"
  10013. "\r\n"
  10014. "value2\r\n"
  10015. "--simple boundary--\r\n"
  10016. "This is the epilogue. It is also to be ignored.\r\n";
  10017. std::string content_type =
  10018. R"(multipart/form-data; boundary="simple boundary")";
  10019. Client cli(HOST, PORT);
  10020. auto res = cli.Post("/post", body, content_type.c_str());
  10021. ASSERT_TRUE(res);
  10022. EXPECT_EQ(StatusCode::OK_200, res->status);
  10023. }
  10024. TEST(MultipartFormDataTest, PostCustomBoundary) {
  10025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10026. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  10027. const ContentReader &content_reader) {
  10028. if (req.is_multipart_form_data()) {
  10029. std::vector<FormData> items;
  10030. content_reader(
  10031. [&](const FormData &file) {
  10032. items.push_back(file);
  10033. return true;
  10034. },
  10035. [&](const char *data, size_t data_length) {
  10036. items.back().content.append(data, data_length);
  10037. return true;
  10038. });
  10039. EXPECT_TRUE(std::string(items[0].name) == "document");
  10040. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10041. EXPECT_TRUE(items[0].filename == "2MB_data");
  10042. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10043. EXPECT_TRUE(items[1].name == "hello");
  10044. EXPECT_TRUE(items[1].content == "world");
  10045. EXPECT_TRUE(items[1].filename == "");
  10046. EXPECT_TRUE(items[1].content_type == "");
  10047. } else {
  10048. std::string body;
  10049. content_reader([&](const char *data, size_t data_length) {
  10050. body.append(data, data_length);
  10051. return true;
  10052. });
  10053. }
  10054. });
  10055. auto port = svr.bind_to_any_port("localhost");
  10056. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10057. auto se = detail::scope_exit([&] {
  10058. svr.stop();
  10059. t.join();
  10060. ASSERT_FALSE(svr.is_running());
  10061. });
  10062. svr.wait_until_ready();
  10063. {
  10064. std::string data(1024 * 1024 * 2, '.');
  10065. std::stringstream buffer;
  10066. buffer << data;
  10067. SSLClient cli("localhost", port);
  10068. cli.enable_server_certificate_verification(false);
  10069. UploadFormDataItems items{
  10070. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10071. {"hello", "world", "", ""},
  10072. };
  10073. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  10074. ASSERT_TRUE(res);
  10075. ASSERT_EQ(StatusCode::OK_200, res->status);
  10076. }
  10077. }
  10078. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  10079. std::string data(1024 * 1024 * 2, '&');
  10080. std::stringstream buffer;
  10081. buffer << data;
  10082. Client cli("https://localhost:8080");
  10083. UploadFormDataItems items{
  10084. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10085. {"hello", "world", "", ""},
  10086. };
  10087. for (const char &c : " \t\r\n") {
  10088. auto res =
  10089. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  10090. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10091. ASSERT_FALSE(res);
  10092. }
  10093. }
  10094. TEST(MultipartFormDataTest, PutFormData) {
  10095. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10096. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  10097. const ContentReader &content_reader) {
  10098. if (req.is_multipart_form_data()) {
  10099. std::vector<FormData> items;
  10100. content_reader(
  10101. [&](const FormData &file) {
  10102. items.push_back(file);
  10103. return true;
  10104. },
  10105. [&](const char *data, size_t data_length) {
  10106. items.back().content.append(data, data_length);
  10107. return true;
  10108. });
  10109. EXPECT_TRUE(std::string(items[0].name) == "document");
  10110. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10111. EXPECT_TRUE(items[0].filename == "2MB_data");
  10112. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10113. EXPECT_TRUE(items[1].name == "hello");
  10114. EXPECT_TRUE(items[1].content == "world");
  10115. EXPECT_TRUE(items[1].filename == "");
  10116. EXPECT_TRUE(items[1].content_type == "");
  10117. } else {
  10118. std::string body;
  10119. content_reader([&](const char *data, size_t data_length) {
  10120. body.append(data, data_length);
  10121. return true;
  10122. });
  10123. }
  10124. });
  10125. auto port = svr.bind_to_any_port("localhost");
  10126. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10127. auto se = detail::scope_exit([&] {
  10128. svr.stop();
  10129. t.join();
  10130. ASSERT_FALSE(svr.is_running());
  10131. });
  10132. svr.wait_until_ready();
  10133. {
  10134. std::string data(1024 * 1024 * 2, '&');
  10135. std::stringstream buffer;
  10136. buffer << data;
  10137. SSLClient cli("localhost", port);
  10138. cli.enable_server_certificate_verification(false);
  10139. UploadFormDataItems items{
  10140. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10141. {"hello", "world", "", ""},
  10142. };
  10143. auto res = cli.Put("/put", items);
  10144. ASSERT_TRUE(res);
  10145. ASSERT_EQ(StatusCode::OK_200, res->status);
  10146. }
  10147. }
  10148. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  10149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10150. svr.Put("/put_customboundary",
  10151. [&](const Request &req, const Response & /*res*/,
  10152. const ContentReader &content_reader) {
  10153. if (req.is_multipart_form_data()) {
  10154. std::vector<FormData> items;
  10155. content_reader(
  10156. [&](const FormData &file) {
  10157. items.push_back(file);
  10158. return true;
  10159. },
  10160. [&](const char *data, size_t data_length) {
  10161. items.back().content.append(data, data_length);
  10162. return true;
  10163. });
  10164. EXPECT_TRUE(std::string(items[0].name) == "document");
  10165. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  10166. EXPECT_TRUE(items[0].filename == "2MB_data");
  10167. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  10168. EXPECT_TRUE(items[1].name == "hello");
  10169. EXPECT_TRUE(items[1].content == "world");
  10170. EXPECT_TRUE(items[1].filename == "");
  10171. EXPECT_TRUE(items[1].content_type == "");
  10172. } else {
  10173. std::string body;
  10174. content_reader([&](const char *data, size_t data_length) {
  10175. body.append(data, data_length);
  10176. return true;
  10177. });
  10178. }
  10179. });
  10180. auto port = svr.bind_to_any_port("localhost");
  10181. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10182. auto se = detail::scope_exit([&] {
  10183. svr.stop();
  10184. t.join();
  10185. ASSERT_FALSE(svr.is_running());
  10186. });
  10187. svr.wait_until_ready();
  10188. {
  10189. std::string data(1024 * 1024 * 2, '&');
  10190. std::stringstream buffer;
  10191. buffer << data;
  10192. SSLClient cli("localhost", port);
  10193. cli.enable_server_certificate_verification(false);
  10194. UploadFormDataItems items{
  10195. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10196. {"hello", "world", "", ""},
  10197. };
  10198. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  10199. ASSERT_TRUE(res);
  10200. ASSERT_EQ(StatusCode::OK_200, res->status);
  10201. }
  10202. }
  10203. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  10204. std::string data(1024 * 1024 * 2, '&');
  10205. std::stringstream buffer;
  10206. buffer << data;
  10207. Client cli("https://localhost:8080");
  10208. cli.enable_server_certificate_verification(false);
  10209. UploadFormDataItems items{
  10210. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  10211. {"hello", "world", "", ""},
  10212. };
  10213. for (const char &c : " \t\r\n") {
  10214. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  10215. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  10216. ASSERT_FALSE(res);
  10217. }
  10218. }
  10219. TEST(MultipartFormDataTest, AlternateFilename) {
  10220. auto handled = false;
  10221. Server svr;
  10222. svr.Post("/test", [&](const Request &req, Response &res) {
  10223. ASSERT_EQ(2u, req.form.files.size());
  10224. ASSERT_EQ(1u, req.form.fields.size());
  10225. // Test files
  10226. const auto &file1 = req.form.get_file("file1");
  10227. ASSERT_EQ("file1", file1.name);
  10228. ASSERT_EQ("A.txt", file1.filename);
  10229. ASSERT_EQ("text/plain", file1.content_type);
  10230. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  10231. const auto &file2 = req.form.get_file("file2");
  10232. ASSERT_EQ("file2", file2.name);
  10233. ASSERT_EQ("a.html", file2.filename);
  10234. ASSERT_EQ("text/html", file2.content_type);
  10235. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  10236. file2.content);
  10237. // Test text field
  10238. const auto &text = req.form.get_field("text");
  10239. ASSERT_EQ("text default", text);
  10240. res.set_content("ok", "text/plain");
  10241. handled = true;
  10242. });
  10243. thread t = thread([&] { svr.listen(HOST, PORT); });
  10244. auto se = detail::scope_exit([&] {
  10245. svr.stop();
  10246. t.join();
  10247. ASSERT_FALSE(svr.is_running());
  10248. ASSERT_TRUE(handled);
  10249. });
  10250. svr.wait_until_ready();
  10251. auto req = "POST /test HTTP/1.1\r\n"
  10252. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10253. "Content-Length: 399\r\n"
  10254. "\r\n"
  10255. "----------\r\n"
  10256. "Content-Disposition: form-data; name=\"text\"\r\n"
  10257. "\r\n"
  10258. "text default\r\n"
  10259. "----------\r\n"
  10260. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  10261. "filename=\"a.txt\"; name=\"file1\"\r\n"
  10262. "Content-Type: text/plain\r\n"
  10263. "\r\n"
  10264. "Content of a.txt.\r\n"
  10265. "\r\n"
  10266. "----------\r\n"
  10267. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  10268. "\"a.html\"\r\n"
  10269. "Content-Type: text/html\r\n"
  10270. "\r\n"
  10271. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  10272. "\r\n"
  10273. "------------\r\n";
  10274. ASSERT_TRUE(send_request(1, req));
  10275. }
  10276. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  10277. auto handled = false;
  10278. Server svr;
  10279. svr.Post("/test", [&](const Request &req, Response &res) {
  10280. // Case-insensitive "utf-8''" prefix with a long value
  10281. const auto &file = req.form.get_file("file1");
  10282. ASSERT_EQ("file1", file.name);
  10283. // 8000 chars exercises both the Content-Disposition parser and the
  10284. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  10285. // Prior to the fix, std::regex_match on this header would cause O(N)
  10286. // stack recursion in libstdc++, leading to SIGSEGV.
  10287. std::string expected_filename(8000, 'A');
  10288. ASSERT_EQ(expected_filename, file.filename);
  10289. res.set_content("ok", "text/plain");
  10290. handled = true;
  10291. });
  10292. thread t = thread([&] { svr.listen(HOST, PORT); });
  10293. auto se = detail::scope_exit([&] {
  10294. svr.stop();
  10295. t.join();
  10296. ASSERT_FALSE(svr.is_running());
  10297. ASSERT_TRUE(handled);
  10298. });
  10299. svr.wait_until_ready();
  10300. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  10301. // Regression test for GHSA-qq6v-r583-3h69
  10302. std::string long_filename(8000, 'A');
  10303. std::string body = "----------\r\n"
  10304. "Content-Disposition: form-data; name=\"file1\"; "
  10305. "filename*=\"Utf-8''" +
  10306. long_filename +
  10307. "\"\r\n"
  10308. "\r\n"
  10309. "hello\r\n"
  10310. "------------\r\n";
  10311. auto req = "POST /test HTTP/1.1\r\n"
  10312. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10313. "Content-Length: " +
  10314. std::to_string(body.size()) + "\r\n\r\n" + body;
  10315. ASSERT_TRUE(send_request(1, req));
  10316. }
  10317. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10318. auto handled = false;
  10319. Server svr;
  10320. svr.Post("/test", [&](const Request &req, Response &) {
  10321. ASSERT_EQ(2u, req.form.fields.size());
  10322. const auto &text1 = req.form.get_field("text1");
  10323. ASSERT_EQ("text1", text1);
  10324. const auto &text2 = req.form.get_field("text2");
  10325. ASSERT_EQ("text2", text2);
  10326. handled = true;
  10327. });
  10328. thread t = thread([&] { svr.listen(HOST, PORT); });
  10329. auto se = detail::scope_exit([&] {
  10330. svr.stop();
  10331. t.join();
  10332. ASSERT_FALSE(svr.is_running());
  10333. ASSERT_TRUE(handled);
  10334. });
  10335. svr.wait_until_ready();
  10336. auto req = "POST /test HTTP/1.1\r\n"
  10337. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10338. "Content-Length: 146\r\n"
  10339. "\r\n----------\r\n"
  10340. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10341. "\r\n"
  10342. "text1"
  10343. "\r\n----------\r\n"
  10344. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10345. "\r\n"
  10346. "text2"
  10347. "\r\n------------";
  10348. std::string response;
  10349. ASSERT_TRUE(send_request(1, req, &response));
  10350. ASSERT_EQ("200", response.substr(9, 3));
  10351. }
  10352. TEST(MultipartFormDataTest, ContentLength) {
  10353. auto handled = false;
  10354. Server svr;
  10355. svr.Post("/test", [&](const Request &req, Response &) {
  10356. ASSERT_EQ(2u, req.form.fields.size());
  10357. const auto &text1 = req.form.get_field("text1");
  10358. ASSERT_EQ("text1", text1);
  10359. const auto &text2 = req.form.get_field("text2");
  10360. ASSERT_EQ("text2", text2);
  10361. handled = true;
  10362. });
  10363. thread t = thread([&] { svr.listen(HOST, PORT); });
  10364. auto se = detail::scope_exit([&] {
  10365. svr.stop();
  10366. t.join();
  10367. ASSERT_FALSE(svr.is_running());
  10368. ASSERT_TRUE(handled);
  10369. });
  10370. svr.wait_until_ready();
  10371. auto req = "POST /test HTTP/1.1\r\n"
  10372. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10373. "Content-Length: 167\r\n"
  10374. "\r\n----------\r\n"
  10375. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10376. "Content-Length: 5\r\n"
  10377. "\r\n"
  10378. "text1"
  10379. "\r\n----------\r\n"
  10380. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10381. "\r\n"
  10382. "text2"
  10383. "\r\n------------\r\n";
  10384. std::string response;
  10385. ASSERT_TRUE(send_request(1, req, &response));
  10386. ASSERT_EQ("200", response.substr(9, 3));
  10387. }
  10388. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10389. auto handled = false;
  10390. Server svr;
  10391. svr.Post("/test", [&](const Request &req, Response &) {
  10392. ASSERT_EQ(2u, req.form.fields.size());
  10393. const auto &text1 = req.form.get_field("text1");
  10394. ASSERT_EQ("text1", text1);
  10395. // TODO: Add header access for text fields if needed
  10396. const auto &text2 = req.form.get_field("text2");
  10397. ASSERT_EQ("text2", text2);
  10398. // TODO: Header access for text fields needs to be implemented
  10399. // auto &headers = it->second.headers;
  10400. // ASSERT_EQ(3U, headers.size());
  10401. // auto custom_header = headers.find("x-whatever");
  10402. // ASSERT_TRUE(custom_header != headers.end());
  10403. // ASSERT_NE("customvalue", custom_header->second);
  10404. // ASSERT_EQ("CustomValue", custom_header->second);
  10405. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10406. handled = true;
  10407. });
  10408. thread t = thread([&] { svr.listen(HOST, PORT); });
  10409. auto se = detail::scope_exit([&] {
  10410. svr.stop();
  10411. t.join();
  10412. ASSERT_FALSE(svr.is_running());
  10413. ASSERT_TRUE(handled);
  10414. });
  10415. svr.wait_until_ready();
  10416. auto req = "POST /test HTTP/1.1\r\n"
  10417. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10418. "Content-Length: 232\r\n"
  10419. "\r\n----------\r\n"
  10420. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10421. "Content-Length: 5\r\n"
  10422. "X-Test: 1\r\n"
  10423. "\r\n"
  10424. "text1"
  10425. "\r\n----------\r\n"
  10426. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10427. "Content-Type: text/plain\r\n"
  10428. "X-Whatever: CustomValue\r\n"
  10429. "\r\n"
  10430. "text2"
  10431. "\r\n------------\r\n"
  10432. "That should be disregarded. Not even read";
  10433. std::string response;
  10434. ASSERT_TRUE(send_request(1, req, &response));
  10435. ASSERT_EQ("200", response.substr(9, 3));
  10436. }
  10437. TEST(MultipartFormDataTest, LargeHeader) {
  10438. auto handled = false;
  10439. Server svr;
  10440. svr.Post("/test", [&](const Request &req, Response &) {
  10441. ASSERT_EQ(1u, req.form.fields.size());
  10442. const auto &text = req.form.get_field("name1");
  10443. ASSERT_EQ("text1", text);
  10444. handled = true;
  10445. });
  10446. thread t = thread([&] { svr.listen(HOST, PORT); });
  10447. auto se = detail::scope_exit([&] {
  10448. svr.stop();
  10449. t.join();
  10450. ASSERT_FALSE(svr.is_running());
  10451. ASSERT_TRUE(handled);
  10452. });
  10453. svr.wait_until_ready();
  10454. auto boundary = std::string("cpp-httplib-multipart-data");
  10455. std::string content = "--" + boundary +
  10456. "\r\n"
  10457. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10458. "\r\n"
  10459. "text1\r\n"
  10460. "--" +
  10461. boundary + "--\r\n";
  10462. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10463. "Content-Type: multipart/form-data;boundary=" +
  10464. boundary +
  10465. "\r\n"
  10466. "Content-Length: " +
  10467. std::to_string(content.size()) +
  10468. "\r\n"
  10469. "Dummy-Header: ";
  10470. std::string header_suffix = "\r\n"
  10471. "\r\n";
  10472. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10473. size_t header_dummy_size =
  10474. read_buff_size -
  10475. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10476. auto header_dummy = std::string(header_dummy_size, '@');
  10477. auto req = header_prefix + header_dummy + header_suffix + content;
  10478. std::string response;
  10479. ASSERT_TRUE(send_request(1, req, &response));
  10480. ASSERT_EQ("200", response.substr(9, 3));
  10481. }
  10482. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10483. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10484. // (not chunked Transfer-Encoding) after the streaming refactor.
  10485. auto handled = false;
  10486. Server svr;
  10487. svr.Post("/upload", [&](const Request &req, Response &res) {
  10488. auto cl_it = req.headers.find("Content-Length");
  10489. EXPECT_TRUE(cl_it != req.headers.end());
  10490. auto te_it = req.headers.find("Transfer-Encoding");
  10491. EXPECT_TRUE(te_it == req.headers.end());
  10492. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10493. res.set_content("ok", "text/plain");
  10494. handled = true;
  10495. });
  10496. auto port = svr.bind_to_any_port(HOST);
  10497. auto t = thread([&] { svr.listen_after_bind(); });
  10498. auto se = detail::scope_exit([&] {
  10499. svr.stop();
  10500. t.join();
  10501. ASSERT_FALSE(svr.is_running());
  10502. ASSERT_TRUE(handled);
  10503. });
  10504. svr.wait_until_ready();
  10505. UploadFormDataItems items = {
  10506. {"field1", "hello", "", "text/plain"},
  10507. {"file1", "world", "test.txt", "application/octet-stream"},
  10508. };
  10509. Client cli(HOST, port);
  10510. auto res = cli.Post("/upload", {}, items);
  10511. ASSERT_TRUE(res);
  10512. EXPECT_EQ(StatusCode::OK_200, res->status);
  10513. }
  10514. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10515. // Verify that make_multipart_content_provider coalesces many small segments
  10516. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10517. constexpr size_t kItemCount = 1000;
  10518. UploadFormDataItems items;
  10519. items.reserve(kItemCount);
  10520. for (size_t i = 0; i < kItemCount; i++) {
  10521. items.push_back(
  10522. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10523. }
  10524. const std::string boundary = "----test-boundary";
  10525. auto content_length = detail::get_multipart_content_length(items, boundary);
  10526. auto provider = detail::make_multipart_content_provider(items, boundary);
  10527. // Drive the provider the same way write_content_with_progress does
  10528. size_t write_count = 0;
  10529. size_t total_bytes = 0;
  10530. DataSink sink;
  10531. size_t offset = 0;
  10532. sink.write = [&](const char *d, size_t l) -> bool {
  10533. (void)d;
  10534. write_count++;
  10535. total_bytes += l;
  10536. offset += l;
  10537. return true;
  10538. };
  10539. sink.is_writable = []() -> bool { return true; };
  10540. while (offset < content_length) {
  10541. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10542. }
  10543. EXPECT_EQ(content_length, total_bytes);
  10544. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10545. // With buffering into 64KB blocks, write_count should be much smaller.
  10546. auto segment_count = 3 * kItemCount + 1;
  10547. EXPECT_LT(write_count, segment_count / 10);
  10548. }
  10549. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10550. // Integration test: send many UploadFormDataItems and verify the server
  10551. // receives all of them correctly (#2410).
  10552. constexpr size_t kItemCount = 500;
  10553. auto handled = false;
  10554. Server svr;
  10555. svr.Post("/upload", [&](const Request &req, Response &res) {
  10556. EXPECT_EQ(kItemCount, req.form.fields.size());
  10557. for (size_t i = 0; i < kItemCount; i++) {
  10558. auto key = "field" + std::to_string(i);
  10559. auto val = "value" + std::to_string(i);
  10560. auto it = req.form.fields.find(key);
  10561. if (it != req.form.fields.end()) {
  10562. EXPECT_EQ(val, it->second.content);
  10563. } else {
  10564. ADD_FAILURE() << "Missing field: " << key;
  10565. }
  10566. }
  10567. res.set_content("ok", "text/plain");
  10568. handled = true;
  10569. });
  10570. auto port = svr.bind_to_any_port(HOST);
  10571. auto t = thread([&] { svr.listen_after_bind(); });
  10572. auto se = detail::scope_exit([&] {
  10573. svr.stop();
  10574. t.join();
  10575. ASSERT_FALSE(svr.is_running());
  10576. ASSERT_TRUE(handled);
  10577. });
  10578. svr.wait_until_ready();
  10579. UploadFormDataItems items;
  10580. items.reserve(kItemCount);
  10581. for (size_t i = 0; i < kItemCount; i++) {
  10582. items.push_back(
  10583. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10584. }
  10585. Client cli(HOST, port);
  10586. auto res = cli.Post("/upload", items);
  10587. ASSERT_TRUE(res);
  10588. EXPECT_EQ(StatusCode::OK_200, res->status);
  10589. }
  10590. TEST(MultipartFormDataTest, MakeFileProvider) {
  10591. // Verify make_file_provider sends a file's contents correctly.
  10592. const std::string file_content(4096, 'Z');
  10593. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10594. {
  10595. std::ofstream ofs(tmp_path, std::ios::binary);
  10596. ofs.write(file_content.data(),
  10597. static_cast<std::streamsize>(file_content.size()));
  10598. }
  10599. auto handled = false;
  10600. Server svr;
  10601. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10602. const ContentReader &content_reader) {
  10603. ASSERT_TRUE(req.is_multipart_form_data());
  10604. std::vector<FormData> items;
  10605. content_reader(
  10606. [&](const FormData &file) {
  10607. items.push_back(file);
  10608. return true;
  10609. },
  10610. [&](const char *data, size_t data_length) {
  10611. items.back().content.append(data, data_length);
  10612. return true;
  10613. });
  10614. ASSERT_EQ(1u, items.size());
  10615. EXPECT_EQ("myfile", items[0].name);
  10616. EXPECT_EQ("data.bin", items[0].filename);
  10617. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10618. EXPECT_EQ(file_content, items[0].content);
  10619. handled = true;
  10620. });
  10621. auto port = svr.bind_to_any_port(HOST);
  10622. auto t = thread([&] { svr.listen_after_bind(); });
  10623. auto se = detail::scope_exit([&] {
  10624. svr.stop();
  10625. t.join();
  10626. ASSERT_FALSE(svr.is_running());
  10627. ASSERT_TRUE(handled);
  10628. std::remove(tmp_path.c_str());
  10629. });
  10630. svr.wait_until_ready();
  10631. FormDataProviderItems providers;
  10632. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10633. "application/octet-stream"));
  10634. Client cli(HOST, port);
  10635. auto res = cli.Post("/upload", {}, {}, providers);
  10636. ASSERT_TRUE(res);
  10637. EXPECT_EQ(StatusCode::OK_200, res->status);
  10638. }
  10639. TEST(MakeFileBodyTest, Basic) {
  10640. const std::string file_content(4096, 'Z');
  10641. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10642. {
  10643. std::ofstream ofs(tmp_path, std::ios::binary);
  10644. ofs.write(file_content.data(),
  10645. static_cast<std::streamsize>(file_content.size()));
  10646. }
  10647. auto handled = false;
  10648. Server svr;
  10649. svr.Post("/upload", [&](const Request &req, Response &res) {
  10650. EXPECT_EQ(file_content, req.body);
  10651. handled = true;
  10652. res.status = StatusCode::OK_200;
  10653. });
  10654. auto port = svr.bind_to_any_port(HOST);
  10655. auto t = thread([&] { svr.listen_after_bind(); });
  10656. auto se = detail::scope_exit([&] {
  10657. svr.stop();
  10658. t.join();
  10659. ASSERT_FALSE(svr.is_running());
  10660. ASSERT_TRUE(handled);
  10661. std::remove(tmp_path.c_str());
  10662. });
  10663. svr.wait_until_ready();
  10664. auto fb = make_file_body(tmp_path);
  10665. ASSERT_GT(fb.first, 0u);
  10666. Client cli(HOST, port);
  10667. auto res =
  10668. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10669. ASSERT_TRUE(res);
  10670. EXPECT_EQ(StatusCode::OK_200, res->status);
  10671. }
  10672. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10673. static constexpr unsigned int number_of_tasks{1000000};
  10674. std::atomic_uint count{0};
  10675. std::unique_ptr<TaskQueue> task_queue{
  10676. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10677. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10678. auto queued = task_queue->enqueue(
  10679. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10680. EXPECT_TRUE(queued);
  10681. }
  10682. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10683. task_queue->shutdown();
  10684. #else
  10685. EXPECT_NO_THROW(task_queue->shutdown());
  10686. #endif
  10687. EXPECT_EQ(number_of_tasks, count.load());
  10688. }
  10689. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10690. static constexpr unsigned int number_of_tasks{1000000};
  10691. static constexpr unsigned int qlimit{2};
  10692. unsigned int queued_count{0};
  10693. std::atomic_uint count{0};
  10694. std::unique_ptr<TaskQueue> task_queue{
  10695. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10696. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10697. if (task_queue->enqueue(
  10698. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10699. queued_count++;
  10700. }
  10701. }
  10702. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10703. task_queue->shutdown();
  10704. #else
  10705. EXPECT_NO_THROW(task_queue->shutdown());
  10706. #endif
  10707. EXPECT_EQ(queued_count, count.load());
  10708. EXPECT_TRUE(queued_count <= number_of_tasks);
  10709. EXPECT_TRUE(queued_count >= qlimit);
  10710. }
  10711. TEST(TaskQueueTest, MaxQueuedRequests) {
  10712. static constexpr unsigned int qlimit{3};
  10713. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10714. std::condition_variable sem_cv;
  10715. std::mutex sem_mtx;
  10716. int credits = 0;
  10717. bool queued;
  10718. /* Fill up the queue with tasks that will block until we give them credits to
  10719. * complete. */
  10720. for (unsigned int n = 0; n <= qlimit;) {
  10721. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10722. std::unique_lock<std::mutex> lock(sem_mtx);
  10723. while (credits <= 0) {
  10724. sem_cv.wait(lock);
  10725. }
  10726. /* Consume the credit and signal the test code if they are all gone. */
  10727. if (--credits == 0) { sem_cv.notify_one(); }
  10728. });
  10729. if (n < qlimit) {
  10730. /* The first qlimit enqueues must succeed. */
  10731. EXPECT_TRUE(queued);
  10732. } else {
  10733. /* The last one will succeed only when the worker thread
  10734. * starts and dequeues the first blocking task. Although
  10735. * not necessary for the correctness of this test, we sleep for
  10736. * a short while to avoid busy waiting. */
  10737. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10738. }
  10739. if (queued) { n++; }
  10740. }
  10741. /* Further enqueues must fail since the queue is full. */
  10742. for (auto i = 0; i < 4; i++) {
  10743. queued = task_queue->enqueue([] {});
  10744. EXPECT_FALSE(queued);
  10745. }
  10746. /* Give the credits to allow the previous tasks to complete. */
  10747. {
  10748. std::unique_lock<std::mutex> lock(sem_mtx);
  10749. credits += qlimit + 1;
  10750. }
  10751. sem_cv.notify_all();
  10752. /* Wait for all the credits to be consumed. */
  10753. {
  10754. std::unique_lock<std::mutex> lock(sem_mtx);
  10755. while (credits > 0) {
  10756. sem_cv.wait(lock);
  10757. }
  10758. }
  10759. /* Check that we are able again to enqueue at least qlimit tasks. */
  10760. for (unsigned int i = 0; i < qlimit; i++) {
  10761. queued = task_queue->enqueue([] {});
  10762. EXPECT_TRUE(queued);
  10763. }
  10764. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10765. task_queue->shutdown();
  10766. #else
  10767. EXPECT_NO_THROW(task_queue->shutdown());
  10768. #endif
  10769. }
  10770. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10771. Server svr;
  10772. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10773. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10774. });
  10775. svr.Get("/hello", [](const Request &req, Response &res) {
  10776. res.set_content(req.get_param_value("key"), "text/plain");
  10777. });
  10778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10779. auto se = detail::scope_exit([&] {
  10780. svr.stop();
  10781. thread.join();
  10782. ASSERT_FALSE(svr.is_running());
  10783. });
  10784. svr.wait_until_ready();
  10785. {
  10786. Client cli(HOST, PORT);
  10787. cli.set_follow_location(true);
  10788. auto res = cli.Get("/");
  10789. ASSERT_TRUE(res);
  10790. EXPECT_EQ(StatusCode::OK_200, res->status);
  10791. EXPECT_EQ("val&key2=val2", res->body);
  10792. }
  10793. }
  10794. #endif
  10795. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10796. Server svr;
  10797. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10798. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10799. });
  10800. svr.Get("/hello", [](const Request &req, Response &res) {
  10801. res.set_content(req.get_param_value("key"), "text/plain");
  10802. });
  10803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10804. auto se = detail::scope_exit([&] {
  10805. svr.stop();
  10806. thread.join();
  10807. ASSERT_FALSE(svr.is_running());
  10808. });
  10809. svr.wait_until_ready();
  10810. {
  10811. Client cli(HOST, PORT);
  10812. cli.set_follow_location(true);
  10813. auto res = cli.Get("/");
  10814. ASSERT_TRUE(res);
  10815. EXPECT_EQ(StatusCode::OK_200, res->status);
  10816. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10817. }
  10818. }
  10819. TEST(RedirectTest, RedirectWithPlusInPath) {
  10820. Server svr;
  10821. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10822. res.set_redirect("/a+b");
  10823. });
  10824. // Route pattern uses regex; escape + as \\+
  10825. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10826. res.set_content(req.path, "text/plain");
  10827. });
  10828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10829. auto se = detail::scope_exit([&] {
  10830. svr.stop();
  10831. thread.join();
  10832. ASSERT_FALSE(svr.is_running());
  10833. });
  10834. svr.wait_until_ready();
  10835. {
  10836. Client cli(HOST, PORT);
  10837. cli.set_follow_location(true);
  10838. auto res = cli.Get("/");
  10839. ASSERT_TRUE(res);
  10840. EXPECT_EQ(StatusCode::OK_200, res->status);
  10841. EXPECT_EQ("/a+b", res->body);
  10842. }
  10843. }
  10844. #ifdef CPPHTTPLIB_SSL_ENABLED
  10845. TEST(RedirectTest, Issue2185_Online) {
  10846. SSLClient client("github.com");
  10847. client.set_follow_location(true);
  10848. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10849. "Coollab-Windows.zip");
  10850. ASSERT_TRUE(res);
  10851. EXPECT_EQ(StatusCode::OK_200, res->status);
  10852. EXPECT_EQ(9920427U, res->body.size());
  10853. }
  10854. #endif
  10855. TEST(VulnerabilityTest, CRLFInjection) {
  10856. Server svr;
  10857. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10858. res.set_content("Hello 1", "text/plain");
  10859. });
  10860. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10861. res.set_content("Hello 2", "text/plain");
  10862. });
  10863. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10864. res.set_content("Hello 3", "text/plain");
  10865. });
  10866. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10867. res.set_content("Hello 4", "text/plain");
  10868. });
  10869. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10870. for (const auto &x : req.headers) {
  10871. auto key = x.first;
  10872. EXPECT_STRNE("evil", key.c_str());
  10873. }
  10874. });
  10875. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10876. auto se = detail::scope_exit([&] {
  10877. svr.stop();
  10878. thread.join();
  10879. ASSERT_FALSE(svr.is_running());
  10880. });
  10881. svr.wait_until_ready();
  10882. {
  10883. Client cli(HOST, PORT);
  10884. cli.Post("/test1", "A=B",
  10885. "application/x-www-form-urlencoded\r\nevil: hello1");
  10886. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10887. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10888. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10889. }
  10890. }
  10891. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10892. auto server_thread = std::thread([] {
  10893. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10894. default_socket_options(srv);
  10895. sockaddr_in addr{};
  10896. addr.sin_family = AF_INET;
  10897. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10898. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10899. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10900. ::listen(srv, 1);
  10901. sockaddr_in cli_addr{};
  10902. socklen_t cli_len = sizeof(cli_addr);
  10903. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10904. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10905. std::string buf_all;
  10906. char buf[2048];
  10907. ssize_t n;
  10908. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10909. buf_all.append(buf, static_cast<size_t>(n));
  10910. size_t pos;
  10911. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10912. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10913. auto e = request_block.find("\r\n");
  10914. if (e != std::string::npos) {
  10915. auto request_line = request_block.substr(0, e);
  10916. std::string msg =
  10917. "CRLF injection detected in request line: '" + request_line + "'";
  10918. EXPECT_FALSE(true) << msg;
  10919. }
  10920. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10921. ::send(cli,
  10922. #ifdef _WIN32
  10923. static_cast<const char *>(resp.c_str()),
  10924. static_cast<int>(resp.size()),
  10925. #else
  10926. resp.c_str(), resp.size(),
  10927. #endif
  10928. 0);
  10929. buf_all.erase(0, pos + 4);
  10930. }
  10931. }
  10932. detail::close_socket(cli);
  10933. detail::close_socket(srv);
  10934. });
  10935. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10936. auto cli = Client("127.0.0.1", PORT + 1);
  10937. auto headers = Headers{
  10938. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10939. {"Connection", "keep-alive"}};
  10940. auto res = cli.Get("/hi", headers);
  10941. EXPECT_FALSE(res);
  10942. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10943. server_thread.join();
  10944. }
  10945. TEST(PathParamsTest, StaticMatch) {
  10946. const auto pattern = "/users/all";
  10947. detail::PathParamsMatcher matcher(pattern);
  10948. Request request;
  10949. request.path = "/users/all";
  10950. ASSERT_TRUE(matcher.match(request));
  10951. std::unordered_map<std::string, std::string> expected_params = {};
  10952. EXPECT_EQ(request.path_params, expected_params);
  10953. }
  10954. TEST(PathParamsTest, StaticMismatch) {
  10955. const auto pattern = "/users/all";
  10956. detail::PathParamsMatcher matcher(pattern);
  10957. Request request;
  10958. request.path = "/users/1";
  10959. ASSERT_FALSE(matcher.match(request));
  10960. }
  10961. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10962. const auto pattern = "/users/:id/subscriptions";
  10963. detail::PathParamsMatcher matcher(pattern);
  10964. Request request;
  10965. request.path = "/users/42/subscriptions";
  10966. ASSERT_TRUE(matcher.match(request));
  10967. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10968. EXPECT_EQ(request.path_params, expected_params);
  10969. }
  10970. TEST(PathParamsTest, SingleParamInTheEnd) {
  10971. const auto pattern = "/users/:id";
  10972. detail::PathParamsMatcher matcher(pattern);
  10973. Request request;
  10974. request.path = "/users/24";
  10975. ASSERT_TRUE(matcher.match(request));
  10976. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10977. EXPECT_EQ(request.path_params, expected_params);
  10978. }
  10979. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10980. const auto pattern = "/users/:id/";
  10981. detail::PathParamsMatcher matcher(pattern);
  10982. Request request;
  10983. request.path = "/users/42/";
  10984. ASSERT_TRUE(matcher.match(request));
  10985. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10986. EXPECT_EQ(request.path_params, expected_params);
  10987. }
  10988. TEST(PathParamsTest, EmptyParam) {
  10989. const auto pattern = "/users/:id/";
  10990. detail::PathParamsMatcher matcher(pattern);
  10991. Request request;
  10992. request.path = "/users//";
  10993. ASSERT_TRUE(matcher.match(request));
  10994. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10995. EXPECT_EQ(request.path_params, expected_params);
  10996. }
  10997. TEST(PathParamsTest, FragmentMismatch) {
  10998. const auto pattern = "/users/:id/";
  10999. detail::PathParamsMatcher matcher(pattern);
  11000. Request request;
  11001. request.path = "/admins/24/";
  11002. ASSERT_FALSE(matcher.match(request));
  11003. }
  11004. TEST(PathParamsTest, ExtraFragments) {
  11005. const auto pattern = "/users/:id";
  11006. detail::PathParamsMatcher matcher(pattern);
  11007. Request request;
  11008. request.path = "/users/42/subscriptions";
  11009. ASSERT_FALSE(matcher.match(request));
  11010. }
  11011. TEST(PathParamsTest, MissingTrailingParam) {
  11012. const auto pattern = "/users/:id";
  11013. detail::PathParamsMatcher matcher(pattern);
  11014. Request request;
  11015. request.path = "/users";
  11016. ASSERT_FALSE(matcher.match(request));
  11017. }
  11018. TEST(PathParamsTest, MissingParamInTheMiddle) {
  11019. const auto pattern = "/users/:id/subscriptions";
  11020. detail::PathParamsMatcher matcher(pattern);
  11021. Request request;
  11022. request.path = "/users/subscriptions";
  11023. ASSERT_FALSE(matcher.match(request));
  11024. }
  11025. TEST(PathParamsTest, MultipleParams) {
  11026. const auto pattern = "/users/:userid/subscriptions/:subid";
  11027. detail::PathParamsMatcher matcher(pattern);
  11028. Request request;
  11029. request.path = "/users/42/subscriptions/2";
  11030. ASSERT_TRUE(matcher.match(request));
  11031. std::unordered_map<std::string, std::string> expected_params = {
  11032. {"userid", "42"}, {"subid", "2"}};
  11033. EXPECT_EQ(request.path_params, expected_params);
  11034. }
  11035. TEST(PathParamsTest, SequenceOfParams) {
  11036. const auto pattern = "/values/:x/:y/:z";
  11037. detail::PathParamsMatcher matcher(pattern);
  11038. Request request;
  11039. request.path = "/values/1/2/3";
  11040. ASSERT_TRUE(matcher.match(request));
  11041. std::unordered_map<std::string, std::string> expected_params = {
  11042. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  11043. EXPECT_EQ(request.path_params, expected_params);
  11044. }
  11045. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  11046. const auto pattern = "/prefix:suffix";
  11047. detail::PathParamsMatcher matcher(pattern);
  11048. Request request;
  11049. request.path = "/prefix:suffix";
  11050. ASSERT_TRUE(matcher.match(request));
  11051. const std::unordered_map<std::string, std::string> expected_params = {};
  11052. EXPECT_EQ(request.path_params, expected_params);
  11053. }
  11054. TEST(ParseUrlTest, VariousPatterns) {
  11055. {
  11056. detail::UrlComponents uc;
  11057. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  11058. EXPECT_EQ("http", uc.scheme);
  11059. EXPECT_EQ("example.com", uc.host);
  11060. EXPECT_EQ("8080", uc.port);
  11061. EXPECT_EQ("/path", uc.path);
  11062. EXPECT_EQ("?q=1", uc.query);
  11063. }
  11064. {
  11065. detail::UrlComponents uc;
  11066. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  11067. EXPECT_EQ("https", uc.scheme);
  11068. EXPECT_EQ("example.com", uc.host);
  11069. EXPECT_TRUE(uc.port.empty());
  11070. EXPECT_EQ("/path", uc.path);
  11071. }
  11072. {
  11073. detail::UrlComponents uc;
  11074. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  11075. EXPECT_EQ("::1", uc.host);
  11076. EXPECT_EQ("8080", uc.port);
  11077. EXPECT_EQ("/path", uc.path);
  11078. }
  11079. {
  11080. detail::UrlComponents uc;
  11081. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  11082. }
  11083. {
  11084. detail::UrlComponents uc;
  11085. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  11086. EXPECT_TRUE(uc.scheme.empty());
  11087. EXPECT_EQ("example.com", uc.host);
  11088. EXPECT_EQ("/path", uc.path);
  11089. EXPECT_EQ("?q=1", uc.query);
  11090. }
  11091. {
  11092. detail::UrlComponents uc;
  11093. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  11094. EXPECT_TRUE(uc.host.empty());
  11095. EXPECT_EQ("/path", uc.path);
  11096. EXPECT_EQ("?q=1", uc.query);
  11097. }
  11098. {
  11099. detail::UrlComponents uc;
  11100. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  11101. EXPECT_EQ("example.com", uc.host);
  11102. EXPECT_EQ("8080", uc.port);
  11103. }
  11104. {
  11105. // Unix socket path — must not be parsed as host
  11106. detail::UrlComponents uc;
  11107. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  11108. EXPECT_TRUE(uc.host.empty());
  11109. }
  11110. {
  11111. detail::UrlComponents uc;
  11112. ASSERT_TRUE(detail::parse_url("", uc));
  11113. EXPECT_TRUE(uc.host.empty());
  11114. EXPECT_TRUE(uc.path.empty());
  11115. }
  11116. {
  11117. detail::UrlComponents uc;
  11118. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  11119. }
  11120. {
  11121. detail::UrlComponents uc;
  11122. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  11123. }
  11124. {
  11125. // Accepted by parse_url; callers restrict to http/https
  11126. detail::UrlComponents uc;
  11127. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  11128. EXPECT_EQ("ftp", uc.scheme);
  11129. }
  11130. {
  11131. detail::UrlComponents uc;
  11132. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  11133. }
  11134. {
  11135. detail::UrlComponents uc;
  11136. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  11137. }
  11138. }
  11139. TEST(ParseUrlTest, FragmentHandling) {
  11140. {
  11141. detail::UrlComponents uc;
  11142. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  11143. EXPECT_EQ("/path", uc.path);
  11144. EXPECT_TRUE(uc.query.empty());
  11145. }
  11146. {
  11147. detail::UrlComponents uc;
  11148. ASSERT_TRUE(detail::parse_url("#frag", uc));
  11149. EXPECT_TRUE(uc.path.empty());
  11150. EXPECT_TRUE(uc.query.empty());
  11151. }
  11152. }
  11153. TEST(ParseUrlTest, UserinfoHandling) {
  11154. // Userinfo with @ but no colon — host includes @
  11155. detail::UrlComponents uc;
  11156. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  11157. EXPECT_EQ("user@host.com", uc.host);
  11158. EXPECT_EQ("/path", uc.path);
  11159. }
  11160. TEST(ParseUrlTest, IPv6EdgeCases) {
  11161. {
  11162. detail::UrlComponents uc;
  11163. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  11164. EXPECT_TRUE(uc.scheme.empty());
  11165. EXPECT_EQ("::1", uc.host);
  11166. EXPECT_EQ("8080", uc.port);
  11167. }
  11168. {
  11169. // Zone ID '%25' is not in [a-fA-F0-9:]
  11170. detail::UrlComponents uc;
  11171. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  11172. }
  11173. }
  11174. TEST(ParseUrlTest, SchemeEdgeCases) {
  11175. {
  11176. detail::UrlComponents uc;
  11177. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  11178. }
  11179. {
  11180. detail::UrlComponents uc;
  11181. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  11182. }
  11183. {
  11184. detail::UrlComponents uc;
  11185. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  11186. }
  11187. }
  11188. TEST(ParseUrlTest, PortEdgeCases) {
  11189. {
  11190. detail::UrlComponents uc;
  11191. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  11192. EXPECT_TRUE(uc.port.empty());
  11193. EXPECT_EQ("/path", uc.path);
  11194. }
  11195. {
  11196. // parse_url accepts any port string; validation is done by parse_port
  11197. detail::UrlComponents uc;
  11198. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  11199. EXPECT_EQ("abc", uc.port);
  11200. }
  11201. }
  11202. TEST(ParseUrlTest, WebSocketPatterns) {
  11203. {
  11204. detail::UrlComponents uc;
  11205. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  11206. EXPECT_EQ("ws", uc.scheme);
  11207. EXPECT_EQ("echo.example.com", uc.host);
  11208. EXPECT_EQ("8080", uc.port);
  11209. EXPECT_EQ("/ws", uc.path);
  11210. }
  11211. {
  11212. detail::UrlComponents uc;
  11213. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  11214. EXPECT_EQ("wss", uc.scheme);
  11215. EXPECT_EQ("echo.example.com", uc.host);
  11216. EXPECT_TRUE(uc.port.empty());
  11217. EXPECT_EQ("/ws", uc.path);
  11218. }
  11219. }
  11220. TEST(ParseUrlTest, QueryOnly) {
  11221. detail::UrlComponents uc;
  11222. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  11223. EXPECT_TRUE(uc.host.empty());
  11224. EXPECT_TRUE(uc.path.empty());
  11225. EXPECT_EQ("?q=1&r=2", uc.query);
  11226. }
  11227. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  11228. detail::UrlComponents uc;
  11229. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  11230. EXPECT_TRUE(uc.scheme.empty());
  11231. EXPECT_EQ("example.com", uc.host);
  11232. EXPECT_EQ("443", uc.port);
  11233. EXPECT_EQ("/path", uc.path);
  11234. }
  11235. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  11236. // If ipv6 regex working, regex match codepath is taken.
  11237. // else port will default to 80 in Client impl
  11238. int clientImplMagicPort = 80;
  11239. int port = 4321;
  11240. // above ports must be different to avoid false negative
  11241. EXPECT_NE(clientImplMagicPort, port);
  11242. std::string ipV6TestURL = "http://[ff06::c3]";
  11243. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  11244. CLIENT_PRIVATE_KEY_FILE);
  11245. EXPECT_EQ(cli.port(), port);
  11246. }
  11247. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  11248. auto file_path = "./www/dir/index.html";
  11249. auto dir_path = "./www/dir";
  11250. detail::FileStat stat_file(file_path);
  11251. EXPECT_TRUE(stat_file.is_file());
  11252. EXPECT_FALSE(stat_file.is_dir());
  11253. detail::FileStat stat_dir(dir_path);
  11254. EXPECT_FALSE(stat_dir.is_file());
  11255. EXPECT_TRUE(stat_dir.is_dir());
  11256. }
  11257. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  11258. // IPv4 with default HTTP port (80)
  11259. EXPECT_EQ("example.com",
  11260. detail::make_host_and_port_string("example.com", 80, false));
  11261. // IPv4 with default HTTPS port (443)
  11262. EXPECT_EQ("example.com",
  11263. detail::make_host_and_port_string("example.com", 443, true));
  11264. // IPv4 with non-default HTTP port
  11265. EXPECT_EQ("example.com:8080",
  11266. detail::make_host_and_port_string("example.com", 8080, false));
  11267. // IPv4 with non-default HTTPS port
  11268. EXPECT_EQ("example.com:8443",
  11269. detail::make_host_and_port_string("example.com", 8443, true));
  11270. // IPv6 with default HTTP port (80)
  11271. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  11272. // IPv6 with default HTTPS port (443)
  11273. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  11274. // IPv6 with non-default HTTP port
  11275. EXPECT_EQ("[::1]:8080",
  11276. detail::make_host_and_port_string("::1", 8080, false));
  11277. // IPv6 with non-default HTTPS port
  11278. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  11279. // IPv6 full address with default port
  11280. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  11281. detail::make_host_and_port_string(
  11282. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  11283. // IPv6 full address with non-default port
  11284. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  11285. detail::make_host_and_port_string(
  11286. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  11287. // IPv6 localhost with non-default port
  11288. EXPECT_EQ("[::1]:3000",
  11289. detail::make_host_and_port_string("::1", 3000, false));
  11290. // IPv6 with zone ID (link-local address) with default port
  11291. EXPECT_EQ("[fe80::1%eth0]",
  11292. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  11293. // IPv6 with zone ID (link-local address) with non-default port
  11294. EXPECT_EQ("[fe80::1%eth0]:8080",
  11295. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  11296. // Edge case: Port 443 with is_ssl=false (should add port)
  11297. EXPECT_EQ("example.com:443",
  11298. detail::make_host_and_port_string("example.com", 443, false));
  11299. // Edge case: Port 80 with is_ssl=true (should add port)
  11300. EXPECT_EQ("example.com:80",
  11301. detail::make_host_and_port_string("example.com", 80, true));
  11302. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11303. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11304. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11305. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11306. // Security fix: Already bracketed IPv6 should not get double brackets
  11307. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11308. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11309. EXPECT_EQ("[::1]:8080",
  11310. detail::make_host_and_port_string("[::1]", 8080, false));
  11311. EXPECT_EQ("[2001:db8::1]:8080",
  11312. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11313. EXPECT_EQ("[fe80::1%eth0]",
  11314. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11315. EXPECT_EQ("[fe80::1%eth0]:8080",
  11316. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11317. // Edge case: Empty host (should return as-is)
  11318. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11319. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11320. // This is a known limitation but shouldn't crash
  11321. EXPECT_EQ("[host:name]",
  11322. detail::make_host_and_port_string("host:name", 80, false));
  11323. // Port number edge cases (no validation, but should not crash)
  11324. EXPECT_EQ("example.com:0",
  11325. detail::make_host_and_port_string("example.com", 0, false));
  11326. EXPECT_EQ("example.com:-1",
  11327. detail::make_host_and_port_string("example.com", -1, false));
  11328. EXPECT_EQ("example.com:65535",
  11329. detail::make_host_and_port_string("example.com", 65535, false));
  11330. EXPECT_EQ("example.com:65536",
  11331. detail::make_host_and_port_string("example.com", 65536, false));
  11332. }
  11333. #ifdef CPPHTTPLIB_SSL_ENABLED
  11334. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11335. httplib::SSLClient cli("roblox.com", 443);
  11336. cli.set_follow_location(true);
  11337. auto res = cli.Get("/");
  11338. ASSERT_TRUE(res);
  11339. EXPECT_EQ(StatusCode::OK_200, res->status);
  11340. }
  11341. #endif
  11342. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11343. Server svr;
  11344. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11345. EXPECT_EQ(res.status, 400);
  11346. });
  11347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11348. auto se = detail::scope_exit([&] {
  11349. svr.stop();
  11350. thread.join();
  11351. ASSERT_FALSE(svr.is_running());
  11352. });
  11353. svr.wait_until_ready();
  11354. Client cli(HOST, PORT);
  11355. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11356. }
  11357. TEST(InvalidHeaderCharsTest, is_field_name) {
  11358. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11359. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11360. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11361. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11362. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11363. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11364. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11365. EXPECT_FALSE(detail::fields::is_field_name(""));
  11366. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11367. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11368. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11369. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11370. }
  11371. TEST(InvalidHeaderCharsTest, is_field_value) {
  11372. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11373. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11374. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11375. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11376. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11377. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11378. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11379. EXPECT_TRUE(detail::fields::is_field_value(""));
  11380. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11381. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11382. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11383. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11384. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11385. }
  11386. TEST(InvalidHeaderCharsTest, OnServer) {
  11387. Server svr;
  11388. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11389. std::string header = "Not Set";
  11390. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11391. res.set_header(header, "value");
  11392. res.set_content("Page Content Page Content", "text/plain");
  11393. });
  11394. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11395. std::string header = "Not Set";
  11396. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11397. res.set_header("X-Test", header);
  11398. res.set_content("Page Content Page Content", "text/plain");
  11399. });
  11400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11401. auto se = detail::scope_exit([&] {
  11402. svr.stop();
  11403. thread.join();
  11404. ASSERT_FALSE(svr.is_running());
  11405. });
  11406. svr.wait_until_ready();
  11407. Client cli(HOST, PORT);
  11408. {
  11409. auto res = cli.Get(
  11410. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11411. ASSERT_TRUE(res);
  11412. EXPECT_EQ("Page Content Page Content", res->body);
  11413. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11414. }
  11415. {
  11416. auto res = cli.Get(
  11417. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11418. ASSERT_TRUE(res);
  11419. EXPECT_EQ("Page Content Page Content", res->body);
  11420. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11421. }
  11422. }
  11423. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11424. auto handled = false;
  11425. Server svr;
  11426. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11427. thread t = thread([&] { svr.listen(HOST, PORT); });
  11428. auto se = detail::scope_exit([&] {
  11429. svr.stop();
  11430. t.join();
  11431. ASSERT_FALSE(svr.is_running());
  11432. ASSERT_FALSE(handled);
  11433. });
  11434. svr.wait_until_ready();
  11435. auto req = "POST /test HTTP/1.1\r\n"
  11436. "Content-Length: x\r\n"
  11437. "\r\n";
  11438. std::string response;
  11439. ASSERT_TRUE(send_request(1, req, &response));
  11440. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11441. response.substr(0, response.find("\r\n")));
  11442. }
  11443. #ifndef _WIN32
  11444. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11445. static constexpr char reject[] = "Unauthorized";
  11446. static constexpr char accept[] = "Upload accepted";
  11447. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11448. Server svr;
  11449. svr.set_expect_100_continue_handler(
  11450. [](const Request & /*req*/, Response &res) {
  11451. res.status = StatusCode::Unauthorized_401;
  11452. res.set_content(reject, "text/plain");
  11453. return res.status;
  11454. });
  11455. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11456. res.set_content(accept, "text/plain");
  11457. });
  11458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11459. auto se = detail::scope_exit([&] {
  11460. svr.stop();
  11461. thread.join();
  11462. ASSERT_FALSE(svr.is_running());
  11463. });
  11464. svr.wait_until_ready();
  11465. {
  11466. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11467. curl_easy_init(), &curl_easy_cleanup};
  11468. ASSERT_NE(curl, nullptr);
  11469. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11470. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11471. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11472. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11473. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11474. &curl_slist_free_all};
  11475. ASSERT_NE(list, nullptr);
  11476. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11477. struct read_data {
  11478. size_t read_size;
  11479. size_t total_size;
  11480. } data = {0, total_size};
  11481. using read_callback_t =
  11482. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11483. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11484. void *userdata) -> size_t {
  11485. read_data *d = (read_data *)userdata;
  11486. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11487. std::fill_n(ptr, size * nmemb, 'A');
  11488. d->read_size += size * nmemb;
  11489. return size * nmemb;
  11490. };
  11491. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11492. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11493. std::vector<char> buffer;
  11494. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11495. using write_callback_t =
  11496. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11497. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11498. void *userdata) -> size_t {
  11499. std::vector<char> *buf = (std::vector<char> *)userdata;
  11500. buf->reserve(buf->size() + size * nmemb + 1);
  11501. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11502. return size * nmemb;
  11503. };
  11504. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11505. {
  11506. const auto res = curl_easy_perform(curl.get());
  11507. ASSERT_EQ(res, CURLE_OK);
  11508. }
  11509. {
  11510. auto response_code = long{};
  11511. const auto res =
  11512. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11513. ASSERT_EQ(res, CURLE_OK);
  11514. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11515. }
  11516. {
  11517. auto dl = curl_off_t{};
  11518. const auto res =
  11519. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11520. ASSERT_EQ(res, CURLE_OK);
  11521. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11522. }
  11523. {
  11524. buffer.push_back('\0');
  11525. ASSERT_STRCASEEQ(buffer.data(), reject);
  11526. }
  11527. }
  11528. }
  11529. #endif
  11530. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  11531. // Regression test for #2458.
  11532. //
  11533. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  11534. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  11535. // ticket can make the client socket spuriously readable during the
  11536. // 100-continue wait. If the readiness is mistaken for an incoming response,
  11537. // the client withholds the body and then blocks reading a response that never
  11538. // comes, failing with `Failed to read connection`.
  11539. //
  11540. // A correct client (like curl) sends the body once no `100 Continue` arrives
  11541. // within the timeout. This raw OpenSSL server deliberately never sends
  11542. // `100 Continue`; the client must still deliver the body and receive 200.
  11543. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  11544. signal(SIGPIPE, SIG_IGN);
  11545. const auto port = PORT + 4;
  11546. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11547. ASSERT_NE(srv, INVALID_SOCKET);
  11548. int opt = 1;
  11549. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  11550. sockaddr_in addr{};
  11551. addr.sin_family = AF_INET;
  11552. addr.sin_port = htons(static_cast<uint16_t>(port));
  11553. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11554. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11555. ASSERT_EQ(0, ::listen(srv, 1));
  11556. std::atomic<size_t> server_body_bytes{0};
  11557. auto server_thread = std::thread([&] {
  11558. sockaddr_in cli_addr{};
  11559. socklen_t cli_len = sizeof(cli_addr);
  11560. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11561. if (cli == INVALID_SOCKET) { return; }
  11562. // Bound the lifetime of the server side so a buggy client (which never
  11563. // sends the body) cannot make this thread block forever on join.
  11564. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  11565. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  11566. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  11567. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  11568. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  11569. SSL *ssl = SSL_new(ctx);
  11570. SSL_set_fd(ssl, static_cast<int>(cli));
  11571. if (SSL_accept(ssl) > 0) {
  11572. // Read the request headers. Reading here also flushes the TLS 1.3
  11573. // session tickets to the client. Deliberately do NOT send
  11574. // `100 Continue`.
  11575. std::string buf;
  11576. char tmp[1024];
  11577. while (buf.find("\r\n\r\n") == std::string::npos) {
  11578. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11579. if (n <= 0) { break; }
  11580. buf.append(tmp, static_cast<size_t>(n));
  11581. }
  11582. // A correct client sends the body now; count what arrives.
  11583. auto pos = buf.find("\r\n\r\n");
  11584. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  11585. while (body < 4096) {
  11586. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  11587. if (n <= 0) { break; }
  11588. body += static_cast<size_t>(n);
  11589. }
  11590. server_body_bytes = body;
  11591. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  11592. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  11593. SSL_shutdown(ssl);
  11594. }
  11595. SSL_free(ssl);
  11596. detail::close_socket(cli);
  11597. SSL_CTX_free(ctx);
  11598. });
  11599. auto se = detail::scope_exit([&] {
  11600. server_thread.join();
  11601. detail::close_socket(srv);
  11602. });
  11603. SSLClient cli("127.0.0.1", port);
  11604. cli.enable_server_certificate_verification(false);
  11605. cli.set_connection_timeout(5, 0);
  11606. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  11607. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  11608. std::string body(4096, 'A');
  11609. auto res = cli.Put("/api/test", body, "application/json");
  11610. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  11611. EXPECT_EQ(StatusCode::OK_200, res->status);
  11612. EXPECT_EQ(body.size(), server_body_bytes.load());
  11613. }
  11614. #endif
  11615. template <typename S, typename C>
  11616. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11617. svr.Get("/stream", [&](const Request &, Response &res) {
  11618. auto data = new std::string("01234567890123456789");
  11619. res.set_content_provider(
  11620. data->size(), "text/plain",
  11621. [&, data](size_t offset, size_t length, DataSink &sink) {
  11622. const size_t DATA_CHUNK_SIZE = 4;
  11623. const auto &d = *data;
  11624. std::this_thread::sleep_for(std::chrono::seconds(1));
  11625. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11626. return true;
  11627. },
  11628. [data](bool success) {
  11629. EXPECT_FALSE(success);
  11630. delete data;
  11631. });
  11632. });
  11633. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11634. auto i = new size_t(0);
  11635. res.set_content_provider(
  11636. "text/plain",
  11637. [i](size_t, DataSink &sink) {
  11638. if (*i < 5) {
  11639. std::this_thread::sleep_for(std::chrono::seconds(1));
  11640. sink.write("abcd", 4);
  11641. (*i)++;
  11642. } else {
  11643. sink.done();
  11644. }
  11645. return true;
  11646. },
  11647. [i](bool success) {
  11648. EXPECT_FALSE(success);
  11649. delete i;
  11650. });
  11651. });
  11652. svr.Get("/chunked", [&](const Request &, Response &res) {
  11653. auto i = new size_t(0);
  11654. res.set_chunked_content_provider(
  11655. "text/plain",
  11656. [i](size_t, DataSink &sink) {
  11657. if (*i < 5) {
  11658. std::this_thread::sleep_for(std::chrono::seconds(1));
  11659. sink.os << "abcd";
  11660. (*i)++;
  11661. } else {
  11662. sink.done();
  11663. }
  11664. return true;
  11665. },
  11666. [i](bool success) {
  11667. EXPECT_FALSE(success);
  11668. delete i;
  11669. });
  11670. });
  11671. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11672. auto se = detail::scope_exit([&] {
  11673. svr.stop();
  11674. listen_thread.join();
  11675. ASSERT_FALSE(svr.is_running());
  11676. });
  11677. svr.wait_until_ready();
  11678. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11679. {
  11680. auto start = std::chrono::steady_clock::now();
  11681. auto res = cli.Get("/stream");
  11682. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11683. std::chrono::steady_clock::now() - start)
  11684. .count();
  11685. ASSERT_FALSE(res);
  11686. EXPECT_EQ(Error::Read, res.error());
  11687. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11688. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11689. }
  11690. {
  11691. auto start = std::chrono::steady_clock::now();
  11692. auto res = cli.Get("/stream_without_length");
  11693. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11694. std::chrono::steady_clock::now() - start)
  11695. .count();
  11696. ASSERT_FALSE(res);
  11697. EXPECT_EQ(Error::Read, res.error());
  11698. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11699. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11700. }
  11701. {
  11702. auto start = std::chrono::steady_clock::now();
  11703. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11704. EXPECT_EQ("abcd", string(data, data_length));
  11705. return true;
  11706. });
  11707. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11708. std::chrono::steady_clock::now() - start)
  11709. .count();
  11710. ASSERT_FALSE(res);
  11711. EXPECT_EQ(Error::Read, res.error());
  11712. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11713. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11714. }
  11715. }
  11716. TEST(MaxTimeoutTest, ContentStream) {
  11717. time_t timeout = 2000;
  11718. time_t threshold = 200;
  11719. Server svr;
  11720. Client cli("localhost", PORT);
  11721. max_timeout_test(svr, cli, timeout, threshold);
  11722. }
  11723. #ifdef CPPHTTPLIB_SSL_ENABLED
  11724. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11725. time_t timeout = 2000;
  11726. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11728. SSLClient cli("localhost", PORT);
  11729. cli.enable_server_certificate_verification(false);
  11730. max_timeout_test(svr, cli, timeout, threshold);
  11731. }
  11732. #endif
  11733. class EventDispatcher {
  11734. public:
  11735. EventDispatcher() {}
  11736. bool wait_event(DataSink *sink) {
  11737. unique_lock<mutex> lk(m_);
  11738. int id = id_;
  11739. // Wait with timeout to prevent hanging if client disconnects
  11740. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11741. [&] { return cid_ == id; })) {
  11742. return false; // Timeout occurred
  11743. }
  11744. sink->write(message_.data(), message_.size());
  11745. return true;
  11746. }
  11747. void send_event(const string &message) {
  11748. lock_guard<mutex> lk(m_);
  11749. cid_ = id_++;
  11750. message_ = message;
  11751. cv_.notify_all();
  11752. }
  11753. private:
  11754. mutex m_;
  11755. condition_variable cv_;
  11756. atomic_int id_{0};
  11757. atomic_int cid_{-1};
  11758. string message_;
  11759. };
  11760. TEST(ClientInThreadTest, Issue2068) {
  11761. EventDispatcher ed;
  11762. Server svr;
  11763. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11764. res.set_chunked_content_provider("text/event-stream",
  11765. [&](size_t /*offset*/, DataSink &sink) {
  11766. return ed.wait_event(&sink);
  11767. });
  11768. });
  11769. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11770. svr.wait_until_ready();
  11771. thread event_thread([&] {
  11772. int id = 0;
  11773. while (svr.is_running()) {
  11774. this_thread::sleep_for(chrono::milliseconds(500));
  11775. std::stringstream ss;
  11776. ss << "data: " << id << "\n\n";
  11777. ed.send_event(ss.str());
  11778. id++;
  11779. }
  11780. });
  11781. auto se = detail::scope_exit([&] {
  11782. svr.stop();
  11783. listen_thread.join();
  11784. event_thread.join();
  11785. ASSERT_FALSE(svr.is_running());
  11786. });
  11787. {
  11788. auto client = detail::make_unique<Client>(HOST, PORT);
  11789. client->set_read_timeout(std::chrono::minutes(10));
  11790. std::atomic<bool> stop{false};
  11791. std::thread t([&] {
  11792. client->Get("/event1",
  11793. [&](const char *, size_t) -> bool { return !stop; });
  11794. });
  11795. std::this_thread::sleep_for(std::chrono::seconds(2));
  11796. stop = true;
  11797. client->stop();
  11798. t.join();
  11799. // Reset client after thread has finished
  11800. client.reset();
  11801. }
  11802. }
  11803. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11804. auto handled = false;
  11805. Server svr;
  11806. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11807. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11808. auto se = detail::scope_exit([&] {
  11809. svr.stop();
  11810. t.join();
  11811. ASSERT_FALSE(svr.is_running());
  11812. ASSERT_FALSE(handled);
  11813. });
  11814. svr.wait_until_ready();
  11815. // Two Content-Length headers with different values — must be rejected
  11816. auto req = "POST /test HTTP/1.1\r\n"
  11817. "Content-Length: 5\r\n"
  11818. "Content-Length: 10\r\n"
  11819. "\r\n"
  11820. "hello";
  11821. std::string response;
  11822. ASSERT_TRUE(send_request(1, req, &response));
  11823. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11824. response.substr(0, response.find("\r\n")));
  11825. }
  11826. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11827. auto handled = false;
  11828. Server svr;
  11829. svr.Post("/test", [&](const Request &, Response &res) {
  11830. handled = true;
  11831. res.set_content("ok", "text/plain");
  11832. });
  11833. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11834. auto se = detail::scope_exit([&] {
  11835. svr.stop();
  11836. t.join();
  11837. ASSERT_FALSE(svr.is_running());
  11838. ASSERT_TRUE(handled);
  11839. });
  11840. svr.wait_until_ready();
  11841. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11842. auto req = "POST /test HTTP/1.1\r\n"
  11843. "Content-Length: 5\r\n"
  11844. "Content-Length: 5\r\n"
  11845. "\r\n"
  11846. "hello";
  11847. std::string response;
  11848. ASSERT_TRUE(send_request(1, req, &response));
  11849. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11850. }
  11851. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11852. Server svr;
  11853. svr.Get("/", [](const Request &req, Response &res) {
  11854. EXPECT_EQ(2U, req.trailers.size());
  11855. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11856. // Denied
  11857. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11858. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11859. // Accepted
  11860. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11861. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11862. EXPECT_TRUE(req.has_trailer("X-World"));
  11863. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11864. res.set_content("ok", "text/plain");
  11865. });
  11866. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11867. auto se = detail::scope_exit([&] {
  11868. svr.stop();
  11869. t.join();
  11870. ASSERT_FALSE(svr.is_running());
  11871. });
  11872. svr.wait_until_ready();
  11873. const std::string req = "GET / HTTP/1.1\r\n"
  11874. "Transfer-Encoding: chunked\r\n"
  11875. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11876. "\r\n"
  11877. "0\r\n"
  11878. "Content-Length: 10\r\n"
  11879. "Host: internal.local\r\n"
  11880. "Content-Type: malicious/content\r\n"
  11881. "Cookie: any\r\n"
  11882. "Set-Cookie: any\r\n"
  11883. "X-Forwarded-For: attacker.com\r\n"
  11884. "X-Real-Ip: 1.1.1.1\r\n"
  11885. "X-Hello: hello\r\n"
  11886. "X-World: world\r\n"
  11887. "\r\n";
  11888. std::string res;
  11889. ASSERT_TRUE(send_request(1, req, &res));
  11890. }
  11891. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11892. Server svr;
  11893. std::string observed_remote_addr;
  11894. std::string observed_xff;
  11895. svr.Get("/ip", [&](const Request &req, Response &res) {
  11896. observed_remote_addr = req.remote_addr;
  11897. observed_xff = req.get_header_value("X-Forwarded-For");
  11898. res.set_content("ok", "text/plain");
  11899. });
  11900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11901. auto se = detail::scope_exit([&] {
  11902. svr.stop();
  11903. t.join();
  11904. ASSERT_FALSE(svr.is_running());
  11905. });
  11906. svr.wait_until_ready();
  11907. Client cli(HOST, PORT);
  11908. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11909. ASSERT_TRUE(res);
  11910. EXPECT_EQ(StatusCode::OK_200, res->status);
  11911. EXPECT_EQ(observed_xff, "203.0.113.66");
  11912. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11913. observed_remote_addr == "127.0.0.1");
  11914. }
  11915. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11916. Server svr;
  11917. svr.set_trusted_proxies({"203.0.113.66"});
  11918. std::string observed_remote_addr;
  11919. std::string observed_xff;
  11920. svr.Get("/ip", [&](const Request &req, Response &res) {
  11921. observed_remote_addr = req.remote_addr;
  11922. observed_xff = req.get_header_value("X-Forwarded-For");
  11923. res.set_content("ok", "text/plain");
  11924. });
  11925. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11926. auto se = detail::scope_exit([&] {
  11927. svr.stop();
  11928. t.join();
  11929. ASSERT_FALSE(svr.is_running());
  11930. });
  11931. svr.wait_until_ready();
  11932. Client cli(HOST, PORT);
  11933. auto res = cli.Get("/ip");
  11934. ASSERT_TRUE(res);
  11935. EXPECT_EQ(StatusCode::OK_200, res->status);
  11936. EXPECT_EQ(observed_xff, "");
  11937. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11938. observed_remote_addr == "127.0.0.1");
  11939. }
  11940. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11941. Server svr;
  11942. svr.set_trusted_proxies({"203.0.113.66"});
  11943. std::string observed_remote_addr;
  11944. std::string observed_xff;
  11945. svr.Get("/ip", [&](const Request &req, Response &res) {
  11946. observed_remote_addr = req.remote_addr;
  11947. observed_xff = req.get_header_value("X-Forwarded-For");
  11948. res.set_content("ok", "text/plain");
  11949. });
  11950. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11951. auto se = detail::scope_exit([&] {
  11952. svr.stop();
  11953. t.join();
  11954. ASSERT_FALSE(svr.is_running());
  11955. });
  11956. svr.wait_until_ready();
  11957. Client cli(HOST, PORT);
  11958. auto res =
  11959. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11960. ASSERT_TRUE(res);
  11961. EXPECT_EQ(StatusCode::OK_200, res->status);
  11962. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11963. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11964. }
  11965. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11966. Server svr;
  11967. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11968. std::string observed_remote_addr;
  11969. std::string observed_xff;
  11970. svr.Get("/ip", [&](const Request &req, Response &res) {
  11971. observed_remote_addr = req.remote_addr;
  11972. observed_xff = req.get_header_value("X-Forwarded-For");
  11973. res.set_content("ok", "text/plain");
  11974. });
  11975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11976. auto se = detail::scope_exit([&] {
  11977. svr.stop();
  11978. t.join();
  11979. ASSERT_FALSE(svr.is_running());
  11980. });
  11981. svr.wait_until_ready();
  11982. Client cli(HOST, PORT);
  11983. auto res = cli.Get(
  11984. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11985. ASSERT_TRUE(res);
  11986. EXPECT_EQ(StatusCode::OK_200, res->status);
  11987. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11988. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11989. }
  11990. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11991. Server svr;
  11992. svr.set_trusted_proxies({"192.0.2.45"});
  11993. std::string observed_remote_addr;
  11994. std::string observed_xff;
  11995. svr.Get("/ip", [&](const Request &req, Response &res) {
  11996. observed_remote_addr = req.remote_addr;
  11997. observed_xff = req.get_header_value("X-Forwarded-For");
  11998. res.set_content("ok", "text/plain");
  11999. });
  12000. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12001. auto se = detail::scope_exit([&] {
  12002. svr.stop();
  12003. t.join();
  12004. ASSERT_FALSE(svr.is_running());
  12005. });
  12006. svr.wait_until_ready();
  12007. Client cli(HOST, PORT);
  12008. auto res =
  12009. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  12010. ASSERT_TRUE(res);
  12011. EXPECT_EQ(StatusCode::OK_200, res->status);
  12012. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  12013. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  12014. }
  12015. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  12016. Server svr;
  12017. svr.set_trusted_proxies({"192.0.2.45"});
  12018. std::string observed_remote_addr;
  12019. std::string observed_xff;
  12020. svr.Get("/ip", [&](const Request &req, Response &res) {
  12021. observed_remote_addr = req.remote_addr;
  12022. observed_xff = req.get_header_value("X-Forwarded-For");
  12023. res.set_content("ok", "text/plain");
  12024. });
  12025. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12026. auto se = detail::scope_exit([&] {
  12027. svr.stop();
  12028. t.join();
  12029. ASSERT_FALSE(svr.is_running());
  12030. });
  12031. svr.wait_until_ready();
  12032. Client cli(HOST, PORT);
  12033. auto res = cli.Get(
  12034. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  12035. ASSERT_TRUE(res);
  12036. EXPECT_EQ(StatusCode::OK_200, res->status);
  12037. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  12038. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12039. }
  12040. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  12041. Server svr;
  12042. svr.set_trusted_proxies({"192.0.2.45"});
  12043. std::string observed_remote_addr;
  12044. std::string observed_xff;
  12045. svr.Get("/ip", [&](const Request &req, Response &res) {
  12046. observed_remote_addr = req.remote_addr;
  12047. observed_xff = req.get_header_value("X-Forwarded-For");
  12048. res.set_content("ok", "text/plain");
  12049. });
  12050. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12051. auto se = detail::scope_exit([&] {
  12052. svr.stop();
  12053. t.join();
  12054. ASSERT_FALSE(svr.is_running());
  12055. });
  12056. svr.wait_until_ready();
  12057. std::string raw_req =
  12058. "GET /ip HTTP/1.1\r\n"
  12059. "Host: localhost\r\n"
  12060. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  12061. "Connection: close\r\n"
  12062. "\r\n";
  12063. std::string out;
  12064. ASSERT_TRUE(send_request(5, raw_req, &out));
  12065. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12066. // Header parser trims surrounding whitespace of the header value
  12067. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  12068. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  12069. }
  12070. // An X-Forwarded-For header whose value parses to zero IP segments must not
  12071. // crash the server (it used to call front() on an empty vector inside
  12072. // get_client_ip). The connection-level remote address must be retained instead.
  12073. static void run_malformed_xff_test(const std::string &xff_value) {
  12074. Server svr;
  12075. svr.set_trusted_proxies({"192.0.2.45"});
  12076. std::string observed_remote_addr;
  12077. svr.Get("/ip", [&](const Request &req, Response &res) {
  12078. observed_remote_addr = req.remote_addr;
  12079. res.set_content("ok", "text/plain");
  12080. });
  12081. int port = 0;
  12082. thread t = thread([&]() {
  12083. port = svr.bind_to_any_port(HOST);
  12084. svr.listen_after_bind();
  12085. });
  12086. auto se = detail::scope_exit([&] {
  12087. svr.stop();
  12088. t.join();
  12089. ASSERT_FALSE(svr.is_running());
  12090. });
  12091. svr.wait_until_ready();
  12092. Client cli(HOST, port);
  12093. auto res = cli.Get("/ip", {{"X-Forwarded-For", xff_value}});
  12094. ASSERT_TRUE(res);
  12095. EXPECT_EQ(StatusCode::OK_200, res->status);
  12096. EXPECT_TRUE(observed_remote_addr == "::1" ||
  12097. observed_remote_addr == "127.0.0.1");
  12098. }
  12099. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  12100. run_malformed_xff_test("");
  12101. }
  12102. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  12103. run_malformed_xff_test(",");
  12104. }
  12105. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  12106. run_malformed_xff_test(", , ,");
  12107. }
  12108. #ifndef _WIN32
  12109. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  12110. Server svr;
  12111. svr.Post("/post", [&](const Request &req, Response &res) {
  12112. res.set_content(req.body, "text/plain");
  12113. });
  12114. svr.Put("/put", [&](const Request &req, Response &res) {
  12115. res.set_content(req.body, "text/plain");
  12116. });
  12117. svr.Patch("/patch", [&](const Request &req, Response &res) {
  12118. res.set_content(req.body, "text/plain");
  12119. });
  12120. svr.Delete("/delete", [&](const Request &req, Response &res) {
  12121. res.set_content(req.body, "text/plain");
  12122. });
  12123. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12124. auto se = detail::scope_exit([&] {
  12125. svr.stop();
  12126. t.join();
  12127. ASSERT_FALSE(svr.is_running());
  12128. });
  12129. svr.wait_until_ready();
  12130. std::string resp;
  12131. // POST without Content-Length
  12132. ASSERT_TRUE(send_request(5,
  12133. "POST /post HTTP/1.1\r\n"
  12134. "Host: localhost\r\n"
  12135. "Connection: close\r\n"
  12136. "\r\n",
  12137. &resp));
  12138. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12139. // PUT without Content-Length
  12140. resp.clear();
  12141. ASSERT_TRUE(send_request(5,
  12142. "PUT /put HTTP/1.1\r\n"
  12143. "Host: localhost\r\n"
  12144. "Connection: close\r\n"
  12145. "\r\n",
  12146. &resp));
  12147. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12148. // PATCH without Content-Length
  12149. resp.clear();
  12150. ASSERT_TRUE(send_request(5,
  12151. "PATCH /patch HTTP/1.1\r\n"
  12152. "Host: localhost\r\n"
  12153. "Connection: close\r\n"
  12154. "\r\n",
  12155. &resp));
  12156. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12157. // DELETE without Content-Length
  12158. resp.clear();
  12159. ASSERT_TRUE(send_request(5,
  12160. "DELETE /delete HTTP/1.1\r\n"
  12161. "Host: localhost\r\n"
  12162. "Connection: close\r\n"
  12163. "\r\n",
  12164. &resp));
  12165. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  12166. }
  12167. #endif
  12168. //==============================================================================
  12169. // open_stream() Tests
  12170. //==============================================================================
  12171. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  12172. std::string result;
  12173. char buf[8192];
  12174. ssize_t n;
  12175. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12176. result.append(buf, static_cast<size_t>(n));
  12177. }
  12178. return result;
  12179. }
  12180. // Mock stream for unit tests
  12181. class MockStream : public Stream {
  12182. public:
  12183. std::string data;
  12184. size_t pos = 0;
  12185. ssize_t error_after = -1; // -1 = no error
  12186. explicit MockStream(const std::string &d, ssize_t err = -1)
  12187. : data(d), error_after(err) {}
  12188. bool is_readable() const override { return true; }
  12189. bool wait_readable() const override { return true; }
  12190. bool wait_writable() const override { return true; }
  12191. ssize_t read(char *ptr, size_t size) override {
  12192. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  12193. if (pos >= data.size()) return 0;
  12194. size_t limit =
  12195. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  12196. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  12197. std::memcpy(ptr, data.data() + pos, to_read);
  12198. pos += to_read;
  12199. return static_cast<ssize_t>(to_read);
  12200. }
  12201. ssize_t write(const char *, size_t) override { return -1; }
  12202. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  12203. ip = "127.0.0.1";
  12204. port = 0;
  12205. }
  12206. void get_local_ip_and_port(std::string &ip, int &port) const override {
  12207. ip = "127.0.0.1";
  12208. port = 0;
  12209. }
  12210. socket_t socket() const override { return INVALID_SOCKET; }
  12211. time_t duration() const override { return 0; }
  12212. };
  12213. TEST(StreamHandleTest, Basic) {
  12214. ClientImpl::StreamHandle handle;
  12215. EXPECT_FALSE(handle.is_valid());
  12216. handle.response = detail::make_unique<Response>();
  12217. handle.error = Error::Connection;
  12218. EXPECT_FALSE(handle.is_valid());
  12219. handle.error = Error::Success;
  12220. EXPECT_TRUE(handle.is_valid());
  12221. }
  12222. TEST(BodyReaderTest, Basic) {
  12223. MockStream stream("Hello, World!");
  12224. detail::BodyReader reader;
  12225. reader.stream = &stream;
  12226. reader.content_length = 13;
  12227. char buf[32];
  12228. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  12229. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  12230. EXPECT_TRUE(reader.eof);
  12231. }
  12232. TEST(BodyReaderTest, NoStream) {
  12233. detail::BodyReader reader;
  12234. char buf[32];
  12235. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12236. EXPECT_EQ(Error::Connection, reader.last_error);
  12237. }
  12238. TEST(BodyReaderTest, Error) {
  12239. MockStream stream("Hello, World!", 5);
  12240. detail::BodyReader reader;
  12241. reader.stream = &stream;
  12242. reader.content_length = 13;
  12243. char buf[32];
  12244. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  12245. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  12246. EXPECT_EQ(Error::Read, reader.last_error);
  12247. }
  12248. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  12249. // Mock-based StreamHandle tests relying on private internals are removed.
  12250. class OpenStreamTest : public ::testing::Test {
  12251. protected:
  12252. void SetUp() override {
  12253. svr_.Get("/hello", [](const Request &, Response &res) {
  12254. res.set_content("Hello World!", "text/plain");
  12255. });
  12256. svr_.Get("/large", [](const Request &, Response &res) {
  12257. res.set_content(std::string(10000, 'X'), "text/plain");
  12258. });
  12259. svr_.Get("/chunked", [](const Request &, Response &res) {
  12260. res.set_chunked_content_provider("text/plain",
  12261. [](size_t offset, DataSink &sink) {
  12262. if (offset < 15) {
  12263. sink.write("chunk", 5);
  12264. return true;
  12265. }
  12266. sink.done();
  12267. return true;
  12268. });
  12269. });
  12270. svr_.Get("/compressible", [](const Request &, Response &res) {
  12271. res.set_chunked_content_provider("text/plain", [](size_t offset,
  12272. DataSink &sink) {
  12273. if (offset < 100 * 1024) {
  12274. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  12275. sink.write(chunk.data(), chunk.size());
  12276. return true;
  12277. }
  12278. sink.done();
  12279. return true;
  12280. });
  12281. });
  12282. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  12283. [](const Request & /*req*/, Response &res) {
  12284. auto i = new int(0);
  12285. res.set_header("Trailer", "Content-Length, X-Allowed");
  12286. res.set_chunked_content_provider(
  12287. "text/plain",
  12288. [i](size_t /*offset*/, DataSink &sink) {
  12289. switch (*i) {
  12290. case 0: sink.os << "123"; break;
  12291. case 1: sink.os << "456"; break;
  12292. case 2: sink.os << "789"; break;
  12293. case 3: {
  12294. sink.done_with_trailer(
  12295. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  12296. } break;
  12297. }
  12298. (*i)++;
  12299. return true;
  12300. },
  12301. [i](bool success) {
  12302. EXPECT_TRUE(success);
  12303. delete i;
  12304. });
  12305. });
  12306. // Echo headers endpoint for header-related tests
  12307. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  12308. std::string body;
  12309. for (const auto &h : req.headers) {
  12310. body.append(h.first);
  12311. body.push_back(':');
  12312. body.append(h.second);
  12313. body.push_back('\n');
  12314. }
  12315. res.set_content(body, "text/plain");
  12316. });
  12317. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  12318. std::string body;
  12319. for (const auto &h : req.headers) {
  12320. body.append(h.first);
  12321. body.push_back(':');
  12322. body.append(h.second);
  12323. body.push_back('\n');
  12324. }
  12325. res.set_content(body, "text/plain");
  12326. });
  12327. port_ = svr_.bind_to_any_port("127.0.0.1");
  12328. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12329. svr_.wait_until_ready();
  12330. }
  12331. void TearDown() override {
  12332. svr_.stop();
  12333. if (thread_.joinable()) thread_.join();
  12334. }
  12335. Server svr_;
  12336. std::thread thread_;
  12337. int port_ = 0;
  12338. };
  12339. TEST_F(OpenStreamTest, Basic) {
  12340. Client cli("127.0.0.1", port_);
  12341. auto handle = cli.open_stream("GET", "/hello");
  12342. EXPECT_TRUE(handle.is_valid());
  12343. EXPECT_EQ("Hello World!", read_all(handle));
  12344. }
  12345. TEST_F(OpenStreamTest, SmallBuffer) {
  12346. Client cli("127.0.0.1", port_);
  12347. auto handle = cli.open_stream("GET", "/hello");
  12348. std::string result;
  12349. char buf[4];
  12350. ssize_t n;
  12351. while ((n = handle.read(buf, sizeof(buf))) > 0)
  12352. result.append(buf, static_cast<size_t>(n));
  12353. EXPECT_EQ("Hello World!", result);
  12354. }
  12355. TEST_F(OpenStreamTest, DefaultHeaders) {
  12356. Client cli("127.0.0.1", port_);
  12357. // open_stream GET should include Host, User-Agent and Accept-Encoding
  12358. {
  12359. auto handle = cli.open_stream("GET", "/echo-headers");
  12360. ASSERT_TRUE(handle.is_valid());
  12361. auto body = read_all(handle);
  12362. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  12363. std::string::npos);
  12364. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  12365. std::string::npos);
  12366. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  12367. }
  12368. // open_stream POST with body and no explicit content_type should NOT add
  12369. // text/plain Content-Type (behavior differs from non-streaming path), but
  12370. // should include Content-Length
  12371. {
  12372. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  12373. ASSERT_TRUE(handle.is_valid());
  12374. auto body = read_all(handle);
  12375. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  12376. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  12377. }
  12378. // open_stream POST with explicit Content-Type should preserve it
  12379. {
  12380. auto handle = cli.open_stream("POST", "/echo-headers", {},
  12381. {{"Content-Type", "application/custom"}},
  12382. "{}", "application/custom");
  12383. ASSERT_TRUE(handle.is_valid());
  12384. auto body = read_all(handle);
  12385. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  12386. }
  12387. // User-specified User-Agent must not be overwritten for stream API
  12388. {
  12389. auto handle = cli.open_stream("GET", "/echo-headers", {},
  12390. {{"User-Agent", "MyAgent/1.2"}});
  12391. ASSERT_TRUE(handle.is_valid());
  12392. auto body = read_all(handle);
  12393. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  12394. }
  12395. }
  12396. TEST_F(OpenStreamTest, Large) {
  12397. Client cli("127.0.0.1", port_);
  12398. auto handle = cli.open_stream("GET", "/large");
  12399. EXPECT_EQ(10000u, read_all(handle).size());
  12400. }
  12401. TEST_F(OpenStreamTest, ConnectionError) {
  12402. Client cli("127.0.0.1", 9999);
  12403. auto handle = cli.open_stream("GET", "/hello");
  12404. EXPECT_FALSE(handle.is_valid());
  12405. }
  12406. TEST_F(OpenStreamTest, Chunked) {
  12407. Client cli("127.0.0.1", port_);
  12408. auto handle = cli.open_stream("GET", "/chunked");
  12409. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12410. "Transfer-Encoding") == "chunked");
  12411. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  12412. }
  12413. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  12414. Client cli("127.0.0.1", port_);
  12415. auto handle =
  12416. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  12417. ASSERT_TRUE(handle.is_valid());
  12418. // Consume body to allow trailers to be received/parsed
  12419. auto body = read_all(handle);
  12420. // Explicitly parse trailers (ensure trailers are available for assertion)
  12421. handle.parse_trailers_if_needed();
  12422. EXPECT_EQ(std::string("123456789"), body);
  12423. // The response should include a Trailer header declaring both names
  12424. ASSERT_TRUE(handle.response);
  12425. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12426. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12427. handle.response->get_header_value("Trailer"));
  12428. // Prohibited trailer must not be present
  12429. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12430. // Allowed trailer should be present
  12431. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12432. EXPECT_EQ(std::string("yes"),
  12433. handle.response->get_trailer_value("X-Allowed"));
  12434. // Verify trailers are NOT present as regular headers
  12435. EXPECT_EQ(std::string(""),
  12436. handle.response->get_header_value("Content-Length"));
  12437. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12438. }
  12439. static std::thread serve_single_response(std::promise<int> &port_promise,
  12440. const std::string &response) {
  12441. return std::thread([&port_promise, response] {
  12442. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12443. default_socket_options(srv);
  12444. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12445. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12446. sockaddr_in addr{};
  12447. addr.sin_family = AF_INET;
  12448. addr.sin_port = htons(0); // Let OS assign a free port
  12449. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12450. int opt = 1;
  12451. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12452. #ifdef _WIN32
  12453. reinterpret_cast<const char *>(&opt),
  12454. #else
  12455. &opt,
  12456. #endif
  12457. sizeof(opt));
  12458. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12459. ::listen(srv, 1) != 0) {
  12460. port_promise.set_value(-1);
  12461. detail::close_socket(srv);
  12462. return;
  12463. }
  12464. socklen_t addr_len = sizeof(addr);
  12465. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12466. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12467. sockaddr_in cli_addr{};
  12468. socklen_t cli_len = sizeof(cli_addr);
  12469. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12470. if (cli != INVALID_SOCKET) {
  12471. // Read the complete HTTP request (until the blank line that terminates
  12472. // headers) before sending the response. If the server closes the socket
  12473. // while the client's request data is still unread in the kernel receive
  12474. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12475. // connection on both sides: it discards the client's receive buffer
  12476. // (which already holds our response) and causes any in-progress write on
  12477. // the client to fail with ECONNRESET. Reading all request data first
  12478. // ensures close() emits a graceful FIN.
  12479. {
  12480. char rbuf[256];
  12481. std::string req;
  12482. while (req.find("\r\n\r\n") == std::string::npos) {
  12483. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12484. if (n <= 0) { break; }
  12485. req.append(rbuf, static_cast<size_t>(n));
  12486. }
  12487. }
  12488. ::send(cli,
  12489. #ifdef _WIN32
  12490. static_cast<const char *>(response.c_str()),
  12491. static_cast<int>(response.size()),
  12492. #else
  12493. response.c_str(), response.size(),
  12494. #endif
  12495. 0);
  12496. detail::close_socket(cli);
  12497. }
  12498. detail::close_socket(srv);
  12499. });
  12500. }
  12501. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12502. #ifndef _WIN32
  12503. signal(SIGPIPE, SIG_IGN);
  12504. #endif
  12505. std::promise<int> port_promise;
  12506. auto port_future = port_promise.get_future();
  12507. auto server_thread =
  12508. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12509. "Content-Type: text/plain\r\n"
  12510. "Content-Length: not-a-number\r\n"
  12511. "Connection: close\r\n"
  12512. "\r\n"
  12513. "hello");
  12514. auto port = port_future.get();
  12515. ASSERT_GT(port, 0);
  12516. Client cli("127.0.0.1", port);
  12517. auto handle = cli.open_stream("GET", "/");
  12518. EXPECT_FALSE(handle.is_valid());
  12519. server_thread.join();
  12520. }
  12521. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12522. #ifndef _WIN32
  12523. signal(SIGPIPE, SIG_IGN);
  12524. #endif
  12525. std::promise<int> port_promise;
  12526. auto port_future = port_promise.get_future();
  12527. auto server_thread = serve_single_response(
  12528. port_promise, "HTTP/1.1 200 OK\r\n"
  12529. "Content-Type: text/plain\r\n"
  12530. "Content-Length: 99999999999999999999999999\r\n"
  12531. "Connection: close\r\n"
  12532. "\r\n"
  12533. "hello");
  12534. auto port = port_future.get();
  12535. ASSERT_GT(port, 0);
  12536. // Before the fix, std::stoull would throw std::out_of_range here and
  12537. // crash the process. After the fix, strtoull silently clamps to
  12538. // ULLONG_MAX so the stream opens without crashing. The important thing
  12539. // is that the process does NOT terminate.
  12540. Client cli("127.0.0.1", port);
  12541. auto handle = cli.open_stream("GET", "/");
  12542. EXPECT_TRUE(handle.is_valid());
  12543. server_thread.join();
  12544. }
  12545. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12546. TEST_F(OpenStreamTest, Gzip) {
  12547. Client cli("127.0.0.1", port_);
  12548. auto handle = cli.open_stream("GET", "/compressible", {},
  12549. {{"Accept-Encoding", "gzip"}});
  12550. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12551. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12552. }
  12553. #endif
  12554. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12555. TEST_F(OpenStreamTest, Brotli) {
  12556. Client cli("127.0.0.1", port_);
  12557. auto handle =
  12558. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12559. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12560. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12561. }
  12562. #endif
  12563. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12564. TEST_F(OpenStreamTest, Zstd) {
  12565. Client cli("127.0.0.1", port_);
  12566. auto handle = cli.open_stream("GET", "/compressible", {},
  12567. {{"Accept-Encoding", "zstd"}});
  12568. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12569. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12570. }
  12571. #endif
  12572. #ifdef CPPHTTPLIB_SSL_ENABLED
  12573. class SSLOpenStreamTest : public ::testing::Test {
  12574. protected:
  12575. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12576. void SetUp() override {
  12577. svr_.Get("/hello", [](const Request &, Response &res) {
  12578. res.set_content("Hello SSL World!", "text/plain");
  12579. });
  12580. svr_.Get("/chunked", [](const Request &, Response &res) {
  12581. res.set_chunked_content_provider("text/plain",
  12582. [](size_t offset, DataSink &sink) {
  12583. if (offset < 15) {
  12584. sink.write("chunk", 5);
  12585. return true;
  12586. }
  12587. sink.done();
  12588. return true;
  12589. });
  12590. });
  12591. svr_.Post("/echo", [](const Request &req, Response &res) {
  12592. res.set_content(req.body, req.get_header_value("Content-Type"));
  12593. });
  12594. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12595. std::string body = req.body;
  12596. res.set_chunked_content_provider(
  12597. "text/plain", [body](size_t offset, DataSink &sink) {
  12598. if (offset < body.size()) {
  12599. sink.write(body.data() + offset, body.size() - offset);
  12600. }
  12601. sink.done();
  12602. return true;
  12603. });
  12604. });
  12605. port_ = svr_.bind_to_any_port("127.0.0.1");
  12606. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12607. svr_.wait_until_ready();
  12608. }
  12609. void TearDown() override {
  12610. svr_.stop();
  12611. if (thread_.joinable()) thread_.join();
  12612. }
  12613. SSLServer svr_;
  12614. std::thread thread_;
  12615. int port_ = 0;
  12616. };
  12617. TEST_F(SSLOpenStreamTest, Basic) {
  12618. SSLClient cli("127.0.0.1", port_);
  12619. cli.enable_server_certificate_verification(false);
  12620. auto handle = cli.open_stream("GET", "/hello");
  12621. ASSERT_TRUE(handle.is_valid());
  12622. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12623. }
  12624. TEST_F(SSLOpenStreamTest, Chunked) {
  12625. SSLClient cli("127.0.0.1", port_);
  12626. cli.enable_server_certificate_verification(false);
  12627. auto handle = cli.open_stream("GET", "/chunked");
  12628. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12629. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12630. "Transfer-Encoding") == "chunked");
  12631. auto body = read_all(handle);
  12632. EXPECT_EQ("chunkchunkchunk", body);
  12633. }
  12634. TEST_F(SSLOpenStreamTest, Post) {
  12635. SSLClient cli("127.0.0.1", port_);
  12636. cli.enable_server_certificate_verification(false);
  12637. auto handle =
  12638. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12639. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12640. EXPECT_EQ(200, handle.response->status);
  12641. auto body = read_all(handle);
  12642. EXPECT_EQ("Hello SSL POST", body);
  12643. }
  12644. TEST_F(SSLOpenStreamTest, PostChunked) {
  12645. SSLClient cli("127.0.0.1", port_);
  12646. cli.enable_server_certificate_verification(false);
  12647. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12648. "Chunked SSL Data", "text/plain");
  12649. ASSERT_TRUE(handle.is_valid());
  12650. EXPECT_EQ(200, handle.response->status);
  12651. auto body = read_all(handle);
  12652. EXPECT_EQ("Chunked SSL Data", body);
  12653. }
  12654. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12655. // Content-Length is terminated by the server closing the connection. When the
  12656. // SSL peer sends a close_notify after the body, the client must treat it as a
  12657. // clean EOF and return a successful response rather than an error.
  12658. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12660. ASSERT_TRUE(svr.is_valid());
  12661. svr.set_keep_alive_max_count(1);
  12662. const std::string expected_body = "Hello from connection-close response!";
  12663. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12664. res.set_content_provider("text/plain",
  12665. [&](size_t offset, DataSink &sink) -> bool {
  12666. if (offset < expected_body.size()) {
  12667. sink.write(expected_body.data() + offset,
  12668. expected_body.size() - offset);
  12669. }
  12670. sink.done();
  12671. return true;
  12672. });
  12673. });
  12674. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12675. auto se = detail::scope_exit([&] {
  12676. svr.stop();
  12677. listen_thread.join();
  12678. ASSERT_FALSE(svr.is_running());
  12679. });
  12680. svr.wait_until_ready();
  12681. SSLClient cli(HOST, PORT);
  12682. cli.enable_server_certificate_verification(false);
  12683. auto res = cli.Get("/no-content-length");
  12684. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12685. EXPECT_EQ(StatusCode::OK_200, res->status);
  12686. EXPECT_EQ(expected_body, res->body);
  12687. }
  12688. #endif // CPPHTTPLIB_SSL_ENABLED
  12689. //==============================================================================
  12690. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12691. // results for various scenarios.
  12692. //==============================================================================
  12693. TEST(ParityTest, GetVsOpenStream) {
  12694. Server svr;
  12695. const std::string path = "/parity";
  12696. const std::string content = "Parity test content: hello world";
  12697. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12698. res.set_content(content, "text/plain");
  12699. });
  12700. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12701. auto se = detail::scope_exit([&] {
  12702. svr.stop();
  12703. t.join();
  12704. ASSERT_FALSE(svr.is_running());
  12705. });
  12706. svr.wait_until_ready();
  12707. Client cli(HOST, PORT);
  12708. // Non-stream path
  12709. auto r1 = cli.Get(path);
  12710. ASSERT_TRUE(r1);
  12711. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12712. // Stream path
  12713. auto h = cli.open_stream("GET", path);
  12714. ASSERT_TRUE(h.is_valid());
  12715. EXPECT_EQ(r1->body, read_all(h));
  12716. }
  12717. // Helper to compress data with provided compressor type T
  12718. template <typename Compressor>
  12719. static std::string compress_payload_for_parity(const std::string &in) {
  12720. std::string out;
  12721. Compressor compressor;
  12722. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12723. [&](const char *data, size_t n) {
  12724. out.append(data, n);
  12725. return true;
  12726. });
  12727. EXPECT_TRUE(ok);
  12728. return out;
  12729. }
  12730. // Helper function for compression parity tests
  12731. template <typename Compressor>
  12732. static void test_compression_parity(const std::string &original,
  12733. const std::string &path,
  12734. const std::string &encoding) {
  12735. const std::string compressed =
  12736. compress_payload_for_parity<Compressor>(original);
  12737. Server svr;
  12738. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12739. res.set_content(compressed, "application/octet-stream");
  12740. res.set_header("Content-Encoding", encoding);
  12741. });
  12742. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12743. auto se = detail::scope_exit([&] {
  12744. svr.stop();
  12745. t.join();
  12746. ASSERT_FALSE(svr.is_running());
  12747. });
  12748. svr.wait_until_ready();
  12749. Client cli(HOST, PORT);
  12750. // Non-streaming
  12751. {
  12752. auto res = cli.Get(path);
  12753. ASSERT_TRUE(res);
  12754. EXPECT_EQ(StatusCode::OK_200, res->status);
  12755. EXPECT_EQ(original, res->body);
  12756. }
  12757. // Streaming
  12758. {
  12759. auto h = cli.open_stream("GET", path);
  12760. ASSERT_TRUE(h.is_valid());
  12761. EXPECT_EQ(original, read_all(h));
  12762. }
  12763. }
  12764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12765. TEST(ParityTest, Gzip) {
  12766. test_compression_parity<detail::gzip_compressor>(
  12767. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12768. }
  12769. #endif
  12770. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12771. TEST(ParityTest, Brotli) {
  12772. test_compression_parity<detail::brotli_compressor>(
  12773. "Hello, brotli parity test payload", "/parity-br", "br");
  12774. }
  12775. #endif
  12776. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12777. TEST(ParityTest, Zstd) {
  12778. test_compression_parity<detail::zstd_compressor>(
  12779. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12780. }
  12781. #endif
  12782. //==============================================================================
  12783. // New Stream API Tests
  12784. //==============================================================================
  12785. inline std::string read_body(httplib::stream::Result &result) {
  12786. std::string body;
  12787. while (result.next()) {
  12788. body.append(result.data(), result.size());
  12789. }
  12790. return body;
  12791. }
  12792. TEST(ClientConnectionTest, Basic) {
  12793. httplib::ClientConnection conn;
  12794. EXPECT_FALSE(conn.is_open());
  12795. conn.sock = 1;
  12796. EXPECT_TRUE(conn.is_open());
  12797. httplib::ClientConnection conn2(std::move(conn));
  12798. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12799. conn2.sock = INVALID_SOCKET;
  12800. }
  12801. // Unified test server for all stream::* tests
  12802. class StreamApiTest : public ::testing::Test {
  12803. protected:
  12804. void SetUp() override {
  12805. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12806. res.set_content("Hello World!", "text/plain");
  12807. });
  12808. svr_.Get("/echo-params",
  12809. [](const httplib::Request &req, httplib::Response &res) {
  12810. std::string r;
  12811. for (const auto &p : req.params) {
  12812. if (!r.empty()) r += "&";
  12813. r += p.first + "=" + p.second;
  12814. }
  12815. res.set_content(r, "text/plain");
  12816. });
  12817. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12818. res.set_content(req.body, req.get_header_value("Content-Type"));
  12819. });
  12820. svr_.Post("/echo-headers",
  12821. [](const httplib::Request &req, httplib::Response &res) {
  12822. std::string r;
  12823. for (const auto &h : req.headers)
  12824. r += h.first + ": " + h.second + "\n";
  12825. res.set_content(r, "text/plain");
  12826. });
  12827. svr_.Post("/echo-params",
  12828. [](const httplib::Request &req, httplib::Response &res) {
  12829. std::string r = "params:";
  12830. for (const auto &p : req.params)
  12831. r += p.first + "=" + p.second + ";";
  12832. res.set_content(r + " body:" + req.body, "text/plain");
  12833. });
  12834. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12835. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12836. });
  12837. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12838. res.set_content("PUT:" + req.body, "text/plain");
  12839. });
  12840. svr_.Patch("/echo",
  12841. [](const httplib::Request &req, httplib::Response &res) {
  12842. res.set_content("PATCH:" + req.body, "text/plain");
  12843. });
  12844. svr_.Delete(
  12845. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12846. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12847. "text/plain");
  12848. });
  12849. svr_.Get("/head-test",
  12850. [](const httplib::Request &, httplib::Response &res) {
  12851. res.set_content("body for HEAD", "text/plain");
  12852. });
  12853. svr_.Options("/options",
  12854. [](const httplib::Request &, httplib::Response &res) {
  12855. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12856. });
  12857. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12858. svr_.wait_until_ready();
  12859. }
  12860. void TearDown() override {
  12861. svr_.stop();
  12862. if (thread_.joinable()) thread_.join();
  12863. }
  12864. httplib::Server svr_;
  12865. std::thread thread_;
  12866. };
  12867. // stream::Get tests
  12868. TEST_F(StreamApiTest, GetBasic) {
  12869. httplib::Client cli(HOST, PORT);
  12870. auto result = httplib::stream::Get(cli, "/hello");
  12871. ASSERT_TRUE(result.is_valid());
  12872. EXPECT_EQ(200, result.status());
  12873. EXPECT_EQ("Hello World!", read_body(result));
  12874. }
  12875. TEST_F(StreamApiTest, GetWithParams) {
  12876. httplib::Client cli(HOST, PORT);
  12877. httplib::Params params{{"foo", "bar"}};
  12878. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12879. ASSERT_TRUE(result.is_valid());
  12880. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12881. }
  12882. TEST_F(StreamApiTest, GetConnectionError) {
  12883. httplib::Client cli(HOST, 9999);
  12884. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12885. }
  12886. TEST_F(StreamApiTest, Get404) {
  12887. httplib::Client cli(HOST, PORT);
  12888. auto result = httplib::stream::Get(cli, "/nonexistent");
  12889. EXPECT_TRUE(result.is_valid());
  12890. EXPECT_EQ(404, result.status());
  12891. }
  12892. // stream::Post tests
  12893. TEST_F(StreamApiTest, PostBasic) {
  12894. httplib::Client cli(HOST, PORT);
  12895. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12896. "application/json");
  12897. ASSERT_TRUE(result.is_valid());
  12898. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12899. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12900. }
  12901. TEST_F(StreamApiTest, PostWithHeaders) {
  12902. httplib::Client cli(HOST, PORT);
  12903. httplib::Headers headers{{"X-Custom", "value"}};
  12904. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12905. "text/plain");
  12906. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12907. }
  12908. TEST_F(StreamApiTest, PostWithParams) {
  12909. httplib::Client cli(HOST, PORT);
  12910. httplib::Params params{{"k", "v"}};
  12911. auto result =
  12912. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12913. auto body = read_body(result);
  12914. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12915. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12916. }
  12917. TEST_F(StreamApiTest, PostLarge) {
  12918. httplib::Client cli(HOST, PORT);
  12919. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12920. size_t total = 0;
  12921. while (result.next()) {
  12922. total += result.size();
  12923. }
  12924. EXPECT_EQ(100u * 1024u, total);
  12925. }
  12926. // stream::Put/Patch tests
  12927. TEST_F(StreamApiTest, PutAndPatch) {
  12928. httplib::Client cli(HOST, PORT);
  12929. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12930. EXPECT_EQ("PUT:test", read_body(put));
  12931. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12932. EXPECT_EQ("PATCH:test", read_body(patch));
  12933. }
  12934. // stream::Delete tests
  12935. TEST_F(StreamApiTest, Delete) {
  12936. httplib::Client cli(HOST, PORT);
  12937. auto del1 = httplib::stream::Delete(cli, "/resource");
  12938. EXPECT_EQ("Deleted", read_body(del1));
  12939. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12940. EXPECT_EQ("Deleted:data", read_body(del2));
  12941. }
  12942. // stream::Head/Options tests
  12943. TEST_F(StreamApiTest, HeadAndOptions) {
  12944. httplib::Client cli(HOST, PORT);
  12945. auto head = httplib::stream::Head(cli, "/head-test");
  12946. EXPECT_TRUE(head.is_valid());
  12947. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12948. auto opts = httplib::stream::Options(cli, "/options");
  12949. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12950. }
  12951. // SSL stream::* tests
  12952. #ifdef CPPHTTPLIB_SSL_ENABLED
  12953. class SSLStreamApiTest : public ::testing::Test {
  12954. protected:
  12955. void SetUp() override {
  12956. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12957. res.set_content("Hello SSL!", "text/plain");
  12958. });
  12959. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12960. res.set_content(req.body, "text/plain");
  12961. });
  12962. port_ = svr_.bind_to_any_port("127.0.0.1");
  12963. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12964. svr_.wait_until_ready();
  12965. }
  12966. void TearDown() override {
  12967. svr_.stop();
  12968. if (thread_.joinable()) thread_.join();
  12969. }
  12970. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12971. std::thread thread_;
  12972. int port_ = 0;
  12973. };
  12974. TEST_F(SSLStreamApiTest, GetAndPost) {
  12975. httplib::SSLClient cli("127.0.0.1", port_);
  12976. cli.enable_server_certificate_verification(false);
  12977. auto get = httplib::stream::Get(cli, "/hello");
  12978. EXPECT_EQ("Hello SSL!", read_body(get));
  12979. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12980. EXPECT_EQ("test", read_body(post));
  12981. }
  12982. #endif
  12983. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12984. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12985. // BodyReader
  12986. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12987. // Test that read timeout during streaming is detected
  12988. // Use a large content-length response where server delays mid-stream
  12989. Server svr;
  12990. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12991. // Send a large response with delay in the middle
  12992. res.set_content_provider(
  12993. 1000, // content_length
  12994. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12995. if (offset < 100) {
  12996. // Send first 100 bytes immediately
  12997. std::string data(100, 'A');
  12998. sink.write(data.c_str(), data.size());
  12999. return true;
  13000. }
  13001. // Then delay longer than client timeout
  13002. std::this_thread::sleep_for(std::chrono::seconds(3));
  13003. std::string data(900, 'B');
  13004. sink.write(data.c_str(), data.size());
  13005. return true;
  13006. });
  13007. });
  13008. auto port = 8091;
  13009. std::thread t([&]() { svr.listen("localhost", port); });
  13010. svr.wait_until_ready();
  13011. Client cli("localhost", port);
  13012. cli.set_read_timeout(1, 0); // 1 second timeout
  13013. auto handle = cli.open_stream("GET", "/slow-stream");
  13014. ASSERT_TRUE(handle.is_valid());
  13015. char buf[256];
  13016. ssize_t total = 0;
  13017. ssize_t n;
  13018. bool got_error = false;
  13019. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13020. total += n;
  13021. }
  13022. if (n < 0) {
  13023. got_error = true;
  13024. // Should be timeout or read error
  13025. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13026. handle.get_read_error() == Error::Read)
  13027. << "Actual error: " << to_string(handle.get_read_error());
  13028. }
  13029. // Either we got an error, or we got less data than expected
  13030. EXPECT_TRUE(got_error || total < 1000)
  13031. << "Expected timeout but got all " << total << " bytes";
  13032. svr.stop();
  13033. t.join();
  13034. }
  13035. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  13036. // Test connection closed detection via BodyReader
  13037. Server svr;
  13038. std::atomic<bool> close_now{false};
  13039. svr.Get("/will-close", [&](const Request &, Response &res) {
  13040. res.set_content_provider(
  13041. 10000, // Large content_length that we won't fully send
  13042. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13043. if (offset < 100) {
  13044. std::string data(100, 'X');
  13045. sink.write(data.c_str(), data.size());
  13046. return true;
  13047. }
  13048. // Wait for signal then abort
  13049. while (!close_now) {
  13050. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13051. }
  13052. return false; // Abort - server will close connection
  13053. });
  13054. });
  13055. auto port = 8092;
  13056. std::thread t([&]() { svr.listen("localhost", port); });
  13057. svr.wait_until_ready();
  13058. Client cli("localhost", port);
  13059. auto handle = cli.open_stream("GET", "/will-close");
  13060. ASSERT_TRUE(handle.is_valid());
  13061. char buf[256];
  13062. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13063. EXPECT_GT(n, 0) << "First read should succeed";
  13064. // Signal server to close
  13065. close_now = true;
  13066. // Keep reading until error or EOF
  13067. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13068. // Keep reading
  13069. }
  13070. // Should get an error since content_length wasn't satisfied
  13071. if (n < 0) {
  13072. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13073. handle.get_read_error() == Error::Read)
  13074. << "Actual error: " << to_string(handle.get_read_error());
  13075. }
  13076. svr.stop();
  13077. t.join();
  13078. }
  13079. #ifdef CPPHTTPLIB_SSL_ENABLED
  13080. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  13081. // Test that read timeout during SSL streaming is detected
  13082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13083. svr.Get("/slow-stream", [](const Request &, Response &res) {
  13084. res.set_content_provider(
  13085. 1000, "text/plain",
  13086. [](size_t offset, size_t /*length*/, DataSink &sink) {
  13087. if (offset < 100) {
  13088. std::string data(100, 'A');
  13089. sink.write(data.c_str(), data.size());
  13090. return true;
  13091. }
  13092. std::this_thread::sleep_for(std::chrono::seconds(3));
  13093. std::string data(900, 'B');
  13094. sink.write(data.c_str(), data.size());
  13095. return true;
  13096. });
  13097. });
  13098. auto port = 8093;
  13099. std::thread t([&]() { svr.listen("localhost", port); });
  13100. svr.wait_until_ready();
  13101. SSLClient cli("localhost", port);
  13102. cli.enable_server_certificate_verification(false);
  13103. cli.set_read_timeout(1, 0); // 1 second timeout
  13104. auto handle = cli.open_stream("GET", "/slow-stream");
  13105. ASSERT_TRUE(handle.is_valid());
  13106. char buf[256];
  13107. ssize_t total = 0;
  13108. ssize_t n;
  13109. bool got_error = false;
  13110. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13111. total += n;
  13112. }
  13113. if (n < 0) {
  13114. got_error = true;
  13115. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  13116. handle.get_read_error() == Error::Read)
  13117. << "Actual error: " << to_string(handle.get_read_error());
  13118. }
  13119. EXPECT_TRUE(got_error || total < 1000)
  13120. << "Expected timeout but got all " << total << " bytes";
  13121. svr.stop();
  13122. t.join();
  13123. }
  13124. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  13125. // Test SSL connection closed detection
  13126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13127. std::atomic<bool> close_now{false};
  13128. svr.Get("/will-close", [&](const Request &, Response &res) {
  13129. res.set_content_provider(
  13130. 10000, "text/plain",
  13131. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  13132. if (offset < 100) {
  13133. std::string data(100, 'X');
  13134. sink.write(data.c_str(), data.size());
  13135. return true;
  13136. }
  13137. while (!close_now) {
  13138. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13139. }
  13140. return false;
  13141. });
  13142. });
  13143. auto port = 8094;
  13144. std::thread t([&]() { svr.listen("localhost", port); });
  13145. svr.wait_until_ready();
  13146. SSLClient cli("localhost", port);
  13147. cli.enable_server_certificate_verification(false);
  13148. auto handle = cli.open_stream("GET", "/will-close");
  13149. ASSERT_TRUE(handle.is_valid());
  13150. char buf[256];
  13151. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  13152. EXPECT_GT(n, 0);
  13153. // Signal server to close
  13154. close_now = true;
  13155. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13156. // Keep reading
  13157. }
  13158. if (n < 0) {
  13159. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  13160. handle.get_read_error() == Error::Read)
  13161. << "Actual error: " << to_string(handle.get_read_error());
  13162. }
  13163. svr.stop();
  13164. t.join();
  13165. }
  13166. #endif
  13167. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  13168. using namespace httplib;
  13169. // Create a test file
  13170. const char *fname = "etag_testfile.txt";
  13171. const char *content = "etag-content";
  13172. {
  13173. std::ofstream ofs(fname);
  13174. ofs << content;
  13175. ASSERT_TRUE(ofs.good());
  13176. }
  13177. Server svr;
  13178. svr.set_mount_point("/static", ".");
  13179. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13180. svr.wait_until_ready();
  13181. Client cli(HOST, PORT);
  13182. // First request: should get 200 with ETag header
  13183. auto res1 = cli.Get("/static/etag_testfile.txt");
  13184. ASSERT_TRUE(res1);
  13185. ASSERT_EQ(200, res1->status);
  13186. ASSERT_TRUE(res1->has_header("ETag"));
  13187. std::string etag = res1->get_header_value("ETag");
  13188. EXPECT_FALSE(etag.empty());
  13189. // Verify ETag format: W/"hex-hex"
  13190. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  13191. EXPECT_EQ('W', etag[0]);
  13192. EXPECT_EQ('/', etag[1]);
  13193. EXPECT_EQ('"', etag[2]);
  13194. EXPECT_EQ('"', etag.back());
  13195. // Exact match: expect 304 Not Modified
  13196. Headers h2 = {{"If-None-Match", etag}};
  13197. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  13198. ASSERT_TRUE(res2);
  13199. EXPECT_EQ(304, res2->status);
  13200. // Wildcard match: expect 304 Not Modified
  13201. Headers h3 = {{"If-None-Match", "*"}};
  13202. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  13203. ASSERT_TRUE(res3);
  13204. EXPECT_EQ(304, res3->status);
  13205. // Non-matching ETag: expect 200
  13206. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  13207. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  13208. ASSERT_TRUE(res4);
  13209. EXPECT_EQ(200, res4->status);
  13210. // Multiple ETags with one matching: expect 304
  13211. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  13212. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  13213. ASSERT_TRUE(res5);
  13214. EXPECT_EQ(304, res5->status);
  13215. svr.stop();
  13216. t.join();
  13217. std::remove(fname);
  13218. }
  13219. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  13220. using namespace httplib;
  13221. Server svr;
  13222. svr.set_mount_point("/static", ".");
  13223. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13224. svr.wait_until_ready();
  13225. Client cli(HOST, PORT);
  13226. // Send If-None-Match: * to a non-existent file
  13227. Headers h = {{"If-None-Match", "*"}};
  13228. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  13229. ASSERT_TRUE(res);
  13230. EXPECT_EQ(404, res->status);
  13231. svr.stop();
  13232. t.join();
  13233. }
  13234. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  13235. using namespace httplib;
  13236. // Create a test file
  13237. const char *fname = "etag_boundary_testfile.txt";
  13238. const char *content = "boundary-test";
  13239. {
  13240. std::ofstream ofs(fname);
  13241. ofs << content;
  13242. ASSERT_TRUE(ofs.good());
  13243. }
  13244. Server svr;
  13245. svr.set_mount_point("/static", ".");
  13246. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  13247. svr.wait_until_ready();
  13248. Client cli(HOST, PORT);
  13249. // Get the actual ETag
  13250. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  13251. ASSERT_TRUE(res1);
  13252. ASSERT_EQ(200, res1->status);
  13253. ASSERT_TRUE(res1->has_header("ETag"));
  13254. std::string etag = res1->get_header_value("ETag");
  13255. // Test 1: Very long ETag value (longer than actual ETag)
  13256. // Should NOT match and return 200 (not trigger out-of-bounds read)
  13257. Headers h1 = {{"If-None-Match", "W/"
  13258. "\"very-long-etag-value-that-is-much-longer-"
  13259. "than-the-actual-etag-value\""}};
  13260. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  13261. ASSERT_TRUE(res2);
  13262. EXPECT_EQ(200, res2->status); // Should not match
  13263. // Test 2: Long string followed by wildcard
  13264. // Should match on "*" and return 304 (without out-of-bounds read on the long
  13265. // string)
  13266. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  13267. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  13268. ASSERT_TRUE(res3);
  13269. EXPECT_EQ(304, res3->status); // Should match on "*"
  13270. // Test 3: Wildcard followed by long string
  13271. // Should match on "*" immediately and return 304
  13272. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  13273. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  13274. ASSERT_TRUE(res4);
  13275. EXPECT_EQ(304, res4->status); // Should match on "*"
  13276. // Test 4: Multiple long non-matching values
  13277. // Should NOT match and return 200 (test that all comparisons are safe)
  13278. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  13279. "W/\"second-long-non-matching-value\", "
  13280. "W/\"third-long-non-matching-value\""}};
  13281. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  13282. ASSERT_TRUE(res5);
  13283. EXPECT_EQ(200, res5->status); // Should not match
  13284. // Test 5: Single character that is not "*" (edge case)
  13285. Headers h5 = {{"If-None-Match", "X"}};
  13286. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  13287. ASSERT_TRUE(res6);
  13288. EXPECT_EQ(200, res6->status); // Should not match
  13289. svr.stop();
  13290. t.join();
  13291. std::remove(fname);
  13292. }
  13293. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  13294. using namespace httplib;
  13295. // Create a test file
  13296. const char *fname = "ims_testfile.txt";
  13297. const char *content = "if-modified-since-test";
  13298. {
  13299. std::ofstream ofs(fname);
  13300. ofs << content;
  13301. ASSERT_TRUE(ofs.good());
  13302. }
  13303. Server svr;
  13304. svr.set_mount_point("/static", ".");
  13305. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13306. svr.wait_until_ready();
  13307. Client cli(HOST, PORT);
  13308. // First request: should get 200 with Last-Modified header
  13309. auto res1 = cli.Get("/static/ims_testfile.txt");
  13310. ASSERT_TRUE(res1);
  13311. ASSERT_EQ(200, res1->status);
  13312. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13313. std::string last_modified = res1->get_header_value("Last-Modified");
  13314. EXPECT_FALSE(last_modified.empty());
  13315. // If-Modified-Since with same time: expect 304
  13316. Headers h2 = {{"If-Modified-Since", last_modified}};
  13317. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  13318. ASSERT_TRUE(res2);
  13319. EXPECT_EQ(304, res2->status);
  13320. // If-Modified-Since with future time: expect 304
  13321. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13322. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  13323. ASSERT_TRUE(res3);
  13324. EXPECT_EQ(304, res3->status);
  13325. // If-Modified-Since with past time: expect 200
  13326. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13327. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  13328. ASSERT_TRUE(res4);
  13329. EXPECT_EQ(200, res4->status);
  13330. // If-None-Match takes precedence over If-Modified-Since
  13331. // (send matching ETag with old If-Modified-Since -> should still be 304)
  13332. ASSERT_TRUE(res1->has_header("ETag"));
  13333. std::string etag = res1->get_header_value("ETag");
  13334. Headers h5 = {{"If-None-Match", etag},
  13335. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13336. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  13337. ASSERT_TRUE(res5);
  13338. EXPECT_EQ(304, res5->status);
  13339. svr.stop();
  13340. t.join();
  13341. std::remove(fname);
  13342. }
  13343. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  13344. using namespace httplib;
  13345. Server svr;
  13346. // Endpoint that returns compressible content
  13347. svr.Get("/compressible", [](const Request &, Response &res) {
  13348. // Return a large enough body to trigger compression
  13349. std::string body(1000, 'a');
  13350. res.set_content(body, "text/plain");
  13351. });
  13352. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13353. svr.wait_until_ready();
  13354. Client cli(HOST, PORT);
  13355. // Request with gzip support: should get Vary header when compressed
  13356. cli.set_compress(true);
  13357. auto res1 = cli.Get("/compressible");
  13358. ASSERT_TRUE(res1);
  13359. EXPECT_EQ(200, res1->status);
  13360. // If Content-Encoding is set, Vary should also be set
  13361. if (res1->has_header("Content-Encoding")) {
  13362. EXPECT_TRUE(res1->has_header("Vary"));
  13363. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  13364. }
  13365. // Request without Accept-Encoding header: should not have compression
  13366. Headers h_no_compress;
  13367. auto res2 = cli.Get("/compressible", h_no_compress);
  13368. ASSERT_TRUE(res2);
  13369. EXPECT_EQ(200, res2->status);
  13370. // Verify Vary header is present when compression is applied
  13371. // (the exact behavior depends on server configuration)
  13372. svr.stop();
  13373. t.join();
  13374. }
  13375. TEST(ETagTest, IfRangeWithETag) {
  13376. using namespace httplib;
  13377. // Create a test file with known content
  13378. const char *fname = "if_range_testfile.txt";
  13379. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  13380. {
  13381. std::ofstream ofs(fname);
  13382. ofs << content;
  13383. ASSERT_TRUE(ofs.good());
  13384. }
  13385. Server svr;
  13386. svr.set_mount_point("/static", ".");
  13387. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13388. svr.wait_until_ready();
  13389. Client cli(HOST, PORT);
  13390. // First request: get ETag
  13391. auto res1 = cli.Get("/static/if_range_testfile.txt");
  13392. ASSERT_TRUE(res1);
  13393. ASSERT_EQ(200, res1->status);
  13394. ASSERT_TRUE(res1->has_header("ETag"));
  13395. std::string etag = res1->get_header_value("ETag");
  13396. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  13397. // Since our server generates weak ETags (W/"..."), If-Range with our
  13398. // ETag should NOT result in partial content - it should return full content.
  13399. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  13400. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  13401. ASSERT_TRUE(res2);
  13402. // Weak ETag in If-Range -> full content (200), not partial (206)
  13403. EXPECT_EQ(200, res2->status);
  13404. EXPECT_EQ(content, res2->body);
  13405. EXPECT_FALSE(res2->has_header("Content-Range"));
  13406. // Range request with non-matching If-Range (ETag): should get 200 (full
  13407. // content)
  13408. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  13409. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  13410. ASSERT_TRUE(res3);
  13411. EXPECT_EQ(200, res3->status);
  13412. EXPECT_EQ(content, res3->body);
  13413. EXPECT_FALSE(res3->has_header("Content-Range"));
  13414. // Range request with strong ETag (hypothetical - our server doesn't generate
  13415. // strong ETags, but if client sends a strong ETag that doesn't match, it
  13416. // should return full content)
  13417. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  13418. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  13419. ASSERT_TRUE(res4);
  13420. EXPECT_EQ(200, res4->status);
  13421. EXPECT_EQ(content, res4->body);
  13422. EXPECT_FALSE(res4->has_header("Content-Range"));
  13423. svr.stop();
  13424. t.join();
  13425. std::remove(fname);
  13426. }
  13427. TEST(ETagTest, IfRangeWithDate) {
  13428. using namespace httplib;
  13429. // Create a test file
  13430. const char *fname = "if_range_date_testfile.txt";
  13431. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13432. {
  13433. std::ofstream ofs(fname);
  13434. ofs << content;
  13435. ASSERT_TRUE(ofs.good());
  13436. }
  13437. Server svr;
  13438. svr.set_mount_point("/static", ".");
  13439. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13440. svr.wait_until_ready();
  13441. Client cli(HOST, PORT);
  13442. // First request: get Last-Modified
  13443. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13444. ASSERT_TRUE(res1);
  13445. ASSERT_EQ(200, res1->status);
  13446. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13447. std::string last_modified = res1->get_header_value("Last-Modified");
  13448. // Range request with matching If-Range (date): should get 206
  13449. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13450. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13451. ASSERT_TRUE(res2);
  13452. EXPECT_EQ(206, res2->status);
  13453. EXPECT_EQ("FGHIJ", res2->body);
  13454. // Range request with old If-Range date: should get 200 (full content)
  13455. Headers h3 = {{"Range", "bytes=5-9"},
  13456. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13457. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13458. ASSERT_TRUE(res3);
  13459. EXPECT_EQ(200, res3->status);
  13460. EXPECT_EQ(content, res3->body);
  13461. // Range request with future If-Range date: should get 206
  13462. Headers h4 = {{"Range", "bytes=0-4"},
  13463. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13464. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13465. ASSERT_TRUE(res4);
  13466. EXPECT_EQ(206, res4->status);
  13467. EXPECT_EQ("ABCDE", res4->body);
  13468. svr.stop();
  13469. t.join();
  13470. std::remove(fname);
  13471. }
  13472. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13473. using namespace httplib;
  13474. const char *fname = "etag_malformed.txt";
  13475. const char *content = "malformed-etag";
  13476. {
  13477. std::ofstream ofs(fname);
  13478. ofs << content;
  13479. ASSERT_TRUE(ofs.good());
  13480. }
  13481. Server svr;
  13482. svr.set_mount_point("/static", ".");
  13483. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13484. svr.wait_until_ready();
  13485. Client cli(HOST, PORT);
  13486. // baseline: should get 200 and an ETag
  13487. auto res1 = cli.Get("/static/etag_malformed.txt");
  13488. ASSERT_TRUE(res1);
  13489. ASSERT_EQ(200, res1->status);
  13490. ASSERT_TRUE(res1->has_header("ETag"));
  13491. // Malformed ETag value (missing quotes) should be treated as non-matching
  13492. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13493. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13494. ASSERT_TRUE(res_bad);
  13495. EXPECT_EQ(200, res_bad->status);
  13496. // Whitespace-only header value should be considered invalid / non-matching
  13497. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13498. "Host: localhost\r\n"
  13499. "If-None-Match: \r\n"
  13500. "Connection: close\r\n"
  13501. "\r\n";
  13502. std::string out;
  13503. ASSERT_TRUE(send_request(5, raw_req, &out));
  13504. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13505. svr.stop();
  13506. t.join();
  13507. std::remove(fname);
  13508. }
  13509. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13510. using namespace httplib;
  13511. const char *fname = "ims_invalid_format.txt";
  13512. const char *content = "ims-bad-format";
  13513. {
  13514. std::ofstream ofs(fname);
  13515. ofs << content;
  13516. ASSERT_TRUE(ofs.good());
  13517. }
  13518. Server svr;
  13519. svr.set_mount_point("/static", ".");
  13520. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13521. svr.wait_until_ready();
  13522. Client cli(HOST, PORT);
  13523. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13524. ASSERT_TRUE(res1);
  13525. ASSERT_EQ(200, res1->status);
  13526. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13527. // If-Modified-Since with invalid format should not result in 304
  13528. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13529. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13530. ASSERT_TRUE(res_bad);
  13531. EXPECT_EQ(200, res_bad->status);
  13532. // If-Range with invalid date format should be treated as mismatch -> full
  13533. // content (200)
  13534. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13535. {"If-Range", "invalid-date"}};
  13536. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13537. ASSERT_TRUE(res_ifrange);
  13538. EXPECT_EQ(200, res_ifrange->status);
  13539. svr.stop();
  13540. t.join();
  13541. std::remove(fname);
  13542. }
  13543. TEST(ETagTest, IfRangeWithMalformedETag) {
  13544. using namespace httplib;
  13545. const char *fname = "ifrange_malformed.txt";
  13546. const std::string content = "0123456789";
  13547. {
  13548. std::ofstream ofs(fname);
  13549. ofs << content;
  13550. ASSERT_TRUE(ofs.good());
  13551. }
  13552. Server svr;
  13553. svr.set_mount_point("/static", ".");
  13554. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13555. svr.wait_until_ready();
  13556. Client cli(HOST, PORT);
  13557. // First request: get ETag
  13558. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13559. ASSERT_TRUE(res1);
  13560. ASSERT_EQ(200, res1->status);
  13561. ASSERT_TRUE(res1->has_header("ETag"));
  13562. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13563. // full content (200)
  13564. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13565. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13566. ASSERT_TRUE(res2);
  13567. EXPECT_EQ(200, res2->status);
  13568. EXPECT_EQ(content, res2->body);
  13569. svr.stop();
  13570. t.join();
  13571. std::remove(fname);
  13572. }
  13573. TEST(ETagTest, ExtremeLargeDateValues) {
  13574. using namespace httplib;
  13575. const char *fname = "ims_extreme_date.txt";
  13576. const char *content = "ims-extreme-date";
  13577. {
  13578. std::ofstream ofs(fname);
  13579. ofs << content;
  13580. ASSERT_TRUE(ofs.good());
  13581. }
  13582. Server svr;
  13583. svr.set_mount_point("/static", ".");
  13584. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13585. svr.wait_until_ready();
  13586. Client cli(HOST, PORT);
  13587. auto res1 = cli.Get(std::string("/static/") + fname);
  13588. ASSERT_TRUE(res1);
  13589. ASSERT_EQ(200, res1->status);
  13590. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13591. // Extremely large year that may overflow date parsing routines.
  13592. Headers h_large_date = {
  13593. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13594. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13595. ASSERT_TRUE(res_bad);
  13596. // Expect server to treat this as invalid/mismatch and return full content
  13597. EXPECT_EQ(200, res_bad->status);
  13598. // If-Range with extremely large date should be treated as mismatch -> full
  13599. // content (200)
  13600. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13601. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13602. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13603. ASSERT_TRUE(res_ifrange);
  13604. EXPECT_EQ(200, res_ifrange->status);
  13605. svr.stop();
  13606. t.join();
  13607. std::remove(fname);
  13608. }
  13609. TEST(ETagTest, NegativeFileModificationTime) {
  13610. using namespace httplib;
  13611. const char *fname = "ims_negative_mtime.txt";
  13612. const std::string content = "negative-mtime";
  13613. {
  13614. std::ofstream ofs(fname);
  13615. ofs << content;
  13616. ASSERT_TRUE(ofs.good());
  13617. }
  13618. // Try to set file mtime to a negative value. This may fail on some
  13619. // platforms/filesystems; if it fails, the test will still verify server
  13620. // behaves safely by performing a regular conditional request.
  13621. #if defined(__APPLE__) || defined(__linux__)
  13622. bool set_negative = false;
  13623. do {
  13624. struct timeval times[2];
  13625. // access time: now
  13626. times[0].tv_sec = time(nullptr);
  13627. times[0].tv_usec = 0;
  13628. // modification time: negative (e.g., -1)
  13629. times[1].tv_sec = -1;
  13630. times[1].tv_usec = 0;
  13631. if (utimes(fname, times) == 0) { set_negative = true; }
  13632. } while (0);
  13633. #else
  13634. bool set_negative = false;
  13635. #endif
  13636. Server svr;
  13637. svr.set_mount_point("/static", ".");
  13638. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13639. svr.wait_until_ready();
  13640. Client cli(HOST, PORT);
  13641. auto res1 = cli.Get(std::string("/static/") + fname);
  13642. ASSERT_TRUE(res1);
  13643. ASSERT_EQ(200, res1->status);
  13644. bool has_last_modified = res1->has_header("Last-Modified");
  13645. std::string last_modified;
  13646. if (has_last_modified) {
  13647. last_modified = res1->get_header_value("Last-Modified");
  13648. }
  13649. if (set_negative) {
  13650. // If we successfully set a negative mtime, ensure server returns a
  13651. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13652. // with an old date and ensure server handles it without crash.
  13653. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13654. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13655. ASSERT_TRUE(res2);
  13656. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13657. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13658. } else {
  13659. // Could not set negative mtime on this platform; fall back to verifying
  13660. // that normal invalid/malformed dates are treated safely (non-304).
  13661. Headers h_bad_date = {
  13662. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13663. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13664. ASSERT_TRUE(res_bad);
  13665. EXPECT_EQ(200, res_bad->status);
  13666. }
  13667. svr.stop();
  13668. t.join();
  13669. std::remove(fname);
  13670. }
  13671. //==============================================================================
  13672. // SSE Parsing Tests
  13673. //==============================================================================
  13674. class SSEParsingTest : public ::testing::Test {
  13675. protected:
  13676. // Test helper that mimics SSE parsing behavior
  13677. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13678. int &retry_ms) {
  13679. // Blank line signals end of event
  13680. if (line.empty() || line == "\r") { return true; }
  13681. // Lines starting with ':' are comments (ignored)
  13682. if (!line.empty() && line[0] == ':') { return false; }
  13683. // Find the colon separator
  13684. auto colon_pos = line.find(':');
  13685. if (colon_pos == std::string::npos) {
  13686. // Line with no colon is treated as field name with empty value
  13687. return false;
  13688. }
  13689. std::string field = line.substr(0, colon_pos);
  13690. std::string value;
  13691. // Value starts after colon, skip optional single space
  13692. if (colon_pos + 1 < line.size()) {
  13693. size_t value_start = colon_pos + 1;
  13694. if (line[value_start] == ' ') { value_start++; }
  13695. value = line.substr(value_start);
  13696. // Remove trailing \r if present
  13697. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13698. }
  13699. // Handle known fields
  13700. if (field == "event") {
  13701. msg.event = value;
  13702. } else if (field == "data") {
  13703. // Multiple data lines are concatenated with newlines
  13704. if (!msg.data.empty()) { msg.data += "\n"; }
  13705. msg.data += value;
  13706. } else if (field == "id") {
  13707. // Empty id is valid (clears the last event ID)
  13708. msg.id = value;
  13709. } else if (field == "retry") {
  13710. // Parse retry interval in milliseconds
  13711. {
  13712. int v = 0;
  13713. auto res =
  13714. detail::from_chars(value.data(), value.data() + value.size(), v);
  13715. if (res.ec == std::errc{}) { retry_ms = v; }
  13716. }
  13717. }
  13718. // Unknown fields are ignored per SSE spec
  13719. return false;
  13720. }
  13721. };
  13722. // Test: Single-line data
  13723. TEST_F(SSEParsingTest, SingleLineData) {
  13724. sse::SSEMessage msg;
  13725. int retry_ms = 3000;
  13726. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13727. EXPECT_EQ(msg.data, "hello");
  13728. EXPECT_EQ(msg.event, "message");
  13729. // Blank line ends event
  13730. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13731. }
  13732. // Test: Multi-line data
  13733. TEST_F(SSEParsingTest, MultiLineData) {
  13734. sse::SSEMessage msg;
  13735. int retry_ms = 3000;
  13736. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13737. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13738. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13739. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13740. }
  13741. // Test: Custom event types
  13742. TEST_F(SSEParsingTest, CustomEventType) {
  13743. sse::SSEMessage msg;
  13744. int retry_ms = 3000;
  13745. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13746. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13747. EXPECT_EQ(msg.event, "update");
  13748. EXPECT_EQ(msg.data, "payload");
  13749. }
  13750. // Test: Event ID handling
  13751. TEST_F(SSEParsingTest, EventIdHandling) {
  13752. sse::SSEMessage msg;
  13753. int retry_ms = 3000;
  13754. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13755. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13756. EXPECT_EQ(msg.id, "12345");
  13757. }
  13758. // Test: Empty event ID (clears last event ID)
  13759. TEST_F(SSEParsingTest, EmptyEventId) {
  13760. sse::SSEMessage msg;
  13761. msg.id = "previous";
  13762. int retry_ms = 3000;
  13763. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13764. EXPECT_EQ(msg.id, "");
  13765. }
  13766. // Test: Retry field parsing
  13767. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13768. sse::SSEMessage msg;
  13769. int retry_ms = 3000;
  13770. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13771. EXPECT_EQ(retry_ms, 5000);
  13772. }
  13773. // Test: Invalid retry value
  13774. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13775. sse::SSEMessage msg;
  13776. int retry_ms = 3000;
  13777. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13778. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13779. }
  13780. // Test: Comments (lines starting with :)
  13781. TEST_F(SSEParsingTest, CommentsIgnored) {
  13782. sse::SSEMessage msg;
  13783. int retry_ms = 3000;
  13784. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13785. EXPECT_EQ(msg.data, "");
  13786. EXPECT_EQ(msg.event, "message");
  13787. }
  13788. // Test: Colon in value
  13789. TEST_F(SSEParsingTest, ColonInValue) {
  13790. sse::SSEMessage msg;
  13791. int retry_ms = 3000;
  13792. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13793. EXPECT_EQ(msg.data, "hello:world:test");
  13794. }
  13795. // Test: Line with no colon (field name only)
  13796. TEST_F(SSEParsingTest, FieldNameOnly) {
  13797. sse::SSEMessage msg;
  13798. int retry_ms = 3000;
  13799. // According to SSE spec, this is treated as field name with empty value
  13800. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13801. // Since we don't recognize "data" without colon, data should be empty
  13802. EXPECT_EQ(msg.data, "");
  13803. }
  13804. // Test: Trailing \r handling
  13805. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13806. sse::SSEMessage msg;
  13807. int retry_ms = 3000;
  13808. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13809. EXPECT_EQ(msg.data, "hello");
  13810. }
  13811. // Test: Unknown fields ignored
  13812. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13813. sse::SSEMessage msg;
  13814. int retry_ms = 3000;
  13815. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13816. EXPECT_EQ(msg.data, "");
  13817. EXPECT_EQ(msg.event, "message");
  13818. }
  13819. // Test: Space after colon is optional
  13820. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13821. sse::SSEMessage msg1, msg2;
  13822. int retry_ms = 3000;
  13823. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13824. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13825. EXPECT_EQ(msg1.data, "hello");
  13826. EXPECT_EQ(msg2.data, "hello");
  13827. }
  13828. // Test: SSEMessage clear
  13829. TEST_F(SSEParsingTest, MessageClear) {
  13830. sse::SSEMessage msg;
  13831. msg.event = "custom";
  13832. msg.data = "some data";
  13833. msg.id = "123";
  13834. msg.clear();
  13835. EXPECT_EQ(msg.event, "message");
  13836. EXPECT_EQ(msg.data, "");
  13837. EXPECT_EQ(msg.id, "");
  13838. }
  13839. // Test: Complete event parsing
  13840. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13841. sse::SSEMessage msg;
  13842. int retry_ms = 3000;
  13843. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13844. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13845. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13846. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13847. // Blank line ends event
  13848. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13849. EXPECT_EQ(msg.event, "notification");
  13850. EXPECT_EQ(msg.id, "evt-42");
  13851. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13852. EXPECT_EQ(retry_ms, 1000);
  13853. }
  13854. //==============================================================================
  13855. // Integration Tests with Server
  13856. //==============================================================================
  13857. class SSEIntegrationTest : public ::testing::Test {
  13858. protected:
  13859. void SetUp() override {
  13860. stop_server_.store(false);
  13861. events_.clear();
  13862. server_ = httplib::detail::make_unique<Server>();
  13863. setup_server();
  13864. start_server();
  13865. }
  13866. void TearDown() override {
  13867. stop_server_.store(true);
  13868. event_cv_.notify_all();
  13869. server_->stop();
  13870. if (server_thread_.joinable()) { server_thread_.join(); }
  13871. }
  13872. void setup_server() {
  13873. // Simple SSE endpoint
  13874. server_->Get("/events", [this](const Request &req, Response &res) {
  13875. auto last_id = req.get_header_value("Last-Event-ID");
  13876. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13877. res.set_chunked_content_provider(
  13878. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13879. std::unique_lock<std::mutex> lock(event_mutex_);
  13880. if (event_cv_.wait_for(
  13881. lock, std::chrono::milliseconds(200), [this] {
  13882. return !events_.empty() || stop_server_.load();
  13883. })) {
  13884. if (stop_server_.load()) { return false; }
  13885. if (!events_.empty()) {
  13886. std::string event = events_.front();
  13887. events_.erase(events_.begin());
  13888. sink.write(event.data(), event.size());
  13889. return true;
  13890. }
  13891. }
  13892. return !stop_server_.load();
  13893. });
  13894. });
  13895. // Endpoint that returns error
  13896. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13897. res.status = 500;
  13898. res.set_content("Internal Server Error", "text/plain");
  13899. });
  13900. // Endpoint for custom event types
  13901. server_->Get("/custom-events", [](const Request &, Response &res) {
  13902. res.set_chunked_content_provider(
  13903. "text/event-stream", [](size_t offset, DataSink &sink) {
  13904. if (offset == 0) {
  13905. std::string event = "event: update\ndata: updated\n\n"
  13906. "event: delete\ndata: deleted\n\n";
  13907. sink.write(event.data(), event.size());
  13908. }
  13909. return false; // End stream after sending
  13910. });
  13911. });
  13912. }
  13913. void start_server() {
  13914. port_ = server_->bind_to_any_port(HOST);
  13915. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13916. // Wait for server to start
  13917. while (!server_->is_running()) {
  13918. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13919. }
  13920. }
  13921. int get_port() const { return port_; }
  13922. void send_event(const std::string &event) {
  13923. std::lock_guard<std::mutex> lock(event_mutex_);
  13924. events_.push_back(event);
  13925. event_cv_.notify_all();
  13926. }
  13927. std::unique_ptr<Server> server_;
  13928. std::thread server_thread_;
  13929. std::mutex event_mutex_;
  13930. std::condition_variable event_cv_;
  13931. std::vector<std::string> events_;
  13932. std::atomic<bool> stop_server_{false};
  13933. std::string last_received_event_id_;
  13934. int port_ = 0;
  13935. };
  13936. // Test: Successful connection and on_open callback
  13937. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13938. // Add a simple endpoint that sends one event and closes
  13939. server_->Get("/simple-event", [](const Request &, Response &res) {
  13940. res.set_chunked_content_provider(
  13941. "text/event-stream", [](size_t offset, DataSink &sink) {
  13942. if (offset == 0) {
  13943. std::string event = "data: hello\n\n";
  13944. sink.write(event.data(), event.size());
  13945. }
  13946. return false; // Close stream after sending
  13947. });
  13948. });
  13949. Client client("localhost", get_port());
  13950. sse::SSEClient sse(client, "/simple-event");
  13951. std::atomic<bool> open_called{false};
  13952. std::atomic<bool> message_received{false};
  13953. sse.on_open([&open_called]() { open_called.store(true); });
  13954. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13955. if (msg.data == "hello") { message_received.store(true); }
  13956. });
  13957. sse.set_reconnect_interval(100);
  13958. sse.set_max_reconnect_attempts(1);
  13959. // Start async
  13960. sse.start_async();
  13961. // Wait for message to be processed
  13962. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13963. sse.stop();
  13964. EXPECT_TRUE(open_called.load());
  13965. EXPECT_TRUE(message_received.load());
  13966. }
  13967. // Test: on_message callback
  13968. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13969. // Endpoint that sends multiple events then closes
  13970. server_->Get("/multi-event", [](const Request &, Response &res) {
  13971. res.set_chunked_content_provider(
  13972. "text/event-stream", [](size_t offset, DataSink &sink) {
  13973. if (offset == 0) {
  13974. std::string events = "data: message1\n\ndata: message2\n\n";
  13975. sink.write(events.data(), events.size());
  13976. }
  13977. return false;
  13978. });
  13979. });
  13980. Client client("localhost", get_port());
  13981. sse::SSEClient sse(client, "/multi-event");
  13982. std::vector<std::string> received_messages;
  13983. std::mutex messages_mutex;
  13984. sse.on_message([&](const sse::SSEMessage &msg) {
  13985. std::lock_guard<std::mutex> lock(messages_mutex);
  13986. received_messages.push_back(msg.data);
  13987. });
  13988. sse.set_reconnect_interval(100);
  13989. sse.set_max_reconnect_attempts(1);
  13990. sse.start_async();
  13991. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13992. sse.stop();
  13993. std::lock_guard<std::mutex> lock(messages_mutex);
  13994. EXPECT_GE(received_messages.size(), 2u);
  13995. if (received_messages.size() >= 2) {
  13996. EXPECT_EQ(received_messages[0], "message1");
  13997. EXPECT_EQ(received_messages[1], "message2");
  13998. }
  13999. }
  14000. // Test: on_event for specific types
  14001. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  14002. Client client("localhost", get_port());
  14003. sse::SSEClient sse(client, "/custom-events");
  14004. std::atomic<bool> update_received{false};
  14005. std::atomic<bool> delete_received{false};
  14006. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  14007. if (msg.data == "updated") { update_received.store(true); }
  14008. });
  14009. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  14010. if (msg.data == "deleted") { delete_received.store(true); }
  14011. });
  14012. sse.set_max_reconnect_attempts(1);
  14013. sse.start_async();
  14014. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  14015. sse.stop();
  14016. EXPECT_TRUE(update_received.load());
  14017. EXPECT_TRUE(delete_received.load());
  14018. }
  14019. // Test: on_error callback on connection failure
  14020. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  14021. // Connect to a non-existent port
  14022. Client client("localhost", 59999);
  14023. sse::SSEClient sse(client, "/events");
  14024. std::atomic<bool> error_called{false};
  14025. Error received_error = Error::Success;
  14026. sse.on_error([&](Error err) {
  14027. error_called.store(true);
  14028. received_error = err;
  14029. });
  14030. sse.set_reconnect_interval(50);
  14031. sse.set_max_reconnect_attempts(1);
  14032. sse.start_async();
  14033. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14034. sse.stop();
  14035. EXPECT_TRUE(error_called.load());
  14036. EXPECT_NE(received_error, Error::Success);
  14037. }
  14038. // Test: Last-Event-ID header sent on reconnect
  14039. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  14040. // Endpoint that sends event with ID
  14041. server_->Get("/event-with-id", [](const Request &, Response &res) {
  14042. res.set_chunked_content_provider(
  14043. "text/event-stream", [](size_t offset, DataSink &sink) {
  14044. if (offset == 0) {
  14045. std::string event = "id: evt-123\ndata: test\n\n";
  14046. sink.write(event.data(), event.size());
  14047. }
  14048. return false;
  14049. });
  14050. });
  14051. Client client("localhost", get_port());
  14052. sse::SSEClient sse(client, "/event-with-id");
  14053. std::atomic<bool> id_received{false};
  14054. sse.on_message([&](const sse::SSEMessage &msg) {
  14055. if (!msg.id.empty()) { id_received.store(true); }
  14056. });
  14057. sse.set_reconnect_interval(100);
  14058. sse.set_max_reconnect_attempts(1);
  14059. sse.start_async();
  14060. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14061. sse.stop();
  14062. EXPECT_TRUE(id_received.load());
  14063. EXPECT_EQ(sse.last_event_id(), "evt-123");
  14064. }
  14065. // Test: Manual stop
  14066. TEST_F(SSEIntegrationTest, ManualStop) {
  14067. // Endpoint that sends one event and stays open briefly
  14068. std::atomic<bool> handler_running{true};
  14069. server_->Get("/stay-open", [&handler_running](const Request &,
  14070. Response &res) {
  14071. res.set_chunked_content_provider(
  14072. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  14073. if (offset == 0) {
  14074. std::string event = "data: connected\n\n";
  14075. sink.write(event.data(), event.size());
  14076. }
  14077. // Keep connection open while handler_running is true
  14078. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  14079. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14080. }
  14081. return false;
  14082. });
  14083. });
  14084. Client client("localhost", get_port());
  14085. sse::SSEClient sse(client, "/stay-open");
  14086. std::atomic<bool> connected{false};
  14087. sse.on_open([&connected]() { connected.store(true); });
  14088. sse.set_reconnect_interval(100);
  14089. sse.set_max_reconnect_attempts(1);
  14090. sse.start_async();
  14091. // Wait for connection to establish
  14092. for (int i = 0; i < 20 && !connected.load(); ++i) {
  14093. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  14094. }
  14095. EXPECT_TRUE(connected.load());
  14096. EXPECT_TRUE(sse.is_connected());
  14097. // Signal handler to stop
  14098. handler_running.store(false);
  14099. // Stop SSE client
  14100. sse.stop();
  14101. EXPECT_FALSE(sse.is_connected());
  14102. }
  14103. // Test: SSEClient with custom headers
  14104. TEST_F(SSEIntegrationTest, CustomHeaders) {
  14105. // Setup a server endpoint that checks for custom header
  14106. std::atomic<bool> header_received{false};
  14107. server_->Get("/header-check", [&](const Request &req, Response &res) {
  14108. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  14109. header_received.store(true);
  14110. }
  14111. res.set_chunked_content_provider("text/event-stream",
  14112. [](size_t, DataSink &) { return false; });
  14113. });
  14114. Client client("localhost", get_port());
  14115. Headers headers = {{"X-Custom-Header", "custom-value"}};
  14116. sse::SSEClient sse(client, "/header-check", headers);
  14117. sse.set_max_reconnect_attempts(1);
  14118. sse.start_async();
  14119. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14120. sse.stop();
  14121. EXPECT_TRUE(header_received.load());
  14122. }
  14123. // Test: Reconnect interval configuration
  14124. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  14125. Client client("localhost", get_port());
  14126. sse::SSEClient sse(client, "/events");
  14127. auto &result = sse.set_reconnect_interval(500);
  14128. // Builder pattern should return reference to self
  14129. EXPECT_EQ(&result, &sse);
  14130. }
  14131. // Test: Max reconnect attempts
  14132. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  14133. // Connect to non-existent port to force reconnects
  14134. Client client("localhost", 59998);
  14135. sse::SSEClient sse(client, "/events");
  14136. std::atomic<int> error_count{0};
  14137. sse.on_error([&](Error) { error_count.fetch_add(1); });
  14138. sse.set_reconnect_interval(50);
  14139. sse.set_max_reconnect_attempts(2);
  14140. auto start = std::chrono::steady_clock::now();
  14141. sse.start(); // Blocking call
  14142. auto end = std::chrono::steady_clock::now();
  14143. // Should have stopped after 2 failed attempts
  14144. EXPECT_GE(error_count.load(), 2);
  14145. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  14146. auto duration =
  14147. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  14148. #ifdef _WIN32
  14149. // Windows is much slower for socket connection failures
  14150. EXPECT_LT(duration.count(), 7000);
  14151. #else
  14152. EXPECT_LT(duration.count(), 1000);
  14153. #endif
  14154. }
  14155. // Test: Multi-line data in integration
  14156. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  14157. // Endpoint with multi-line data
  14158. server_->Get("/multiline-data", [](const Request &, Response &res) {
  14159. res.set_chunked_content_provider(
  14160. "text/event-stream", [](size_t offset, DataSink &sink) {
  14161. if (offset == 0) {
  14162. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  14163. sink.write(event.data(), event.size());
  14164. }
  14165. return false;
  14166. });
  14167. });
  14168. Client client("localhost", get_port());
  14169. sse::SSEClient sse(client, "/multiline-data");
  14170. std::string received_data;
  14171. std::mutex data_mutex;
  14172. sse.on_message([&](const sse::SSEMessage &msg) {
  14173. std::lock_guard<std::mutex> lock(data_mutex);
  14174. received_data = msg.data;
  14175. });
  14176. sse.set_reconnect_interval(100);
  14177. sse.set_max_reconnect_attempts(1);
  14178. sse.start_async();
  14179. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14180. sse.stop();
  14181. std::lock_guard<std::mutex> lock(data_mutex);
  14182. EXPECT_EQ(received_data, "line1\nline2\nline3");
  14183. }
  14184. // Test: Auto-reconnect after server disconnection
  14185. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  14186. std::atomic<int> connection_count{0};
  14187. std::atomic<int> message_count{0};
  14188. // Endpoint that sends one event and closes, forcing reconnect
  14189. server_->Get("/reconnect-test",
  14190. [&connection_count](const Request &, Response &res) {
  14191. connection_count.fetch_add(1);
  14192. res.set_chunked_content_provider(
  14193. "text/event-stream", [](size_t offset, DataSink &sink) {
  14194. if (offset == 0) {
  14195. std::string event = "data: hello\n\n";
  14196. sink.write(event.data(), event.size());
  14197. }
  14198. return false; // Close connection after sending
  14199. });
  14200. });
  14201. Client client("localhost", get_port());
  14202. sse::SSEClient sse(client, "/reconnect-test");
  14203. sse.on_message([&message_count](const sse::SSEMessage &) {
  14204. message_count.fetch_add(1);
  14205. });
  14206. sse.set_reconnect_interval(100);
  14207. sse.set_max_reconnect_attempts(3);
  14208. sse.start_async();
  14209. // Wait long enough for multiple reconnects
  14210. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14211. sse.stop();
  14212. // Should have connected multiple times (initial + reconnects)
  14213. EXPECT_GE(connection_count.load(), 2);
  14214. // Should have received messages from multiple connections
  14215. EXPECT_GE(message_count.load(), 2);
  14216. }
  14217. // Test: Last-Event-ID sent on reconnect
  14218. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  14219. std::atomic<int> connection_count{0};
  14220. std::vector<std::string> received_last_event_ids;
  14221. std::mutex id_mutex;
  14222. // Endpoint that checks Last-Event-ID header and sends event with ID
  14223. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  14224. int conn = connection_count.fetch_add(1);
  14225. // Capture the Last-Event-ID header from each connection
  14226. {
  14227. std::lock_guard<std::mutex> lock(id_mutex);
  14228. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  14229. }
  14230. res.set_chunked_content_provider(
  14231. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  14232. if (offset == 0) {
  14233. std::string event =
  14234. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  14235. sink.write(event.data(), event.size());
  14236. }
  14237. return false;
  14238. });
  14239. });
  14240. Client client("localhost", get_port());
  14241. sse::SSEClient sse(client, "/reconnect-with-id");
  14242. sse.set_reconnect_interval(100);
  14243. sse.set_max_reconnect_attempts(3);
  14244. sse.start_async();
  14245. // Wait for at least 2 connections
  14246. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  14247. sse.stop();
  14248. // Verify behavior
  14249. std::lock_guard<std::mutex> lock(id_mutex);
  14250. EXPECT_GE(received_last_event_ids.size(), 2u);
  14251. // First connection should have no Last-Event-ID
  14252. if (!received_last_event_ids.empty()) {
  14253. EXPECT_EQ(received_last_event_ids[0], "");
  14254. }
  14255. // Second connection should have Last-Event-ID from first connection
  14256. if (received_last_event_ids.size() >= 2) {
  14257. EXPECT_EQ(received_last_event_ids[1], "event-0");
  14258. }
  14259. }
  14260. // Test: set_headers updates headers used on reconnect
  14261. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  14262. std::vector<std::string> received_tokens;
  14263. std::mutex token_mutex;
  14264. // Endpoint that captures Authorization header
  14265. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  14266. {
  14267. std::lock_guard<std::mutex> lock(token_mutex);
  14268. received_tokens.push_back(req.get_header_value("Authorization"));
  14269. }
  14270. res.set_chunked_content_provider(
  14271. "text/event-stream", [](size_t offset, DataSink &sink) {
  14272. if (offset == 0) {
  14273. std::string event = "data: hello\n\n";
  14274. sink.write(event.data(), event.size());
  14275. }
  14276. return false; // Close connection to trigger reconnect
  14277. });
  14278. });
  14279. Client client("localhost", get_port());
  14280. Headers headers = {{"Authorization", "Bearer old-token"}};
  14281. sse::SSEClient sse(client, "/auth-check", headers);
  14282. // Update headers on each successful connection
  14283. sse.on_open(
  14284. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  14285. sse.set_reconnect_interval(100);
  14286. sse.set_max_reconnect_attempts(3);
  14287. sse.start_async();
  14288. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14289. sse.stop();
  14290. std::lock_guard<std::mutex> lock(token_mutex);
  14291. ASSERT_GE(received_tokens.size(), 2u);
  14292. // First connection uses original header
  14293. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  14294. // Second connection uses updated header from set_headers
  14295. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  14296. }
  14297. // Test: 401 allows reconnection (so on_error can refresh headers)
  14298. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  14299. std::atomic<int> connection_count{0};
  14300. // Endpoint: returns 401 on first attempt, 200 on second
  14301. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  14302. int conn = connection_count.fetch_add(1);
  14303. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  14304. res.status = StatusCode::Unauthorized_401;
  14305. res.set_content("Unauthorized", "text/plain");
  14306. return;
  14307. }
  14308. res.set_chunked_content_provider(
  14309. "text/event-stream", [](size_t offset, DataSink &sink) {
  14310. if (offset == 0) {
  14311. std::string event = "data: authenticated\n\n";
  14312. sink.write(event.data(), event.size());
  14313. }
  14314. return false;
  14315. });
  14316. });
  14317. Client client("localhost", get_port());
  14318. Headers headers = {{"Authorization", "Bearer expired"}};
  14319. sse::SSEClient sse(client, "/auth-retry", headers);
  14320. std::atomic<bool> message_received{false};
  14321. // Refresh token on error
  14322. sse.on_error(
  14323. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  14324. sse.on_message([&](const sse::SSEMessage &msg) {
  14325. if (msg.data == "authenticated") { message_received.store(true); }
  14326. });
  14327. sse.set_reconnect_interval(100);
  14328. sse.set_max_reconnect_attempts(3);
  14329. sse.start_async();
  14330. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  14331. sse.stop();
  14332. // Should have reconnected after 401 and succeeded with new token
  14333. EXPECT_GE(connection_count.load(), 2);
  14334. EXPECT_TRUE(message_received.load());
  14335. }
  14336. TEST(Issue2318Test, EmptyHostString) {
  14337. {
  14338. httplib::Client cli_empty("", PORT);
  14339. auto res = cli_empty.Get("/");
  14340. ASSERT_FALSE(res);
  14341. EXPECT_EQ(httplib::Error::Connection, res.error());
  14342. }
  14343. {
  14344. httplib::Client cli(" ", PORT);
  14345. auto res = cli.Get("/");
  14346. ASSERT_FALSE(res);
  14347. EXPECT_EQ(httplib::Error::Connection, res.error());
  14348. }
  14349. }
  14350. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  14351. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  14352. Server svr;
  14353. // Set a small payload limit (1KB)
  14354. svr.set_payload_max_length(1024);
  14355. svr.Post("/test", [&](const Request &req, Response &res) {
  14356. res.set_content("Body size: " + std::to_string(req.body.size()),
  14357. "text/plain");
  14358. });
  14359. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14360. auto se = detail::scope_exit([&] {
  14361. svr.stop();
  14362. listen_thread.join();
  14363. });
  14364. svr.wait_until_ready();
  14365. // Create data that compresses well but exceeds limit when decompressed
  14366. // 8KB of repeated null bytes compresses to a very small size
  14367. std::string original_data(8 * 1024, '\0');
  14368. // Compress the data using gzip
  14369. std::string compressed_data;
  14370. detail::gzip_compressor compressor;
  14371. compressor.compress(original_data.data(), original_data.size(), true,
  14372. [&](const char *data, size_t size) {
  14373. compressed_data.append(data, size);
  14374. return true;
  14375. });
  14376. // Verify compression worked (compressed should be much smaller)
  14377. ASSERT_LT(compressed_data.size(), original_data.size());
  14378. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  14379. // Send compressed data with Content-Encoding: gzip
  14380. Client cli(HOST, PORT);
  14381. Headers headers = {{"Content-Encoding", "gzip"}};
  14382. auto res =
  14383. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  14384. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  14385. ASSERT_TRUE(res);
  14386. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  14387. }
  14388. #endif
  14389. // ============================================================================
  14390. // OpenSSL-Specific Tests
  14391. // ============================================================================
  14392. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14393. X509 *readCertificate(const std::string &strFileName) {
  14394. std::ifstream inStream(strFileName);
  14395. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  14396. std::istreambuf_iterator<char>());
  14397. if (strCertPEM.empty()) return (nullptr);
  14398. BIO *pbCert = BIO_new(BIO_s_mem());
  14399. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  14400. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  14401. BIO_free(pbCert);
  14402. return (pCert);
  14403. }
  14404. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  14405. std::ifstream inStream(strFileName);
  14406. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  14407. std::istreambuf_iterator<char>());
  14408. if (strPrivateKeyPEM.empty()) return (nullptr);
  14409. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  14410. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  14411. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  14412. BIO_free(pbPrivKey);
  14413. return (pPrivateKey);
  14414. }
  14415. TEST(BindServerTest, UpdateCerts) {
  14416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14417. int port = svr.bind_to_any_port("0.0.0.0");
  14418. ASSERT_TRUE(svr.is_valid());
  14419. ASSERT_TRUE(port > 0);
  14420. X509 *cert = readCertificate(SERVER_CERT_FILE);
  14421. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  14422. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  14423. ASSERT_TRUE(cert != nullptr);
  14424. ASSERT_TRUE(ca_cert != nullptr);
  14425. ASSERT_TRUE(key != nullptr);
  14426. X509_STORE *cert_store = X509_STORE_new();
  14427. X509_STORE_add_cert(cert_store, ca_cert);
  14428. // svr.update_certs(cert, key, cert_store); // deprecated
  14429. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14430. CLIENT_CA_CERT_FILE);
  14431. ASSERT_TRUE(svr.is_valid());
  14432. svr.stop();
  14433. X509_STORE_free(cert_store);
  14434. X509_free(cert);
  14435. X509_free(ca_cert);
  14436. EVP_PKEY_free(key);
  14437. }
  14438. // Test that update_certs() updates client CA list correctly
  14439. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14440. // Start with file-based constructor
  14441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14442. ASSERT_TRUE(svr.is_valid());
  14443. // Initially no client CA list should be set
  14444. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14445. ASSERT_TRUE(ssl_ctx != nullptr);
  14446. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14447. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14448. EXPECT_EQ(0, count_before);
  14449. // Now update with client CA (PEM string)
  14450. std::string cert_pem, key_pem, ca_pem;
  14451. read_file(SERVER_CERT_FILE, cert_pem);
  14452. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14453. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14454. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14455. ASSERT_TRUE(svr.is_valid());
  14456. // Now client CA list should be set
  14457. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14458. ASSERT_TRUE(ca_list_after != nullptr);
  14459. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14460. }
  14461. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14462. // Test that the file-path SSLServer constructor properly sets the client CA
  14463. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14465. ASSERT_TRUE(svr.is_valid());
  14466. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14467. ASSERT_TRUE(ssl_ctx != nullptr);
  14468. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14469. ASSERT_TRUE(ca_list != nullptr);
  14470. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14471. }
  14472. #endif
  14473. // ============================================================================
  14474. // MbedTLS-Specific Tests
  14475. // ============================================================================
  14476. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14477. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14478. using namespace httplib::tls;
  14479. // Track if callback was invoked
  14480. bool callback_invoked = false;
  14481. // The callback receives void* ctx which is actually MbedTlsContext*
  14482. // We can access the mbedtls_ssl_config via the context
  14483. auto setup_callback = [&callback_invoked](void *ctx) {
  14484. callback_invoked = true;
  14485. // Cast to MbedTlsContext* to access the ssl config
  14486. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14487. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14488. // Use static variables to hold certificate data (simplified for test)
  14489. static mbedtls_x509_crt own_cert;
  14490. static mbedtls_pk_context own_key;
  14491. static mbedtls_x509_crt ca_chain;
  14492. static bool initialized = false;
  14493. if (!initialized) {
  14494. mbedtls_x509_crt_init(&own_cert);
  14495. mbedtls_pk_init(&own_key);
  14496. mbedtls_x509_crt_init(&ca_chain);
  14497. // Load server certificate
  14498. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14499. return false;
  14500. }
  14501. // Load server private key
  14502. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14503. #if MBEDTLS_VERSION_MAJOR >= 3
  14504. ,
  14505. mbedtls_ctr_drbg_random, nullptr
  14506. #endif
  14507. ) != 0) {
  14508. return false;
  14509. }
  14510. // Load CA chain for client verification
  14511. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14512. return false;
  14513. }
  14514. initialized = true;
  14515. }
  14516. // Configure the SSL config
  14517. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14518. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14519. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14520. // Set minimum TLS version using mbedTLS native API
  14521. #if MBEDTLS_VERSION_MAJOR >= 3
  14522. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14523. #else
  14524. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14525. MBEDTLS_SSL_MINOR_VERSION_3);
  14526. #endif
  14527. return true;
  14528. };
  14529. SSLServer svr(setup_callback);
  14530. ASSERT_TRUE(svr.is_valid());
  14531. ASSERT_TRUE(callback_invoked);
  14532. svr.Get("/test", [&](const Request &req, Response &res) {
  14533. res.set_content("test", "text/plain");
  14534. auto cert = req.peer_cert();
  14535. ASSERT_TRUE(static_cast<bool>(cert));
  14536. auto common_name = cert.subject_cn();
  14537. EXPECT_EQ("Common Name", common_name);
  14538. });
  14539. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14540. auto se = detail::scope_exit([&] {
  14541. svr.stop();
  14542. t.join();
  14543. ASSERT_FALSE(svr.is_running());
  14544. });
  14545. svr.wait_until_ready();
  14546. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14547. cli.enable_server_certificate_verification(false);
  14548. cli.set_connection_timeout(30);
  14549. auto res = cli.Get("/test");
  14550. ASSERT_TRUE(res);
  14551. ASSERT_EQ(StatusCode::OK_200, res->status);
  14552. }
  14553. #endif
  14554. // WebSocket Tests
  14555. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14556. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14557. // defining the meaning of these bits has been negotiated.
  14558. auto make_frame = [](uint8_t first_byte) {
  14559. std::string frame;
  14560. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14561. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14562. frame += "Hello";
  14563. return frame;
  14564. };
  14565. // RSV1 set (0x40)
  14566. {
  14567. detail::BufferStream strm;
  14568. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14569. ws::Opcode opcode;
  14570. std::string payload;
  14571. bool fin;
  14572. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14573. false, 1024));
  14574. }
  14575. // RSV2 set (0x20)
  14576. {
  14577. detail::BufferStream strm;
  14578. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14579. ws::Opcode opcode;
  14580. std::string payload;
  14581. bool fin;
  14582. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14583. false, 1024));
  14584. }
  14585. // RSV3 set (0x10)
  14586. {
  14587. detail::BufferStream strm;
  14588. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14589. ws::Opcode opcode;
  14590. std::string payload;
  14591. bool fin;
  14592. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14593. false, 1024));
  14594. }
  14595. // No RSV bits set - should succeed
  14596. {
  14597. detail::BufferStream strm;
  14598. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14599. ws::Opcode opcode;
  14600. std::string payload;
  14601. bool fin;
  14602. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14603. false, 1024));
  14604. EXPECT_EQ(ws::Opcode::Text, opcode);
  14605. EXPECT_EQ("Hello", payload);
  14606. EXPECT_TRUE(fin);
  14607. }
  14608. }
  14609. TEST(WebSocketTest, ControlFrameValidation) {
  14610. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14611. // payload length <= 125.
  14612. // Ping with FIN=0 - must be rejected
  14613. {
  14614. detail::BufferStream strm;
  14615. std::string frame;
  14616. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14617. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14618. strm.write(frame.data(), frame.size());
  14619. ws::Opcode opcode;
  14620. std::string payload;
  14621. bool fin;
  14622. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14623. false, 1024));
  14624. }
  14625. // Close with FIN=0 - must be rejected
  14626. {
  14627. detail::BufferStream strm;
  14628. std::string frame;
  14629. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14630. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14631. strm.write(frame.data(), frame.size());
  14632. ws::Opcode opcode;
  14633. std::string payload;
  14634. bool fin;
  14635. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14636. false, 1024));
  14637. }
  14638. // Ping with payload_len=126 (extended length) - must be rejected
  14639. {
  14640. detail::BufferStream strm;
  14641. std::string frame;
  14642. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14643. frame += static_cast<char>(126); // payload_len=126 (>125)
  14644. frame += static_cast<char>(0x00); // extended length high byte
  14645. frame += static_cast<char>(126); // extended length low byte
  14646. frame += std::string(126, 'x');
  14647. strm.write(frame.data(), frame.size());
  14648. ws::Opcode opcode;
  14649. std::string payload;
  14650. bool fin;
  14651. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14652. false, 1024));
  14653. }
  14654. // Ping with FIN=1 and payload_len=125 - should succeed
  14655. {
  14656. detail::BufferStream strm;
  14657. std::string frame;
  14658. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14659. frame += static_cast<char>(125); // payload_len=125
  14660. frame += std::string(125, 'x');
  14661. strm.write(frame.data(), frame.size());
  14662. ws::Opcode opcode;
  14663. std::string payload;
  14664. bool fin;
  14665. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14666. false, 1024));
  14667. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14668. EXPECT_EQ(125u, payload.size());
  14669. EXPECT_TRUE(fin);
  14670. }
  14671. }
  14672. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14673. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14674. // length MUST be 0.
  14675. // MSB set - must be rejected
  14676. {
  14677. detail::BufferStream strm;
  14678. std::string frame;
  14679. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14680. frame += static_cast<char>(127); // 64-bit extended length
  14681. frame += static_cast<char>(0x80); // MSB set (invalid)
  14682. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14683. strm.write(frame.data(), frame.size());
  14684. ws::Opcode opcode;
  14685. std::string payload;
  14686. bool fin;
  14687. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14688. false, 1024));
  14689. }
  14690. // MSB clear - should pass length parsing (will be rejected by max_len,
  14691. // but that's a different check; use a small length to verify)
  14692. {
  14693. detail::BufferStream strm;
  14694. std::string frame;
  14695. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14696. frame += static_cast<char>(127); // 64-bit extended length
  14697. frame += std::string(7, '\0'); // high bytes = 0
  14698. frame += static_cast<char>(0x03); // length = 3
  14699. frame += "abc";
  14700. strm.write(frame.data(), frame.size());
  14701. ws::Opcode opcode;
  14702. std::string payload;
  14703. bool fin;
  14704. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14705. false, 1024));
  14706. EXPECT_EQ(ws::Opcode::Text, opcode);
  14707. EXPECT_EQ("abc", payload);
  14708. }
  14709. }
  14710. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14711. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14712. // Valid UTF-8
  14713. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14714. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14715. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14716. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14717. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14718. // Invalid UTF-8
  14719. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14720. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14721. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14722. EXPECT_FALSE(
  14723. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14724. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14725. }
  14726. TEST(WebSocketTest, ConnectAndDisconnect) {
  14727. Server svr;
  14728. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14729. std::string msg;
  14730. while (ws.read(msg)) {}
  14731. });
  14732. auto port = svr.bind_to_any_port(HOST);
  14733. std::thread t([&]() { svr.listen_after_bind(); });
  14734. svr.wait_until_ready();
  14735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14736. ASSERT_TRUE(client.connect());
  14737. EXPECT_TRUE(client.is_open());
  14738. client.close();
  14739. EXPECT_FALSE(client.is_open());
  14740. svr.stop();
  14741. t.join();
  14742. }
  14743. TEST(WebSocketTest, ValidURL) {
  14744. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14745. EXPECT_TRUE(ws1.is_valid());
  14746. ws::WebSocketClient ws2("ws://example.com/path");
  14747. EXPECT_TRUE(ws2.is_valid());
  14748. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14749. EXPECT_TRUE(ws3.is_valid());
  14750. #ifdef CPPHTTPLIB_SSL_ENABLED
  14751. ws::WebSocketClient wss1("wss://example.com/path");
  14752. EXPECT_TRUE(wss1.is_valid());
  14753. ws::WebSocketClient wss2("wss://example.com:443/path");
  14754. EXPECT_TRUE(wss2.is_valid());
  14755. #endif
  14756. }
  14757. TEST(WebSocketTest, InvalidURL) {
  14758. // No scheme
  14759. ws::WebSocketClient ws1("localhost:8080/path");
  14760. EXPECT_FALSE(ws1.is_valid());
  14761. // No path
  14762. ws::WebSocketClient ws2("ws://localhost:8080");
  14763. EXPECT_FALSE(ws2.is_valid());
  14764. // Empty string
  14765. ws::WebSocketClient ws3("");
  14766. EXPECT_FALSE(ws3.is_valid());
  14767. // Missing host
  14768. ws::WebSocketClient ws4("ws://:8080/path");
  14769. EXPECT_FALSE(ws4.is_valid());
  14770. // Port number overflow — should not crash
  14771. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14772. EXPECT_FALSE(ws5.is_valid());
  14773. // Port out of range
  14774. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14775. EXPECT_FALSE(ws6.is_valid());
  14776. }
  14777. TEST(WebSocketTest, UnsupportedScheme) {
  14778. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14779. ws::WebSocketClient ws1("http://localhost:8080/path");
  14780. EXPECT_FALSE(ws1.is_valid());
  14781. ws::WebSocketClient ws2("https://localhost:8080/path");
  14782. EXPECT_FALSE(ws2.is_valid());
  14783. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14784. EXPECT_FALSE(ws3.is_valid());
  14785. #else
  14786. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14787. std::invalid_argument);
  14788. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14789. std::invalid_argument);
  14790. #endif
  14791. }
  14792. TEST(WebSocketTest, ConnectWhenInvalid) {
  14793. ws::WebSocketClient ws("not a valid url");
  14794. EXPECT_FALSE(ws.is_valid());
  14795. EXPECT_FALSE(ws.connect());
  14796. }
  14797. TEST(WebSocketTest, DefaultPort) {
  14798. ws::WebSocketClient ws1("ws://example.com/path");
  14799. EXPECT_TRUE(ws1.is_valid());
  14800. // ws:// defaults to port 80 (verified by successful parse)
  14801. #ifdef CPPHTTPLIB_SSL_ENABLED
  14802. ws::WebSocketClient ws2("wss://example.com/path");
  14803. EXPECT_TRUE(ws2.is_valid());
  14804. // wss:// defaults to port 443 (verified by successful parse)
  14805. #endif
  14806. }
  14807. TEST(WebSocketTest, IPv6LiteralAddress) {
  14808. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14809. EXPECT_TRUE(ws1.is_valid());
  14810. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14811. EXPECT_TRUE(ws2.is_valid());
  14812. }
  14813. TEST(WebSocketTest, ComplexPath) {
  14814. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14815. EXPECT_TRUE(ws1.is_valid());
  14816. ws::WebSocketClient ws2("ws://localhost:8080/");
  14817. EXPECT_TRUE(ws2.is_valid());
  14818. }
  14819. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  14820. Server svr;
  14821. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14822. std::string msg;
  14823. while (ws.read(msg)) {}
  14824. });
  14825. auto port = svr.bind_to_any_port(HOST);
  14826. std::thread t([&]() { svr.listen_after_bind(); });
  14827. svr.wait_until_ready();
  14828. auto another_host = "example.com";
  14829. auto wrong_ip = "192.0.2.1";
  14830. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14831. client.set_hostname_addr_map({{another_host, wrong_ip}});
  14832. ASSERT_TRUE(client.connect());
  14833. EXPECT_TRUE(client.is_open());
  14834. client.close();
  14835. svr.stop();
  14836. t.join();
  14837. }
  14838. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  14839. Server svr;
  14840. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14841. std::string msg;
  14842. while (ws.read(msg)) {}
  14843. });
  14844. auto port = svr.bind_to_any_port(HOST);
  14845. std::thread t([&]() { svr.listen_after_bind(); });
  14846. svr.wait_until_ready();
  14847. auto wrong_ip = "192.0.2.1";
  14848. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14849. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  14850. client.set_connection_timeout(1);
  14851. client.set_read_timeout(1);
  14852. client.set_write_timeout(1);
  14853. EXPECT_FALSE(client.connect());
  14854. EXPECT_FALSE(client.is_open());
  14855. svr.stop();
  14856. t.join();
  14857. }
  14858. class WebSocketIntegrationTest : public ::testing::Test {
  14859. protected:
  14860. void SetUp() override {
  14861. server_ = httplib::detail::make_unique<Server>();
  14862. setup_server();
  14863. start_server();
  14864. }
  14865. void TearDown() override {
  14866. server_->stop();
  14867. if (server_thread_.joinable()) { server_thread_.join(); }
  14868. }
  14869. void setup_server() {
  14870. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14871. std::string msg;
  14872. ws::ReadResult ret;
  14873. while ((ret = ws.read(msg))) {
  14874. if (ret == ws::Binary) {
  14875. ws.send(msg.data(), msg.size());
  14876. } else {
  14877. ws.send(msg);
  14878. }
  14879. }
  14880. });
  14881. server_->WebSocket("/ws-echo-string",
  14882. [](const Request &, ws::WebSocket &ws) {
  14883. std::string msg;
  14884. while (ws.read(msg)) {
  14885. ws.send("echo: " + msg);
  14886. }
  14887. });
  14888. server_->WebSocket(
  14889. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14890. // Echo back request metadata
  14891. ws.send("path:" + req.path);
  14892. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14893. std::string msg;
  14894. while (ws.read(msg)) {}
  14895. });
  14896. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14897. std::string msg;
  14898. ws.read(msg); // wait for a message
  14899. ws.close();
  14900. });
  14901. server_->WebSocket("/ws-close-status",
  14902. [](const Request &, ws::WebSocket &ws) {
  14903. std::string msg;
  14904. ws.read(msg); // wait for a message
  14905. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14906. });
  14907. server_->WebSocket(
  14908. "/ws-subprotocol",
  14909. [](const Request &, ws::WebSocket &ws) {
  14910. std::string msg;
  14911. while (ws.read(msg)) {
  14912. ws.send(msg);
  14913. }
  14914. },
  14915. [](const std::vector<std::string> &protocols) -> std::string {
  14916. for (const auto &p : protocols) {
  14917. if (p == "graphql-ws") { return p; }
  14918. }
  14919. return "";
  14920. });
  14921. }
  14922. void start_server() {
  14923. port_ = server_->bind_to_any_port(HOST);
  14924. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14925. server_->wait_until_ready();
  14926. }
  14927. std::unique_ptr<Server> server_;
  14928. std::thread server_thread_;
  14929. int port_ = 0;
  14930. };
  14931. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14933. "/ws-echo");
  14934. ASSERT_TRUE(client.connect());
  14935. ASSERT_TRUE(client.is_open());
  14936. ASSERT_TRUE(client.send("Hello WebSocket"));
  14937. std::string msg;
  14938. EXPECT_EQ(ws::Text, client.read(msg));
  14939. EXPECT_EQ("Hello WebSocket", msg);
  14940. client.close();
  14941. }
  14942. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14943. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14944. "/ws-echo");
  14945. ASSERT_TRUE(client.connect());
  14946. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14947. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14948. std::string msg;
  14949. EXPECT_EQ(ws::Binary, client.read(msg));
  14950. EXPECT_EQ(binary_data, msg);
  14951. client.close();
  14952. }
  14953. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14954. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14955. "/ws-echo");
  14956. ASSERT_TRUE(client.connect());
  14957. for (int i = 0; i < 10; i++) {
  14958. auto text = "message " + std::to_string(i);
  14959. ASSERT_TRUE(client.send(text));
  14960. std::string msg;
  14961. ASSERT_TRUE(client.read(msg));
  14962. EXPECT_EQ(text, msg);
  14963. }
  14964. client.close();
  14965. }
  14966. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14968. "/ws-close");
  14969. ASSERT_TRUE(client.connect());
  14970. // Send a message to trigger the server to close
  14971. ASSERT_TRUE(client.send("trigger close"));
  14972. // The server will close, so read should return false
  14973. std::string msg;
  14974. EXPECT_FALSE(client.read(msg));
  14975. EXPECT_FALSE(client.is_open());
  14976. }
  14977. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14978. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14979. "/ws-echo");
  14980. ASSERT_TRUE(client.connect());
  14981. // 128KB message
  14982. std::string large_data(128 * 1024, 'X');
  14983. ASSERT_TRUE(client.send(large_data));
  14984. std::string msg;
  14985. ASSERT_TRUE(client.read(msg));
  14986. EXPECT_EQ(large_data, msg);
  14987. client.close();
  14988. }
  14989. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14990. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14991. "/ws-echo");
  14992. ASSERT_TRUE(client.connect());
  14993. const int num_threads = 4;
  14994. std::vector<std::thread> threads;
  14995. std::atomic<int> send_count{0};
  14996. for (int t = 0; t < num_threads; t++) {
  14997. threads.emplace_back([&client, &send_count, t]() {
  14998. for (int i = 0; i < 5; i++) {
  14999. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  15000. if (client.send(text)) { send_count++; }
  15001. }
  15002. });
  15003. }
  15004. for (auto &th : threads) {
  15005. th.join();
  15006. }
  15007. int received = 0;
  15008. std::string msg;
  15009. while (received < send_count.load()) {
  15010. if (!client.read(msg)) { break; }
  15011. received++;
  15012. }
  15013. EXPECT_EQ(send_count.load(), received);
  15014. client.close();
  15015. }
  15016. TEST_F(WebSocketIntegrationTest, ReadString) {
  15017. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15018. "/ws-echo-string");
  15019. ASSERT_TRUE(client.connect());
  15020. ASSERT_TRUE(client.send("hello"));
  15021. std::string msg;
  15022. ASSERT_TRUE(client.read(msg));
  15023. EXPECT_EQ("echo: hello", msg);
  15024. ASSERT_TRUE(client.send("world"));
  15025. ASSERT_TRUE(client.read(msg));
  15026. EXPECT_EQ("echo: world", msg);
  15027. client.close();
  15028. }
  15029. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  15030. Headers headers = {{"X-Test-Header", "test-value"}};
  15031. ws::WebSocketClient client(
  15032. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  15033. ASSERT_TRUE(client.connect());
  15034. std::string msg;
  15035. ASSERT_TRUE(client.read(msg));
  15036. EXPECT_EQ("path:/ws-request-info", msg);
  15037. ASSERT_TRUE(client.read(msg));
  15038. EXPECT_EQ("header:test-value", msg);
  15039. client.close();
  15040. }
  15041. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  15042. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15043. "/ws-echo");
  15044. client.set_read_timeout(1, 0); // 1 second
  15045. ASSERT_TRUE(client.connect());
  15046. // Don't send anything — server echo handler waits for a message,
  15047. // so read() should time out and return false.
  15048. std::string msg;
  15049. EXPECT_FALSE(client.read(msg));
  15050. }
  15051. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  15052. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15053. "/ws-echo");
  15054. client.set_read_timeout(5, 0);
  15055. ASSERT_TRUE(client.connect());
  15056. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15057. // The server should reject it and close the connection.
  15058. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  15059. client.send(oversized);
  15060. // The server's read() should have failed due to payload limit,
  15061. // so our read() should return false (connection closed).
  15062. std::string msg;
  15063. EXPECT_FALSE(client.read(msg));
  15064. }
  15065. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  15066. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15067. "/ws-echo");
  15068. client.set_read_timeout(10, 0);
  15069. ASSERT_TRUE(client.connect());
  15070. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  15071. // This should succeed.
  15072. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  15073. ASSERT_TRUE(client.send(at_limit));
  15074. std::string msg;
  15075. ASSERT_TRUE(client.read(msg));
  15076. EXPECT_EQ(at_limit.size(), msg.size());
  15077. client.close();
  15078. }
  15079. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  15080. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15081. "/nonexistent");
  15082. EXPECT_FALSE(client.connect());
  15083. EXPECT_FALSE(client.is_open());
  15084. }
  15085. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  15086. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15087. "/ws-echo");
  15088. ASSERT_TRUE(client.connect());
  15089. ASSERT_TRUE(client.send(""));
  15090. std::string msg;
  15091. EXPECT_EQ(ws::Text, client.read(msg));
  15092. EXPECT_EQ("", msg);
  15093. client.close();
  15094. }
  15095. TEST_F(WebSocketIntegrationTest, Reconnect) {
  15096. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15097. "/ws-echo");
  15098. // First connection
  15099. ASSERT_TRUE(client.connect());
  15100. ASSERT_TRUE(client.send("first"));
  15101. std::string msg;
  15102. ASSERT_TRUE(client.read(msg));
  15103. EXPECT_EQ("first", msg);
  15104. client.close();
  15105. EXPECT_FALSE(client.is_open());
  15106. // Reconnect using the same client object
  15107. ASSERT_TRUE(client.connect());
  15108. ASSERT_TRUE(client.is_open());
  15109. ASSERT_TRUE(client.send("second"));
  15110. ASSERT_TRUE(client.read(msg));
  15111. EXPECT_EQ("second", msg);
  15112. client.close();
  15113. }
  15114. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  15115. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15116. "/ws-close-status");
  15117. ASSERT_TRUE(client.connect());
  15118. // Trigger the server to close with GoingAway status
  15119. ASSERT_TRUE(client.send("trigger"));
  15120. // read() should return false after receiving the close frame
  15121. std::string msg;
  15122. EXPECT_FALSE(client.read(msg));
  15123. EXPECT_FALSE(client.is_open());
  15124. }
  15125. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  15126. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15127. "/ws-echo");
  15128. ASSERT_TRUE(client.connect());
  15129. client.close(ws::CloseStatus::GoingAway, "client leaving");
  15130. EXPECT_FALSE(client.is_open());
  15131. }
  15132. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  15133. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  15134. ws::WebSocketClient client(
  15135. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15136. ASSERT_TRUE(client.connect());
  15137. // Server should have selected graphql-ws
  15138. EXPECT_EQ("graphql-ws", client.subprotocol());
  15139. client.close();
  15140. }
  15141. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  15142. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  15143. ws::WebSocketClient client(
  15144. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  15145. ASSERT_TRUE(client.connect());
  15146. // Server should not have selected any subprotocol
  15147. EXPECT_TRUE(client.subprotocol().empty());
  15148. client.close();
  15149. }
  15150. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  15151. // Connect without requesting any subprotocol
  15152. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15153. "/ws-subprotocol");
  15154. ASSERT_TRUE(client.connect());
  15155. EXPECT_TRUE(client.subprotocol().empty());
  15156. client.close();
  15157. }
  15158. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  15159. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  15160. "/ws-echo");
  15161. client.set_tcp_nodelay(true);
  15162. client.set_connection_timeout(3, 0);
  15163. bool socket_options_called = false;
  15164. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  15165. ASSERT_TRUE(client.connect());
  15166. ASSERT_TRUE(client.is_open());
  15167. EXPECT_TRUE(socket_options_called);
  15168. ASSERT_TRUE(client.send("hello"));
  15169. std::string msg;
  15170. auto result = client.read(msg);
  15171. EXPECT_EQ(result, ws::ReadResult::Text);
  15172. EXPECT_EQ(msg, "hello");
  15173. client.close();
  15174. }
  15175. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  15176. Server svr;
  15177. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  15178. if (!req.has_header("Authorization")) {
  15179. res.status = StatusCode::Unauthorized_401;
  15180. res.set_content("Unauthorized", "text/plain");
  15181. return Server::HandlerResponse::Handled;
  15182. }
  15183. return Server::HandlerResponse::Unhandled;
  15184. });
  15185. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  15186. std::string msg;
  15187. while (ws.read(msg)) {
  15188. ws.send(msg);
  15189. }
  15190. });
  15191. auto port = svr.bind_to_any_port("localhost");
  15192. std::thread t([&]() { svr.listen_after_bind(); });
  15193. svr.wait_until_ready();
  15194. // Without Authorization header - should be rejected before upgrade
  15195. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  15196. EXPECT_FALSE(client1.connect());
  15197. // With Authorization header - should succeed
  15198. Headers headers = {{"Authorization", "Bearer token123"}};
  15199. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  15200. headers);
  15201. ASSERT_TRUE(client2.connect());
  15202. ASSERT_TRUE(client2.send("hello"));
  15203. std::string msg;
  15204. ASSERT_TRUE(client2.read(msg));
  15205. EXPECT_EQ("hello", msg);
  15206. client2.close();
  15207. svr.stop();
  15208. t.join();
  15209. }
  15210. TEST(WebSocketTest, QueryStringInHandshake) {
  15211. Server svr;
  15212. std::mutex mtx;
  15213. std::string received_target;
  15214. std::string received_token;
  15215. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  15216. {
  15217. std::lock_guard<std::mutex> lock(mtx);
  15218. received_target = req.target;
  15219. if (req.has_param("token")) {
  15220. received_token = req.get_param_value("token");
  15221. }
  15222. }
  15223. std::string msg;
  15224. while (ws.read(msg)) {
  15225. ws.send(msg);
  15226. }
  15227. });
  15228. auto port = svr.bind_to_any_port("localhost");
  15229. std::thread t([&]() { svr.listen_after_bind(); });
  15230. svr.wait_until_ready();
  15231. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  15232. "/ws?token=ABC&session=123");
  15233. ASSERT_TRUE(client.connect());
  15234. // Round-trip ensures the handler has run and captured the request.
  15235. ASSERT_TRUE(client.send("hello"));
  15236. std::string msg;
  15237. ASSERT_TRUE(client.read(msg));
  15238. EXPECT_EQ("hello", msg);
  15239. client.close();
  15240. {
  15241. std::lock_guard<std::mutex> lock(mtx);
  15242. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  15243. EXPECT_EQ("ABC", received_token);
  15244. }
  15245. svr.stop();
  15246. t.join();
  15247. }
  15248. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  15249. class WebSocketSSLIntegrationTest : public ::testing::Test {
  15250. protected:
  15251. void SetUp() override {
  15252. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  15253. SERVER_PRIVATE_KEY_FILE);
  15254. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  15255. std::string msg;
  15256. ws::ReadResult ret;
  15257. while ((ret = ws.read(msg))) {
  15258. if (ret == ws::Binary) {
  15259. ws.send(msg.data(), msg.size());
  15260. } else {
  15261. ws.send(msg);
  15262. }
  15263. }
  15264. });
  15265. port_ = server_->bind_to_any_port(HOST);
  15266. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  15267. server_->wait_until_ready();
  15268. }
  15269. void TearDown() override {
  15270. server_->stop();
  15271. if (server_thread_.joinable()) { server_thread_.join(); }
  15272. }
  15273. std::unique_ptr<SSLServer> server_;
  15274. std::thread server_thread_;
  15275. int port_ = 0;
  15276. };
  15277. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  15278. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  15279. "/ws-echo");
  15280. client.enable_server_certificate_verification(false);
  15281. ASSERT_TRUE(client.connect());
  15282. ASSERT_TRUE(client.is_open());
  15283. ASSERT_TRUE(client.send("Hello WSS"));
  15284. std::string msg;
  15285. EXPECT_EQ(ws::Text, client.read(msg));
  15286. EXPECT_EQ("Hello WSS", msg);
  15287. client.close();
  15288. }
  15289. #endif
  15290. #if !defined(_WIN32)
  15291. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  15292. auto secret_dir = std::string("./symlink_test_secret");
  15293. auto served_dir = std::string("./symlink_test_served");
  15294. auto secret_file = secret_dir + "/secret.txt";
  15295. auto symlink_path = served_dir + "/escape";
  15296. // Setup: create directories and files
  15297. mkdir(secret_dir.c_str(), 0755);
  15298. mkdir(served_dir.c_str(), 0755);
  15299. {
  15300. std::ofstream ofs(secret_file);
  15301. ofs << "SECRET_DATA";
  15302. }
  15303. // Create symlink using absolute path so it resolves correctly
  15304. #ifdef PATH_MAX
  15305. char abs_secret[PATH_MAX];
  15306. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  15307. #else
  15308. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  15309. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  15310. ASSERT_NE(nullptr, abs_secret);
  15311. #endif
  15312. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  15313. auto se = detail::scope_exit([&] {
  15314. unlink(symlink_path.c_str());
  15315. unlink(secret_file.c_str());
  15316. rmdir(served_dir.c_str());
  15317. rmdir(secret_dir.c_str());
  15318. });
  15319. Server svr;
  15320. svr.set_mount_point("/", served_dir);
  15321. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15322. auto se2 = detail::scope_exit([&] {
  15323. svr.stop();
  15324. listen_thread.join();
  15325. });
  15326. svr.wait_until_ready();
  15327. Client cli("localhost", PORT);
  15328. // Symlink pointing outside base dir should be blocked
  15329. auto res = cli.Get("/escape/secret.txt");
  15330. ASSERT_TRUE(res);
  15331. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15332. }
  15333. #endif
  15334. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  15335. // A GET request with Content-Length to a static file handler must have its
  15336. // body drained before the keep-alive connection is reused. Otherwise the
  15337. // unread body bytes are interpreted as the next HTTP request.
  15338. //
  15339. // The body is sent AFTER receiving the first response (as in the original
  15340. // PoC) so that the stream_line_reader cannot buffer it together with the
  15341. // headers of the first request.
  15342. Server svr;
  15343. svr.set_mount_point("/", "./www");
  15344. std::atomic<int> smuggled_count(0);
  15345. svr.Get("/smuggled", [&](const Request &, Response &res) {
  15346. smuggled_count++;
  15347. res.set_content("oops", "text/plain");
  15348. });
  15349. auto port = svr.bind_to_any_port("localhost");
  15350. thread t = thread([&] { svr.listen_after_bind(); });
  15351. auto se = detail::scope_exit([&] {
  15352. svr.stop();
  15353. t.join();
  15354. });
  15355. svr.wait_until_ready();
  15356. auto error = Error::Success;
  15357. auto sock = detail::create_client_socket(
  15358. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  15359. /*connection_timeout_sec=*/2, 0,
  15360. /*read_timeout_sec=*/2, 0,
  15361. /*write_timeout_sec=*/2, 0, std::string(), error);
  15362. ASSERT_NE(INVALID_SOCKET, sock);
  15363. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15364. // The "smuggled" request will be sent as the body of the outer GET
  15365. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  15366. "Host: localhost\r\n"
  15367. "Connection: close\r\n"
  15368. "\r\n";
  15369. // Step 1: Send only the outer request headers (no body yet)
  15370. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  15371. "Host: localhost\r\n"
  15372. "Content-Length: " +
  15373. std::to_string(smuggled.size()) +
  15374. "\r\n"
  15375. "\r\n";
  15376. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  15377. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  15378. // Step 2: Read the first response (server serves file without reading body)
  15379. std::string first_response;
  15380. char buf[4096];
  15381. for (;;) {
  15382. auto n = recv(sock, buf, sizeof(buf), 0);
  15383. if (n <= 0) break;
  15384. first_response.append(buf, static_cast<size_t>(n));
  15385. // Stop once we have a complete response (headers + body)
  15386. auto hdr_end = first_response.find("\r\n\r\n");
  15387. if (hdr_end != std::string::npos) {
  15388. // Check for Content-Length to know when the body is complete
  15389. auto cl_pos = first_response.find("Content-Length:");
  15390. if (cl_pos != std::string::npos) {
  15391. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  15392. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  15393. auto cl = std::stoul(
  15394. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  15395. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  15396. } else {
  15397. break; // No Content-Length, assume headers-only response
  15398. }
  15399. }
  15400. }
  15401. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  15402. // Step 3: Now send the body, which looks like a new HTTP request.
  15403. // On a vulnerable server the keep-alive loop reads this as a second request.
  15404. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  15405. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  15406. // Step 4: Try to read a second response (should NOT exist after fix)
  15407. std::string second_response;
  15408. for (;;) {
  15409. auto n = recv(sock, buf, sizeof(buf), 0);
  15410. if (n <= 0) break;
  15411. second_response.append(buf, static_cast<size_t>(n));
  15412. }
  15413. // The smuggled request must NOT have been processed
  15414. EXPECT_EQ(0, smuggled_count.load());
  15415. }
  15416. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  15417. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  15418. // must be rejected with 400 Bad Request.
  15419. Server svr;
  15420. svr.Post("/test", [&](const Request &, Response &res) {
  15421. res.set_content("ok", "text/plain");
  15422. });
  15423. thread t = thread([&] { svr.listen(HOST, PORT); });
  15424. auto se = detail::scope_exit([&] {
  15425. svr.stop();
  15426. t.join();
  15427. ASSERT_FALSE(svr.is_running());
  15428. });
  15429. svr.wait_until_ready();
  15430. // Exact "chunked"
  15431. {
  15432. auto req = "POST /test HTTP/1.1\r\n"
  15433. "Host: localhost\r\n"
  15434. "Content-Length: 5\r\n"
  15435. "Transfer-Encoding: chunked\r\n"
  15436. "Connection: close\r\n"
  15437. "\r\n"
  15438. "hello";
  15439. std::string response;
  15440. ASSERT_TRUE(send_request(1, req, &response));
  15441. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15442. response.substr(0, response.find("\r\n")));
  15443. }
  15444. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  15445. {
  15446. auto req = "POST /test HTTP/1.1\r\n"
  15447. "Host: localhost\r\n"
  15448. "Content-Length: 5\r\n"
  15449. "Transfer-Encoding: gzip, chunked\r\n"
  15450. "Connection: close\r\n"
  15451. "\r\n"
  15452. "hello";
  15453. std::string response;
  15454. ASSERT_TRUE(send_request(1, req, &response));
  15455. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  15456. response.substr(0, response.find("\r\n")));
  15457. }
  15458. }
  15459. // Regression for issue #2450: a DELETE without Content-Length on a
  15460. // keep-alive connection must not let the post-response drain consume the
  15461. // next request's bytes.
  15462. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  15463. Server svr;
  15464. std::atomic<int> delete_count(0);
  15465. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  15466. delete_count++;
  15467. res.status = StatusCode::NoContent_204;
  15468. });
  15469. auto port = svr.bind_to_any_port(HOST);
  15470. thread t = thread([&] { svr.listen_after_bind(); });
  15471. auto se = detail::scope_exit([&] {
  15472. svr.stop();
  15473. t.join();
  15474. });
  15475. svr.wait_until_ready();
  15476. auto error = Error::Success;
  15477. auto sock = detail::create_client_socket(
  15478. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  15479. /*connection_timeout_sec=*/2, 0,
  15480. /*read_timeout_sec=*/2, 0,
  15481. /*write_timeout_sec=*/2, 0, std::string(), error);
  15482. ASSERT_NE(INVALID_SOCKET, sock);
  15483. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  15484. auto send_request_and_read_response = [&](const std::string &req,
  15485. std::string &out) -> bool {
  15486. auto sent = send(sock, req.data(), req.size(), 0);
  15487. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  15488. char buf[4096];
  15489. for (;;) {
  15490. auto n = recv(sock, buf, sizeof(buf), 0);
  15491. if (n <= 0) { return !out.empty(); }
  15492. out.append(buf, static_cast<size_t>(n));
  15493. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  15494. }
  15495. };
  15496. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  15497. "Host: localhost\r\n"
  15498. "\r\n";
  15499. std::string resp1;
  15500. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  15501. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  15502. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  15503. "Host: localhost\r\n"
  15504. "Connection: close\r\n"
  15505. "\r\n";
  15506. std::string resp2;
  15507. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  15508. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  15509. EXPECT_EQ(2, delete_count.load());
  15510. }
  15511. namespace no_proxy_test {
  15512. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  15513. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  15514. // calling listen().
  15515. class ScopedServer {
  15516. public:
  15517. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  15518. ~ScopedServer() {
  15519. svr_.stop();
  15520. if (th_.joinable()) { th_.join(); }
  15521. }
  15522. Server &svr() { return svr_; }
  15523. int port() const { return port_; }
  15524. void listen() {
  15525. th_ = std::thread([this] { svr_.listen_after_bind(); });
  15526. svr_.wait_until_ready();
  15527. }
  15528. private:
  15529. Server svr_;
  15530. std::thread th_;
  15531. int port_ = 0;
  15532. };
  15533. class ProxyAndTargetServers {
  15534. public:
  15535. ProxyAndTargetServers() {
  15536. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  15537. proxy_hits_++;
  15538. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15539. res.set_content("via-proxy", "text/plain");
  15540. });
  15541. target_.Get(".*", [this](const Request &req, Response &res) {
  15542. target_hits_++;
  15543. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  15544. res.set_content("direct", "text/plain");
  15545. });
  15546. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  15547. target_port_ = target_.bind_to_any_port("127.0.0.1");
  15548. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  15549. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  15550. proxy_mock_.wait_until_ready();
  15551. target_.wait_until_ready();
  15552. }
  15553. ~ProxyAndTargetServers() {
  15554. proxy_mock_.stop();
  15555. target_.stop();
  15556. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  15557. if (target_thread_.joinable()) { target_thread_.join(); }
  15558. }
  15559. Server &proxy_mock() { return proxy_mock_; }
  15560. Server &target() { return target_; }
  15561. int proxy_port() const { return proxy_port_; }
  15562. int target_port() const { return target_port_; }
  15563. int proxy_hits() const { return proxy_hits_.load(); }
  15564. int target_hits() const { return target_hits_.load(); }
  15565. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  15566. void reset_counters() {
  15567. proxy_hits_ = 0;
  15568. target_hits_ = 0;
  15569. last_had_proxy_authz_ = false;
  15570. }
  15571. private:
  15572. Server proxy_mock_;
  15573. Server target_;
  15574. std::thread proxy_thread_;
  15575. std::thread target_thread_;
  15576. int proxy_port_ = 0;
  15577. int target_port_ = 0;
  15578. std::atomic<int> proxy_hits_{0};
  15579. std::atomic<int> target_hits_{0};
  15580. std::atomic<bool> last_had_proxy_authz_{false};
  15581. };
  15582. inline std::unique_ptr<Client> make_client(const std::string &host,
  15583. ProxyAndTargetServers &s) {
  15584. auto cli = detail::make_unique<Client>(host, s.target_port());
  15585. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  15586. cli->set_proxy("127.0.0.1", s.proxy_port());
  15587. return cli;
  15588. }
  15589. } // namespace no_proxy_test
  15590. using no_proxy_test::make_client;
  15591. using no_proxy_test::ProxyAndTargetServers;
  15592. TEST(NoProxyTest, ExactHostnameBypasses) {
  15593. ProxyAndTargetServers s;
  15594. auto cli = make_client("example.com", s);
  15595. cli->set_no_proxy({"example.com"});
  15596. auto res = cli->Get("/");
  15597. ASSERT_TRUE(res);
  15598. EXPECT_EQ(0, s.proxy_hits());
  15599. EXPECT_EQ(1, s.target_hits());
  15600. }
  15601. TEST(NoProxyTest, SubdomainBypasses) {
  15602. ProxyAndTargetServers s;
  15603. auto cli = make_client("foo.example.com", s);
  15604. cli->set_no_proxy({"example.com"});
  15605. auto res = cli->Get("/");
  15606. ASSERT_TRUE(res);
  15607. EXPECT_EQ(0, s.proxy_hits());
  15608. EXPECT_EQ(1, s.target_hits());
  15609. }
  15610. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  15611. // Regression guard: "evilexample.com" must not be considered a subdomain
  15612. // of "example.com". Without the dot-boundary rule, a naive endsWith
  15613. // check would let traffic bypass the proxy and leak credentials direct
  15614. // to the attacker host.
  15615. ProxyAndTargetServers s;
  15616. auto cli = make_client("evilexample.com", s);
  15617. cli->set_no_proxy({"example.com"});
  15618. auto res = cli->Get("/");
  15619. ASSERT_TRUE(res);
  15620. EXPECT_GE(s.proxy_hits(), 1);
  15621. EXPECT_EQ(0, s.target_hits());
  15622. }
  15623. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  15624. ProxyAndTargetServers s;
  15625. auto cli = make_client("example.com.evil.com", s);
  15626. cli->set_no_proxy({"example.com"});
  15627. auto res = cli->Get("/");
  15628. ASSERT_TRUE(res);
  15629. EXPECT_GE(s.proxy_hits(), 1);
  15630. EXPECT_EQ(0, s.target_hits());
  15631. }
  15632. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  15633. ProxyAndTargetServers s;
  15634. auto cli = make_client("example.com", s);
  15635. cli->set_no_proxy({".example.com"});
  15636. auto res = cli->Get("/");
  15637. ASSERT_TRUE(res);
  15638. EXPECT_EQ(0, s.proxy_hits());
  15639. EXPECT_EQ(1, s.target_hits());
  15640. }
  15641. TEST(NoProxyTest, CaseInsensitiveHostname) {
  15642. ProxyAndTargetServers s;
  15643. auto cli = make_client("Example.COM", s);
  15644. cli->set_no_proxy({"EXAMPLE.com"});
  15645. auto res = cli->Get("/");
  15646. ASSERT_TRUE(res);
  15647. EXPECT_EQ(0, s.proxy_hits());
  15648. EXPECT_EQ(1, s.target_hits());
  15649. }
  15650. TEST(NoProxyTest, TrailingDotIsNormalized) {
  15651. ProxyAndTargetServers s;
  15652. auto cli = make_client("example.com.", s);
  15653. cli->set_no_proxy({"example.com"});
  15654. auto res = cli->Get("/");
  15655. ASSERT_TRUE(res);
  15656. EXPECT_EQ(0, s.proxy_hits());
  15657. EXPECT_EQ(1, s.target_hits());
  15658. }
  15659. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  15660. // Trailing dots must be normalized on BOTH sides — host and entry.
  15661. // An implementation that only strips the host-side trailing dot would
  15662. // fail to match host "example.com" against entry "example.com." because
  15663. // a literal substring search would compare 11 chars against 12.
  15664. ProxyAndTargetServers s;
  15665. auto cli = make_client("example.com", s);
  15666. cli->set_no_proxy({"example.com."});
  15667. auto res = cli->Get("/");
  15668. ASSERT_TRUE(res);
  15669. EXPECT_EQ(0, s.proxy_hits());
  15670. EXPECT_EQ(1, s.target_hits());
  15671. }
  15672. TEST(NoProxyTest, WildcardBypassesEverything) {
  15673. ProxyAndTargetServers s;
  15674. auto cli = make_client("anything.invalid.test", s);
  15675. cli->set_no_proxy({"*"});
  15676. auto res = cli->Get("/");
  15677. ASSERT_TRUE(res);
  15678. EXPECT_EQ(0, s.proxy_hits());
  15679. EXPECT_EQ(1, s.target_hits());
  15680. }
  15681. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  15682. ProxyAndTargetServers s;
  15683. Client cli("127.0.0.1", s.target_port());
  15684. cli.set_proxy("127.0.0.1", s.proxy_port());
  15685. cli.set_no_proxy({"127.0.0.1"});
  15686. auto res = cli.Get("/");
  15687. ASSERT_TRUE(res);
  15688. EXPECT_EQ(0, s.proxy_hits());
  15689. EXPECT_EQ(1, s.target_hits());
  15690. }
  15691. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  15692. ProxyAndTargetServers s;
  15693. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  15694. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  15695. cli.set_proxy("127.0.0.1", s.proxy_port());
  15696. cli.set_no_proxy({"::1"});
  15697. auto res = cli.Get("/");
  15698. ASSERT_TRUE(res);
  15699. EXPECT_EQ(0, s.proxy_hits());
  15700. EXPECT_EQ(1, s.target_hits());
  15701. }
  15702. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  15703. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  15704. // must still be recognized as IPv6 for CIDR matching. Implementations
  15705. // that detect IPv6 only when the host begins with '[' would parse the
  15706. // host as a hostname and miss the match.
  15707. ProxyAndTargetServers s;
  15708. Client cli("fe80::1", s.target_port());
  15709. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  15710. cli.set_proxy("127.0.0.1", s.proxy_port());
  15711. cli.set_no_proxy({"fe80::/10"});
  15712. auto res = cli.Get("/");
  15713. ASSERT_TRUE(res);
  15714. EXPECT_EQ(0, s.proxy_hits());
  15715. EXPECT_EQ(1, s.target_hits());
  15716. }
  15717. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  15718. ProxyAndTargetServers s;
  15719. Client cli("::1", s.target_port());
  15720. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  15721. cli.set_proxy("127.0.0.1", s.proxy_port());
  15722. cli.set_no_proxy({"[::1]"});
  15723. auto res = cli.Get("/");
  15724. ASSERT_TRUE(res);
  15725. EXPECT_EQ(0, s.proxy_hits());
  15726. EXPECT_EQ(1, s.target_hits());
  15727. }
  15728. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  15729. ProxyAndTargetServers s;
  15730. Client cli("fe80::1", s.target_port());
  15731. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  15732. cli.set_proxy("127.0.0.1", s.proxy_port());
  15733. cli.set_no_proxy({"[fe80::]/10"});
  15734. auto res = cli.Get("/");
  15735. ASSERT_TRUE(res);
  15736. EXPECT_EQ(0, s.proxy_hits());
  15737. EXPECT_EQ(1, s.target_hits());
  15738. }
  15739. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  15740. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  15741. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  15742. // tricks via address-family conversion.
  15743. ProxyAndTargetServers s;
  15744. Client cli("::ffff:127.0.0.1", s.target_port());
  15745. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  15746. cli.set_proxy("127.0.0.1", s.proxy_port());
  15747. cli.set_no_proxy({"127.0.0.1"});
  15748. auto res = cli.Get("/");
  15749. ASSERT_TRUE(res);
  15750. EXPECT_GE(s.proxy_hits(), 1);
  15751. EXPECT_EQ(0, s.target_hits());
  15752. }
  15753. TEST(NoProxyTest, IPv4CidrMatch) {
  15754. ProxyAndTargetServers s;
  15755. Client cli("127.0.0.1", s.target_port());
  15756. cli.set_proxy("127.0.0.1", s.proxy_port());
  15757. cli.set_no_proxy({"127.0.0.0/8"});
  15758. auto res = cli.Get("/");
  15759. ASSERT_TRUE(res);
  15760. EXPECT_EQ(0, s.proxy_hits());
  15761. EXPECT_EQ(1, s.target_hits());
  15762. }
  15763. TEST(NoProxyTest, IPv4CidrNonMatch) {
  15764. ProxyAndTargetServers s;
  15765. Client cli("127.0.0.1", s.target_port());
  15766. cli.set_proxy("127.0.0.1", s.proxy_port());
  15767. cli.set_no_proxy({"10.0.0.0/8"});
  15768. auto res = cli.Get("/");
  15769. ASSERT_TRUE(res);
  15770. EXPECT_GE(s.proxy_hits(), 1);
  15771. EXPECT_EQ(0, s.target_hits());
  15772. }
  15773. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  15774. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  15775. // IPv4 target matches.
  15776. ProxyAndTargetServers s;
  15777. Client cli("127.0.0.1", s.target_port());
  15778. cli.set_proxy("127.0.0.1", s.proxy_port());
  15779. cli.set_no_proxy({"0.0.0.0/0"});
  15780. auto res = cli.Get("/");
  15781. ASSERT_TRUE(res);
  15782. EXPECT_EQ(0, s.proxy_hits());
  15783. EXPECT_EQ(1, s.target_hits());
  15784. }
  15785. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  15786. ProxyAndTargetServers s;
  15787. Client cli("127.0.0.1", s.target_port());
  15788. cli.set_proxy("127.0.0.1", s.proxy_port());
  15789. cli.set_no_proxy({"127.0.0.1"});
  15790. auto res = cli.Get("/");
  15791. ASSERT_TRUE(res);
  15792. EXPECT_EQ(0, s.proxy_hits());
  15793. EXPECT_EQ(1, s.target_hits());
  15794. }
  15795. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  15796. ProxyAndTargetServers s;
  15797. Client cli("127.0.0.1", s.target_port());
  15798. cli.set_proxy("127.0.0.1", s.proxy_port());
  15799. cli.set_no_proxy({"127.0.0.0/33"});
  15800. auto res = cli.Get("/");
  15801. ASSERT_TRUE(res);
  15802. EXPECT_GE(s.proxy_hits(), 1);
  15803. EXPECT_EQ(0, s.target_hits());
  15804. }
  15805. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  15806. // Empty prefix after the slash must be rejected, not silently treated as /32.
  15807. ProxyAndTargetServers s;
  15808. Client cli("127.0.0.1", s.target_port());
  15809. cli.set_proxy("127.0.0.1", s.proxy_port());
  15810. cli.set_no_proxy({"127.0.0.1/"});
  15811. auto res = cli.Get("/");
  15812. ASSERT_TRUE(res);
  15813. EXPECT_GE(s.proxy_hits(), 1);
  15814. EXPECT_EQ(0, s.target_hits());
  15815. }
  15816. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  15817. ProxyAndTargetServers s;
  15818. auto cli = make_client("internal.corp", s);
  15819. cli->set_proxy_basic_auth("u", "p");
  15820. cli->set_no_proxy({"internal.corp"});
  15821. auto res = cli->Get("/");
  15822. ASSERT_TRUE(res);
  15823. EXPECT_EQ(1, s.target_hits());
  15824. EXPECT_EQ(0, s.proxy_hits());
  15825. EXPECT_FALSE(s.last_had_proxy_authz())
  15826. << "Proxy-Authorization must not be sent direct to the target";
  15827. }
  15828. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  15829. ProxyAndTargetServers s;
  15830. auto cli = make_client("public.example", s);
  15831. cli->set_proxy_basic_auth("u", "p");
  15832. cli->set_no_proxy({"internal.corp"}); // does not match
  15833. auto res = cli->Get("/");
  15834. ASSERT_TRUE(res);
  15835. EXPECT_GE(s.proxy_hits(), 1);
  15836. EXPECT_TRUE(s.last_had_proxy_authz());
  15837. }
  15838. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  15839. ProxyAndTargetServers s;
  15840. auto cli = make_client("anything.test", s);
  15841. auto res = cli->Get("/");
  15842. ASSERT_TRUE(res);
  15843. EXPECT_GE(s.proxy_hits(), 1);
  15844. EXPECT_EQ(0, s.target_hits());
  15845. }
  15846. TEST(NoProxyTest, PortSpecificEntryRejected) {
  15847. ProxyAndTargetServers s;
  15848. auto cli = make_client("example.com", s);
  15849. cli->set_no_proxy({"example.com:8080"});
  15850. auto res = cli->Get("/");
  15851. ASSERT_TRUE(res);
  15852. EXPECT_GE(s.proxy_hits(), 1);
  15853. EXPECT_EQ(0, s.target_hits());
  15854. }
  15855. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  15856. ProxyAndTargetServers s;
  15857. auto cli = make_client("anything.test", s);
  15858. cli->set_no_proxy({"", " ", "\t"});
  15859. auto res = cli->Get("/");
  15860. ASSERT_TRUE(res);
  15861. EXPECT_GE(s.proxy_hits(), 1);
  15862. EXPECT_EQ(0, s.target_hits());
  15863. }
  15864. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  15865. // An entry with leading/trailing whitespace must still match — env-style
  15866. // values are commonly pasted with stray spaces and an implementation
  15867. // that feeds the raw token directly to inet_pton would fail to match
  15868. // valid CIDRs because of the spaces.
  15869. ProxyAndTargetServers s;
  15870. Client cli("127.0.0.1", s.target_port());
  15871. cli.set_proxy("127.0.0.1", s.proxy_port());
  15872. cli.set_no_proxy({" 127.0.0.0/8 "});
  15873. auto res = cli.Get("/");
  15874. ASSERT_TRUE(res);
  15875. EXPECT_EQ(0, s.proxy_hits());
  15876. EXPECT_EQ(1, s.target_hits());
  15877. }
  15878. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  15879. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  15880. // go direct and must NOT carry Proxy-Authorization.
  15881. std::atomic<int> proxy_hits{0};
  15882. std::atomic<int> target_hits{0};
  15883. std::atomic<bool> target_saw_authz{false};
  15884. no_proxy_test::ScopedServer proxy_mock, target;
  15885. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  15886. proxy_hits++;
  15887. res.status = 302;
  15888. res.set_header("Location", "http://127.0.0.1:" +
  15889. std::to_string(target.port()) + "/landed");
  15890. });
  15891. target.svr().Get(".*", [&](const Request &req, Response &res) {
  15892. target_hits++;
  15893. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  15894. res.set_content("direct", "text/plain");
  15895. });
  15896. proxy_mock.listen();
  15897. target.listen();
  15898. Client cli("public.example", target.port());
  15899. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15900. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15901. cli.set_proxy_basic_auth("u", "p");
  15902. cli.set_no_proxy({"127.0.0.1"});
  15903. cli.set_follow_location(true);
  15904. auto res = cli.Get("/redir");
  15905. ASSERT_TRUE(res);
  15906. EXPECT_GE(proxy_hits.load(), 1);
  15907. EXPECT_GE(target_hits.load(), 1);
  15908. EXPECT_FALSE(target_saw_authz.load());
  15909. }
  15910. #ifdef CPPHTTPLIB_SSL_ENABLED
  15911. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  15912. // Direct origin replying 407 must not trigger the digest retry; otherwise
  15913. // proxy creds would be sent to the (possibly hostile) origin.
  15914. std::atomic<int> target_hits{0};
  15915. std::atomic<bool> target_saw_proxy_authz{false};
  15916. no_proxy_test::ScopedServer target;
  15917. target.svr().Get(".*", [&](const Request &req, Response &res) {
  15918. target_hits++;
  15919. if (req.has_header("Proxy-Authorization")) {
  15920. target_saw_proxy_authz = true;
  15921. }
  15922. res.status = StatusCode::ProxyAuthenticationRequired_407;
  15923. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  15924. "nonce=\"abc\", algorithm=MD5");
  15925. });
  15926. target.listen();
  15927. // The proxy address is set to the target's port: the bypass MUST kick in;
  15928. // if it doesn't, the test still routes "via proxy" to the same server and
  15929. // the Proxy-Authorization assertion below catches the leak.
  15930. Client cli("evil.example", target.port());
  15931. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  15932. cli.set_proxy("127.0.0.1", target.port());
  15933. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  15934. cli.set_no_proxy({"evil.example"});
  15935. auto res = cli.Get("/x");
  15936. ASSERT_TRUE(res);
  15937. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  15938. EXPECT_EQ(1, target_hits.load());
  15939. EXPECT_FALSE(target_saw_proxy_authz.load());
  15940. }
  15941. #endif
  15942. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  15943. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  15944. std::atomic<int> proxy_hits{0};
  15945. std::atomic<int> bypass_hits{0};
  15946. std::atomic<bool> proxy_saw_c_url{false};
  15947. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  15948. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  15949. proxy_hits++;
  15950. if (req.path.find("/start") != std::string::npos) {
  15951. res.status = 302;
  15952. res.set_header("Location", "http://127.0.0.1:" +
  15953. std::to_string(bypass_server.port()) +
  15954. "/middle");
  15955. return;
  15956. }
  15957. if (req.path.find("/end") != std::string::npos) {
  15958. proxy_saw_c_url = true;
  15959. res.set_content("c-via-proxy", "text/plain");
  15960. return;
  15961. }
  15962. res.set_content("unexpected", "text/plain");
  15963. });
  15964. // public.example's "advertised" port is arbitrary (the request never lands
  15965. // there — it goes through the proxy), but use a dynamic value to stay
  15966. // friendly with sharded parallel runs.
  15967. int public_port = bypass_server.port();
  15968. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  15969. bypass_hits++;
  15970. res.status = 302;
  15971. res.set_header("Location", "http://public.example:" +
  15972. std::to_string(public_port) + "/end");
  15973. });
  15974. proxy_mock.listen();
  15975. bypass_server.listen();
  15976. Client cli("public.example", public_port);
  15977. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  15978. cli.set_proxy("127.0.0.1", proxy_mock.port());
  15979. cli.set_no_proxy({"127.0.0.1"});
  15980. cli.set_follow_location(true);
  15981. auto res = cli.Get("/start");
  15982. ASSERT_TRUE(res);
  15983. EXPECT_EQ(StatusCode::OK_200, res->status);
  15984. EXPECT_EQ("c-via-proxy", res->body);
  15985. EXPECT_GE(proxy_hits.load(), 2);
  15986. EXPECT_GE(bypass_hits.load(), 1);
  15987. EXPECT_TRUE(proxy_saw_c_url.load());
  15988. }
  15989. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  15990. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  15991. // request reconnects to the correct endpoint.
  15992. std::atomic<int> proxy_hits{0};
  15993. std::atomic<int> target_hits{0};
  15994. no_proxy_test::ScopedServer proxy_mock, target;
  15995. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  15996. proxy_hits++;
  15997. res.set_content("via-proxy", "text/plain");
  15998. });
  15999. target.svr().Get(".*", [&](const Request &, Response &res) {
  16000. target_hits++;
  16001. res.set_content("direct", "text/plain");
  16002. });
  16003. proxy_mock.listen();
  16004. target.listen();
  16005. Client cli("public.example", target.port());
  16006. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  16007. cli.set_proxy("127.0.0.1", proxy_mock.port());
  16008. cli.set_keep_alive(true);
  16009. auto res1 = cli.Get("/a");
  16010. ASSERT_TRUE(res1);
  16011. EXPECT_EQ("via-proxy", res1->body);
  16012. EXPECT_EQ(1, proxy_hits.load());
  16013. EXPECT_EQ(0, target_hits.load());
  16014. cli.set_no_proxy({"public.example"});
  16015. auto res2 = cli.Get("/b");
  16016. ASSERT_TRUE(res2);
  16017. EXPECT_EQ("direct", res2->body);
  16018. EXPECT_EQ(1, proxy_hits.load());
  16019. EXPECT_EQ(1, target_hits.load());
  16020. }
  16021. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  16022. namespace proxy_tunnel_test {
  16023. // SSLServer counterpart to no_proxy_test::ScopedServer.
  16024. class ScopedSSLServer {
  16025. public:
  16026. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  16027. port_ = svr_.bind_to_any_port("127.0.0.1");
  16028. }
  16029. ~ScopedSSLServer() {
  16030. svr_.stop();
  16031. if (th_.joinable()) { th_.join(); }
  16032. }
  16033. SSLServer &svr() { return svr_; }
  16034. int port() const { return port_; }
  16035. void listen() {
  16036. th_ = std::thread([this] { svr_.listen_after_bind(); });
  16037. svr_.wait_until_ready();
  16038. }
  16039. private:
  16040. SSLServer svr_;
  16041. std::thread th_;
  16042. int port_ = 0;
  16043. };
  16044. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  16045. class ScopedConnectProxy {
  16046. public:
  16047. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  16048. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  16049. if (listen_fd_ < 0) { return; }
  16050. int yes = 1;
  16051. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  16052. sockaddr_in a{};
  16053. a.sin_family = AF_INET;
  16054. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16055. a.sin_port = 0;
  16056. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  16057. return;
  16058. }
  16059. socklen_t alen = sizeof(a);
  16060. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  16061. 0) {
  16062. return;
  16063. }
  16064. port_ = ntohs(a.sin_port);
  16065. if (::listen(listen_fd_, 1) != 0) { return; }
  16066. th_ = std::thread([this] { run(); });
  16067. }
  16068. ~ScopedConnectProxy() {
  16069. stop_ = true;
  16070. if (listen_fd_ >= 0) {
  16071. ::shutdown(listen_fd_, SHUT_RDWR);
  16072. ::close(listen_fd_);
  16073. }
  16074. if (th_.joinable()) { th_.join(); }
  16075. }
  16076. int port() const { return port_; }
  16077. int connect_hits() const { return connect_hits_.load(); }
  16078. private:
  16079. void run() {
  16080. while (!stop_.load()) {
  16081. fd_set rfds;
  16082. FD_ZERO(&rfds);
  16083. FD_SET(listen_fd_, &rfds);
  16084. timeval tv{0, 100 * 1000};
  16085. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  16086. if (sel <= 0) { continue; }
  16087. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  16088. if (client_fd < 0) { continue; }
  16089. std::string req;
  16090. char buf[2048];
  16091. while (req.find("\r\n\r\n") == std::string::npos) {
  16092. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  16093. if (n <= 0) { break; }
  16094. req.append(buf, static_cast<size_t>(n));
  16095. }
  16096. if (req.compare(0, 7, "CONNECT") != 0) {
  16097. ::close(client_fd);
  16098. continue;
  16099. }
  16100. connect_hits_++;
  16101. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  16102. ::send(client_fd, ok, std::strlen(ok), 0);
  16103. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  16104. sockaddr_in o{};
  16105. o.sin_family = AF_INET;
  16106. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  16107. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  16108. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  16109. 0) {
  16110. ::close(client_fd);
  16111. ::close(origin_fd);
  16112. continue;
  16113. }
  16114. auto forward = [](int from, int to) {
  16115. char b[8192];
  16116. for (;;) {
  16117. ssize_t n = ::recv(from, b, sizeof(b), 0);
  16118. if (n <= 0) { break; }
  16119. ssize_t off = 0;
  16120. while (off < n) {
  16121. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  16122. if (s <= 0) {
  16123. off = n;
  16124. break;
  16125. }
  16126. off += s;
  16127. }
  16128. }
  16129. ::shutdown(to, SHUT_WR);
  16130. };
  16131. std::thread t1([&] { forward(client_fd, origin_fd); });
  16132. std::thread t2([&] { forward(origin_fd, client_fd); });
  16133. t1.join();
  16134. t2.join();
  16135. ::close(client_fd);
  16136. ::close(origin_fd);
  16137. }
  16138. }
  16139. int forward_port_ = -1;
  16140. int listen_fd_ = -1;
  16141. int port_ = 0;
  16142. std::thread th_;
  16143. std::atomic<bool> stop_{false};
  16144. std::atomic<int> connect_hits_{0};
  16145. };
  16146. } // namespace proxy_tunnel_test
  16147. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  16148. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  16149. // retry; otherwise proxy creds would be sent to the origin.
  16150. std::atomic<int> origin_hits{0};
  16151. std::atomic<bool> origin_saw_proxy_authz{false};
  16152. proxy_tunnel_test::ScopedSSLServer origin;
  16153. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  16154. origin_hits++;
  16155. if (req.has_header("Proxy-Authorization")) {
  16156. origin_saw_proxy_authz = true;
  16157. }
  16158. res.status = StatusCode::ProxyAuthenticationRequired_407;
  16159. res.set_header("Proxy-Authenticate",
  16160. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  16161. "algorithm=MD5");
  16162. });
  16163. origin.listen();
  16164. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  16165. ASSERT_NE(0, proxy.port());
  16166. SSLClient cli(HOST, origin.port());
  16167. cli.enable_server_certificate_verification(false);
  16168. cli.set_proxy(HOST, proxy.port());
  16169. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  16170. auto res = cli.Get("/x");
  16171. ASSERT_TRUE(res);
  16172. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  16173. EXPECT_EQ(1, origin_hits.load());
  16174. EXPECT_FALSE(origin_saw_proxy_authz.load());
  16175. EXPECT_EQ(1, proxy.connect_hits());
  16176. }
  16177. #endif