test.cc 551 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(DivideTest, DivideStringTests) {
  666. auto divide = [](const std::string &str, char d) {
  667. std::string lhs;
  668. std::string rhs;
  669. detail::divide(str, d,
  670. [&](const char *lhs_data, std::size_t lhs_size,
  671. const char *rhs_data, std::size_t rhs_size) {
  672. lhs.assign(lhs_data, lhs_size);
  673. rhs.assign(rhs_data, rhs_size);
  674. });
  675. return std::make_pair(std::move(lhs), std::move(rhs));
  676. };
  677. {
  678. const auto res = divide("", '=');
  679. EXPECT_EQ(res.first, "");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "");
  686. }
  687. {
  688. const auto res = divide(" ", '=');
  689. EXPECT_EQ(res.first, " ");
  690. EXPECT_EQ(res.second, "");
  691. }
  692. {
  693. const auto res = divide("a", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "");
  696. }
  697. {
  698. const auto res = divide("a=", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "");
  701. }
  702. {
  703. const auto res = divide("=b", '=');
  704. EXPECT_EQ(res.first, "");
  705. EXPECT_EQ(res.second, "b");
  706. }
  707. {
  708. const auto res = divide("a=b", '=');
  709. EXPECT_EQ(res.first, "a");
  710. EXPECT_EQ(res.second, "b");
  711. }
  712. {
  713. const auto res = divide("a=b=", '=');
  714. EXPECT_EQ(res.first, "a");
  715. EXPECT_EQ(res.second, "b=");
  716. }
  717. {
  718. const auto res = divide("a=b=c", '=');
  719. EXPECT_EQ(res.first, "a");
  720. EXPECT_EQ(res.second, "b=c");
  721. }
  722. }
  723. TEST(SplitTest, ParseQueryString) {
  724. string s = "key1=val1&key2=val2&key3=val3";
  725. Params dic;
  726. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  727. [&](const char *b, const char *e) {
  728. string key, val;
  729. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  730. if (key.empty()) {
  731. key.assign(b2, e2);
  732. } else {
  733. val.assign(b2, e2);
  734. }
  735. });
  736. dic.emplace(key, val);
  737. });
  738. EXPECT_EQ("val1", dic.find("key1")->second);
  739. EXPECT_EQ("val2", dic.find("key2")->second);
  740. EXPECT_EQ("val3", dic.find("key3")->second);
  741. }
  742. TEST(SplitTest, ParseInvalidQueryTests) {
  743. {
  744. string s = " ";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. {
  750. string s = " = =";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. }
  756. TEST(ParseQueryTest, ParseQueryString) {
  757. {
  758. std::string s = "key1=val1&key2=val2&key3=val3";
  759. Params dic;
  760. detail::parse_query_text(s, dic);
  761. EXPECT_EQ("val1", dic.find("key1")->second);
  762. EXPECT_EQ("val2", dic.find("key2")->second);
  763. EXPECT_EQ("val3", dic.find("key3")->second);
  764. }
  765. {
  766. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  767. Params dic;
  768. detail::parse_query_text(s, dic);
  769. EXPECT_EQ("", dic.find("key1")->second);
  770. EXPECT_EQ("val1", dic.find("key2")->second);
  771. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  772. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  773. }
  774. }
  775. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  776. Params dic;
  777. EXPECT_EQ(detail::params_to_query_str(dic), "");
  778. dic.emplace("key1", "val1");
  779. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  780. dic.emplace("key2", "val2");
  781. dic.emplace("key3", "val3");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  783. }
  784. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  785. string content_type = "multipart/form-data; boundary=something";
  786. string boundary;
  787. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(boundary, "something");
  790. }
  791. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  792. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  793. string boundary;
  794. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  795. EXPECT_TRUE(ret);
  796. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  797. }
  798. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  799. string content_type =
  800. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  801. string boundary;
  802. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  803. EXPECT_TRUE(ret);
  804. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  805. }
  806. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  807. string content_type =
  808. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  809. string boundary;
  810. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  811. EXPECT_TRUE(ret);
  812. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  813. }
  814. TEST(GetHeaderValueTest, DefaultValue) {
  815. Headers headers = {{"Dummy", "Dummy"}};
  816. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  817. EXPECT_STREQ("text/plain", val);
  818. }
  819. TEST(GetHeaderValueTest, DefaultValueInt) {
  820. Headers headers = {{"Dummy", "Dummy"}};
  821. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  822. EXPECT_EQ(100ull, val);
  823. }
  824. TEST(GetHeaderValueTest, RegularValue) {
  825. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  826. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  827. EXPECT_STREQ("text/html", val);
  828. }
  829. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  830. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  832. EXPECT_STREQ("text/html", val);
  833. }
  834. TEST(GetHeaderValueTest, SetContent) {
  835. Response res;
  836. res.set_content("html", "text/html");
  837. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  838. res.set_content("text", "text/plain");
  839. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  840. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  841. }
  842. TEST(GetHeaderValueTest, RegularValueInt) {
  843. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  845. EXPECT_EQ(100ull, val);
  846. }
  847. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  848. Headers headers = {{"Content-Length", "x"}};
  849. auto is_invalid_value = false;
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  851. is_invalid_value);
  852. EXPECT_EQ(0ull, val);
  853. EXPECT_TRUE(is_invalid_value);
  854. }
  855. TEST(GetHeaderValueTest, Range) {
  856. {
  857. Headers headers = {make_range_header({{1, -1}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=-1", val);
  865. }
  866. {
  867. Headers headers = {make_range_header({{1, 10}})};
  868. auto val = detail::get_header_value(headers, "Range", 0, 0);
  869. EXPECT_STREQ("bytes=1-10", val);
  870. }
  871. {
  872. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  873. auto val = detail::get_header_value(headers, "Range", 0, 0);
  874. EXPECT_STREQ("bytes=1-10, 100-", val);
  875. }
  876. {
  877. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  878. auto val = detail::get_header_value(headers, "Range", 0, 0);
  879. EXPECT_STREQ("bytes=1-10, 100-200", val);
  880. }
  881. {
  882. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  883. auto val = detail::get_header_value(headers, "Range", 0, 0);
  884. EXPECT_STREQ("bytes=0-0, -1", val);
  885. }
  886. }
  887. TEST(ParseHeaderValueTest, Range) {
  888. {
  889. Ranges ranges;
  890. auto ret = detail::parse_range_header("bytes=1-", ranges);
  891. EXPECT_TRUE(ret);
  892. EXPECT_EQ(1u, ranges.size());
  893. EXPECT_EQ(1u, ranges[0].first);
  894. EXPECT_EQ(-1, ranges[0].second);
  895. }
  896. {
  897. Ranges ranges;
  898. auto ret = detail::parse_range_header("bytes=-1", ranges);
  899. EXPECT_TRUE(ret);
  900. EXPECT_EQ(1u, ranges.size());
  901. EXPECT_EQ(-1, ranges[0].first);
  902. EXPECT_EQ(1u, ranges[0].second);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(1u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. }
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  915. EXPECT_FALSE(ret);
  916. }
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(2u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(-1, ranges[1].second);
  926. }
  927. {
  928. Ranges ranges;
  929. auto ret =
  930. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(3u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. EXPECT_EQ(100u, ranges[1].first);
  936. EXPECT_EQ(200u, ranges[1].second);
  937. EXPECT_EQ(300u, ranges[2].first);
  938. EXPECT_EQ(400u, ranges[2].second);
  939. }
  940. {
  941. Ranges ranges;
  942. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  955. EXPECT_TRUE(ranges.empty());
  956. }
  957. }
  958. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  966. #else
  967. EXPECT_TRUE(ret == detail::EncodingType::None);
  968. #endif
  969. }
  970. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  971. Request req;
  972. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  973. Response res;
  974. res.set_header("Content-Type", "text/plain");
  975. auto ret = detail::encoding_type(req, res);
  976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  978. #elif CPPHTTPLIB_ZLIB_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  980. #elif CPPHTTPLIB_ZSTD_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  982. #else
  983. EXPECT_TRUE(ret == detail::EncodingType::None);
  984. #endif
  985. }
  986. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  987. Request req;
  988. req.set_header("Accept-Encoding",
  989. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  995. #elif CPPHTTPLIB_ZLIB_SUPPORT
  996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  997. #elif CPPHTTPLIB_ZSTD_SUPPORT
  998. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  999. #else
  1000. EXPECT_TRUE(ret == detail::EncodingType::None);
  1001. #endif
  1002. }
  1003. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1004. // All supported encodings rejected with q=0 should return None
  1005. Request req;
  1006. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1007. Response res;
  1008. res.set_header("Content-Type", "text/plain");
  1009. auto ret = detail::encoding_type(req, res);
  1010. EXPECT_TRUE(ret == detail::EncodingType::None);
  1011. }
  1012. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1013. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1014. Request req;
  1015. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1016. Response res;
  1017. res.set_header("Content-Type", "text/plain");
  1018. auto ret = detail::encoding_type(req, res);
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. }
  1021. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1022. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1023. Request req;
  1024. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1025. Response res;
  1026. res.set_header("Content-Type", "text/plain");
  1027. auto ret = detail::encoding_type(req, res);
  1028. EXPECT_TRUE(ret == detail::EncodingType::None);
  1029. }
  1030. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1031. // RFC 7231: Accept-Encoding values are case-insensitive
  1032. Request req;
  1033. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1034. Response res;
  1035. res.set_header("Content-Type", "text/plain");
  1036. auto ret = detail::encoding_type(req, res);
  1037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1043. #else
  1044. EXPECT_TRUE(ret == detail::EncodingType::None);
  1045. #endif
  1046. }
  1047. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1048. // q value should determine priority, not hardcoded order
  1049. Request req;
  1050. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1051. Response res;
  1052. res.set_header("Content-Type", "text/plain");
  1053. auto ret = detail::encoding_type(req, res);
  1054. // gzip has highest q=1.0, so it should be selected even though
  1055. // br and zstd are also supported
  1056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1060. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1062. #else
  1063. EXPECT_TRUE(ret == detail::EncodingType::None);
  1064. #endif
  1065. }
  1066. TEST(BufferStreamTest, read) {
  1067. detail::BufferStream strm1;
  1068. Stream &strm = strm1;
  1069. EXPECT_EQ(5, strm.write("hello"));
  1070. char buf[512];
  1071. EXPECT_EQ(2, strm.read(buf, 2));
  1072. EXPECT_EQ('h', buf[0]);
  1073. EXPECT_EQ('e', buf[1]);
  1074. EXPECT_EQ(2, strm.read(buf, 2));
  1075. EXPECT_EQ('l', buf[0]);
  1076. EXPECT_EQ('l', buf[1]);
  1077. EXPECT_EQ(1, strm.read(buf, 1));
  1078. EXPECT_EQ('o', buf[0]);
  1079. EXPECT_EQ(0, strm.read(buf, 1));
  1080. }
  1081. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1082. auto host = "www.httpwatch.com";
  1083. auto ip = hosted_at(host);
  1084. EXPECT_EQ("23.96.13.243", ip);
  1085. std::vector<std::string> addrs;
  1086. hosted_at(host, addrs);
  1087. EXPECT_EQ(1u, addrs.size());
  1088. }
  1089. #if 0 // It depends on each test environment...
  1090. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1091. auto host = "www.youtube.com";
  1092. std::vector<std::string> addrs;
  1093. hosted_at(host, addrs);
  1094. EXPECT_EQ(20u, addrs.size());
  1095. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1096. EXPECT_TRUE(it != addrs.end());
  1097. }
  1098. #endif
  1099. class ChunkedEncodingTest : public ::testing::Test {
  1100. protected:
  1101. ChunkedEncodingTest()
  1102. : cli_(HOST, PORT)
  1103. #ifdef CPPHTTPLIB_SSL_ENABLED
  1104. ,
  1105. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1106. #endif
  1107. {
  1108. cli_.set_connection_timeout(2);
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. cli_.enable_server_certificate_verification(false);
  1111. #endif
  1112. }
  1113. virtual void SetUp() {
  1114. read_file("./image.jpg", image_data_);
  1115. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. svr_.Get(
  1119. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1120. res.set_chunked_content_provider(
  1121. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1122. size_t remaining = image_data_.size() - offset;
  1123. if (remaining == 0) {
  1124. sink.done();
  1125. } else {
  1126. constexpr size_t CHUNK_SIZE = 1024;
  1127. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1128. sink.write(&image_data_[offset], send_size);
  1129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1130. }
  1131. return true;
  1132. });
  1133. });
  1134. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1135. svr_.wait_until_ready();
  1136. }
  1137. virtual void TearDown() {
  1138. svr_.stop();
  1139. if (!request_threads_.empty()) {
  1140. std::this_thread::sleep_for(std::chrono::seconds(1));
  1141. for (auto &t : request_threads_) {
  1142. t.join();
  1143. }
  1144. }
  1145. t_.join();
  1146. }
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. SSLClient cli_;
  1149. SSLServer svr_;
  1150. #else
  1151. Client cli_;
  1152. Server svr_;
  1153. #endif
  1154. thread t_;
  1155. std::vector<thread> request_threads_;
  1156. std::string image_data_;
  1157. };
  1158. TEST_F(ChunkedEncodingTest, NormalGet) {
  1159. auto res = cli_.Get("/chunked");
  1160. ASSERT_TRUE(res);
  1161. std::string out;
  1162. read_file("./image.jpg", out);
  1163. EXPECT_EQ(StatusCode::OK_200, res->status);
  1164. EXPECT_EQ(out, res->body);
  1165. }
  1166. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1167. std::string body;
  1168. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1169. body.append(data, data_length);
  1170. return true;
  1171. });
  1172. ASSERT_TRUE(res);
  1173. std::string out;
  1174. read_file("./image.jpg", out);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. EXPECT_EQ(out, body);
  1177. }
  1178. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1179. std::string body;
  1180. auto res = cli_.Get(
  1181. "/chunked",
  1182. [&](const Response &response) {
  1183. EXPECT_EQ(StatusCode::OK_200, response.status);
  1184. return true;
  1185. },
  1186. [&](const char *data, size_t data_length) {
  1187. body.append(data, data_length);
  1188. return true;
  1189. });
  1190. ASSERT_TRUE(res);
  1191. std::string out;
  1192. read_file("./image.jpg", out);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. EXPECT_EQ(out, body);
  1195. }
  1196. TEST(RangeTest, FromHTTPBin_Online) {
  1197. auto host = "httpbingo.org";
  1198. auto path = std::string{"/range/32"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(5);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_TRUE(res);
  1210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. }
  1213. {
  1214. Headers headers = {make_range_header({{1, -1}})};
  1215. auto res = cli.Get(path, headers);
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1219. }
  1220. {
  1221. Headers headers = {make_range_header({{1, 10}})};
  1222. auto res = cli.Get(path, headers);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("bcdefghijk", res->body);
  1225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1226. }
  1227. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1228. // entire resource, while the original httpbin returned 200. Both are
  1229. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1230. {
  1231. Headers headers = {make_range_header({{0, 31}})};
  1232. auto res = cli.Get(path, headers);
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1235. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1236. res->status == StatusCode::PartialContent_206);
  1237. }
  1238. {
  1239. Headers headers = {make_range_header({{0, -1}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1243. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1244. res->status == StatusCode::PartialContent_206);
  1245. }
  1246. // go-httpbin returns 206 with clamped range for over-range requests,
  1247. // while the original httpbin returned 416. Both behaviors are observed
  1248. // in real servers, so we only verify the request succeeds.
  1249. {
  1250. Headers headers = {make_range_header({{0, 32}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. }
  1254. }
  1255. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1256. auto host = "unresolvableaddress.local";
  1257. auto path = std::string{"/"};
  1258. #ifdef CPPHTTPLIB_SSL_ENABLED
  1259. auto port = 443;
  1260. SSLClient cli(host, port);
  1261. #else
  1262. auto port = 80;
  1263. Client cli(host, port);
  1264. #endif
  1265. cli.set_connection_timeout(1);
  1266. {
  1267. auto res = cli.Get(path);
  1268. ASSERT_FALSE(res);
  1269. }
  1270. std::this_thread::sleep_for(std::chrono::seconds(8));
  1271. }
  1272. #if defined(__linux__) && defined(__GLIBC__) && \
  1273. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  1274. // Forward declaration: in split builds split.py strips `inline` and moves the
  1275. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  1276. // visible from the public httplib.h. Re-declaring it here lets the tests link
  1277. // against the symbol in both header-only and split builds.
  1278. namespace httplib {
  1279. namespace detail {
  1280. int getaddrinfo_with_timeout(const char *node, const char *service,
  1281. const struct addrinfo *hints,
  1282. struct addrinfo **res, time_t timeout_sec);
  1283. } // namespace detail
  1284. } // namespace httplib
  1285. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  1286. //
  1287. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  1288. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  1289. // gai_suspend() call hits the connection timeout the function calls
  1290. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  1291. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  1292. // still alive and still references the now-destroyed stack frame.
  1293. //
  1294. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  1295. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  1296. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  1297. // and runs them in a container.
  1298. namespace {
  1299. bool should_run_issue_2431_tests() {
  1300. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  1301. return v && *v && std::string(v) != "0";
  1302. }
  1303. std::string unique_unresolvable_host(int n) {
  1304. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  1305. // glibc still asks the configured nameserver — which is exactly the path
  1306. // we want to exercise. A unique label per call avoids the resolver cache.
  1307. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  1308. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  1309. std::to_string(n) + ".invalid";
  1310. }
  1311. } // namespace
  1312. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  1313. if (!should_run_issue_2431_tests()) {
  1314. GTEST_SKIP()
  1315. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1316. }
  1317. for (int i = 0; i < 8; ++i) {
  1318. struct addrinfo hints;
  1319. memset(&hints, 0, sizeof(hints));
  1320. hints.ai_family = AF_UNSPEC;
  1321. hints.ai_socktype = SOCK_STREAM;
  1322. auto host = unique_unresolvable_host(i);
  1323. struct addrinfo *result = nullptr;
  1324. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1325. &result, /*timeout_sec=*/1);
  1326. if (rc == 0 && result) { freeaddrinfo(result); }
  1327. }
  1328. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  1329. // stack region they still believe holds their gaicb.
  1330. std::this_thread::sleep_for(std::chrono::seconds(3));
  1331. }
  1332. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  1333. if (!should_run_issue_2431_tests()) {
  1334. GTEST_SKIP()
  1335. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1336. }
  1337. std::atomic<bool> stop{false};
  1338. std::vector<std::thread> threads;
  1339. for (int t = 0; t < 8; ++t) {
  1340. threads.emplace_back([t, &stop] {
  1341. int i = 0;
  1342. while (!stop.load(std::memory_order_relaxed)) {
  1343. struct addrinfo hints;
  1344. memset(&hints, 0, sizeof(hints));
  1345. hints.ai_family = AF_UNSPEC;
  1346. hints.ai_socktype = SOCK_STREAM;
  1347. auto host = unique_unresolvable_host(t * 100000 + i++);
  1348. struct addrinfo *result = nullptr;
  1349. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  1350. &result, /*timeout_sec=*/1);
  1351. if (rc == 0 && result) { freeaddrinfo(result); }
  1352. }
  1353. });
  1354. }
  1355. std::this_thread::sleep_for(std::chrono::seconds(8));
  1356. stop.store(true, std::memory_order_relaxed);
  1357. for (auto &th : threads) {
  1358. th.join();
  1359. }
  1360. std::this_thread::sleep_for(std::chrono::seconds(3));
  1361. }
  1362. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  1363. if (!should_run_issue_2431_tests()) {
  1364. GTEST_SKIP()
  1365. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  1366. }
  1367. std::atomic<bool> stop{false};
  1368. std::vector<std::thread> threads;
  1369. for (int t = 0; t < 8; ++t) {
  1370. threads.emplace_back([t, &stop] {
  1371. int i = 0;
  1372. while (!stop.load(std::memory_order_relaxed)) {
  1373. auto host = unique_unresolvable_host(t * 100000 + i++);
  1374. Client cli(host, 80);
  1375. cli.set_connection_timeout(1, 0);
  1376. cli.set_read_timeout(1, 0);
  1377. cli.set_write_timeout(1, 0);
  1378. (void)cli.Get("/");
  1379. }
  1380. });
  1381. }
  1382. std::this_thread::sleep_for(std::chrono::seconds(8));
  1383. stop.store(true, std::memory_order_relaxed);
  1384. for (auto &th : threads) {
  1385. th.join();
  1386. }
  1387. std::this_thread::sleep_for(std::chrono::seconds(3));
  1388. }
  1389. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  1390. TEST(ConnectionErrorTest, InvalidHost) {
  1391. auto host = "-abcde.com";
  1392. #ifdef CPPHTTPLIB_SSL_ENABLED
  1393. auto port = 443;
  1394. SSLClient cli(host, port);
  1395. #else
  1396. auto port = 80;
  1397. Client cli(host, port);
  1398. #endif
  1399. cli.set_connection_timeout(std::chrono::seconds(2));
  1400. auto res = cli.Get("/");
  1401. ASSERT_TRUE(!res);
  1402. EXPECT_EQ(Error::Connection, res.error());
  1403. }
  1404. TEST(ConnectionErrorTest, InvalidHost2) {
  1405. auto host = "httpcan.org/";
  1406. #ifdef CPPHTTPLIB_SSL_ENABLED
  1407. SSLClient cli(host);
  1408. #else
  1409. Client cli(host);
  1410. #endif
  1411. cli.set_connection_timeout(std::chrono::seconds(2));
  1412. auto res = cli.Get("/");
  1413. ASSERT_TRUE(!res);
  1414. EXPECT_EQ(Error::Connection, res.error());
  1415. }
  1416. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1417. auto host = "httpcan.org/";
  1418. #ifdef CPPHTTPLIB_SSL_ENABLED
  1419. SSLClient cli(host);
  1420. #else
  1421. Client cli(host);
  1422. #endif
  1423. cli.set_connection_timeout(std::chrono::seconds(2));
  1424. auto res = cli.Get("/");
  1425. ASSERT_TRUE(!res);
  1426. stringstream s;
  1427. s << "error code: " << res.error();
  1428. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1429. }
  1430. TEST(ConnectionErrorTest, InvalidPort) {
  1431. auto host = "localhost";
  1432. auto port = 44380;
  1433. #ifdef CPPHTTPLIB_SSL_ENABLED
  1434. SSLClient cli(host, port);
  1435. #else
  1436. Client cli(host, port);
  1437. #endif
  1438. cli.set_connection_timeout(std::chrono::seconds(2));
  1439. auto res = cli.Get("/");
  1440. ASSERT_TRUE(!res);
  1441. EXPECT_TRUE(Error::Connection == res.error() ||
  1442. Error::ConnectionTimeout == res.error());
  1443. }
  1444. TEST(ConnectionErrorTest, Timeout_Online) {
  1445. auto host = "google.com";
  1446. #ifdef CPPHTTPLIB_SSL_ENABLED
  1447. auto port = 44380;
  1448. SSLClient cli(host, port);
  1449. #else
  1450. auto port = 8080;
  1451. Client cli(host, port);
  1452. #endif
  1453. cli.set_connection_timeout(std::chrono::seconds(2));
  1454. // only probe one address type so that the error reason
  1455. // correlates to the timed-out IPv4, not the unsupported
  1456. // IPv6 connection attempt
  1457. cli.set_address_family(AF_INET);
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1461. }
  1462. TEST(CancelTest, NoCancel_Online) {
  1463. auto host = "httpbingo.org";
  1464. auto path = std::string{"/range/32"};
  1465. #ifdef CPPHTTPLIB_SSL_ENABLED
  1466. auto port = 443;
  1467. SSLClient cli(host, port);
  1468. #else
  1469. auto port = 80;
  1470. Client cli(host, port);
  1471. #endif
  1472. cli.set_connection_timeout(std::chrono::seconds(5));
  1473. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1474. ASSERT_TRUE(res);
  1475. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1476. EXPECT_EQ(StatusCode::OK_200, res->status);
  1477. }
  1478. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1479. // Use /bytes with a large payload so that the DownloadProgress callback
  1480. // (which only fires for Content-Length responses) is invoked before the
  1481. // entire body is received, giving cancellation a chance to fire.
  1482. auto host = "httpbingo.org";
  1483. auto path = std::string{"/bytes/524288"};
  1484. #ifdef CPPHTTPLIB_SSL_ENABLED
  1485. auto port = 443;
  1486. SSLClient cli(host, port);
  1487. #else
  1488. auto port = 80;
  1489. Client cli(host, port);
  1490. #endif
  1491. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. ASSERT_TRUE(!res);
  1494. EXPECT_EQ(Error::Canceled, res.error());
  1495. }
  1496. TEST(CancelTest, WithCancelLargePayload_Online) {
  1497. auto host = "httpbingo.org";
  1498. auto path = std::string{"/bytes/524288"};
  1499. #ifdef CPPHTTPLIB_SSL_ENABLED
  1500. auto port = 443;
  1501. SSLClient cli(host, port);
  1502. #else
  1503. auto port = 80;
  1504. Client cli(host, port);
  1505. #endif
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. uint32_t count = 0;
  1508. auto res =
  1509. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelPost) {
  1514. Server svr;
  1515. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1535. Server svr;
  1536. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadPost) {
  1555. Server svr;
  1556. svr.set_payload_max_length(200 * 1024 * 1024);
  1557. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1558. res.set_content(LARGE_DATA, "text/plain");
  1559. });
  1560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1561. auto se = detail::scope_exit([&] {
  1562. svr.stop();
  1563. thread.join();
  1564. ASSERT_FALSE(svr.is_running());
  1565. });
  1566. svr.wait_until_ready();
  1567. Client cli(HOST, PORT);
  1568. cli.set_payload_max_length(200 * 1024 * 1024);
  1569. cli.set_connection_timeout(std::chrono::seconds(5));
  1570. auto res =
  1571. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1572. "application/json", [](uint64_t, uint64_t) { return false; });
  1573. ASSERT_TRUE(!res);
  1574. EXPECT_EQ(Error::Canceled, res.error());
  1575. }
  1576. TEST(CancelTest, NoCancelPut) {
  1577. Server svr;
  1578. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1579. res.set_content("Hello World!", "text/plain");
  1580. });
  1581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. Client cli(HOST, PORT);
  1589. cli.set_connection_timeout(std::chrono::seconds(5));
  1590. auto res =
  1591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1592. "application/json", [](uint64_t, uint64_t) { return true; });
  1593. ASSERT_TRUE(res);
  1594. EXPECT_EQ("Hello World!", res->body);
  1595. EXPECT_EQ(StatusCode::OK_200, res->status);
  1596. }
  1597. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1598. Server svr;
  1599. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1600. res.set_content("Hello World!", "text/plain");
  1601. });
  1602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1603. auto se = detail::scope_exit([&] {
  1604. svr.stop();
  1605. thread.join();
  1606. ASSERT_FALSE(svr.is_running());
  1607. });
  1608. svr.wait_until_ready();
  1609. Client cli(HOST, PORT);
  1610. cli.set_connection_timeout(std::chrono::seconds(5));
  1611. auto res =
  1612. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1613. "application/json", [](uint64_t, uint64_t) { return false; });
  1614. ASSERT_TRUE(!res);
  1615. EXPECT_EQ(Error::Canceled, res.error());
  1616. }
  1617. TEST(CancelTest, WithCancelLargePayloadPut) {
  1618. Server svr;
  1619. svr.set_payload_max_length(200 * 1024 * 1024);
  1620. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1621. res.set_content(LARGE_DATA, "text/plain");
  1622. });
  1623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1624. auto se = detail::scope_exit([&] {
  1625. svr.stop();
  1626. thread.join();
  1627. ASSERT_FALSE(svr.is_running());
  1628. });
  1629. svr.wait_until_ready();
  1630. Client cli(HOST, PORT);
  1631. cli.set_payload_max_length(200 * 1024 * 1024);
  1632. cli.set_connection_timeout(std::chrono::seconds(5));
  1633. auto res =
  1634. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1635. "application/json", [](uint64_t, uint64_t) { return false; });
  1636. ASSERT_TRUE(!res);
  1637. EXPECT_EQ(Error::Canceled, res.error());
  1638. }
  1639. TEST(CancelTest, NoCancelPatch) {
  1640. Server svr;
  1641. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1642. res.set_content("Hello World!", "text/plain");
  1643. });
  1644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1645. auto se = detail::scope_exit([&] {
  1646. svr.stop();
  1647. thread.join();
  1648. ASSERT_FALSE(svr.is_running());
  1649. });
  1650. svr.wait_until_ready();
  1651. Client cli(HOST, PORT);
  1652. cli.set_connection_timeout(std::chrono::seconds(5));
  1653. auto res =
  1654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1655. "application/json", [](uint64_t, uint64_t) { return true; });
  1656. ASSERT_TRUE(res);
  1657. EXPECT_EQ("Hello World!", res->body);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1661. Server svr;
  1662. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1663. res.set_content("Hello World!", "text/plain");
  1664. });
  1665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1666. auto se = detail::scope_exit([&] {
  1667. svr.stop();
  1668. thread.join();
  1669. ASSERT_FALSE(svr.is_running());
  1670. });
  1671. svr.wait_until_ready();
  1672. Client cli(HOST, PORT);
  1673. cli.set_connection_timeout(std::chrono::seconds(5));
  1674. auto res =
  1675. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1676. "application/json", [](uint64_t, uint64_t) { return false; });
  1677. ASSERT_TRUE(!res);
  1678. EXPECT_EQ(Error::Canceled, res.error());
  1679. }
  1680. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1681. Server svr;
  1682. svr.set_payload_max_length(200 * 1024 * 1024);
  1683. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1684. res.set_content(LARGE_DATA, "text/plain");
  1685. });
  1686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. thread.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. Client cli(HOST, PORT);
  1694. cli.set_payload_max_length(200 * 1024 * 1024);
  1695. cli.set_connection_timeout(std::chrono::seconds(5));
  1696. auto res =
  1697. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1698. "application/json", [](uint64_t, uint64_t) { return false; });
  1699. ASSERT_TRUE(!res);
  1700. EXPECT_EQ(Error::Canceled, res.error());
  1701. }
  1702. TEST(CancelTest, NoCancelDelete) {
  1703. Server svr;
  1704. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1705. res.set_content("Hello World!", "text/plain");
  1706. });
  1707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1708. auto se = detail::scope_exit([&] {
  1709. svr.stop();
  1710. thread.join();
  1711. ASSERT_FALSE(svr.is_running());
  1712. });
  1713. svr.wait_until_ready();
  1714. Client cli(HOST, PORT);
  1715. cli.set_connection_timeout(std::chrono::seconds(5));
  1716. auto res =
  1717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1718. "application/json", [](uint64_t, uint64_t) { return true; });
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ("Hello World!", res->body);
  1721. EXPECT_EQ(StatusCode::OK_200, res->status);
  1722. }
  1723. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1724. Server svr;
  1725. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1726. res.set_content("Hello World!", "text/plain");
  1727. });
  1728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1729. auto se = detail::scope_exit([&] {
  1730. svr.stop();
  1731. thread.join();
  1732. ASSERT_FALSE(svr.is_running());
  1733. });
  1734. svr.wait_until_ready();
  1735. Client cli(HOST, PORT);
  1736. cli.set_connection_timeout(std::chrono::seconds(5));
  1737. auto res =
  1738. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1739. "application/json", [](uint64_t, uint64_t) { return false; });
  1740. ASSERT_TRUE(!res);
  1741. EXPECT_EQ(Error::Canceled, res.error());
  1742. }
  1743. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1744. Server svr;
  1745. svr.set_payload_max_length(200 * 1024 * 1024);
  1746. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content(LARGE_DATA, "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. Client cli(HOST, PORT);
  1757. cli.set_payload_max_length(200 * 1024 * 1024);
  1758. cli.set_connection_timeout(std::chrono::seconds(5));
  1759. auto res =
  1760. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1761. "application/json", [](uint64_t, uint64_t) { return false; });
  1762. ASSERT_TRUE(!res);
  1763. EXPECT_EQ(Error::Canceled, res.error());
  1764. }
  1765. static std::string remove_whitespace(const std::string &input) {
  1766. std::string output;
  1767. output.reserve(input.size());
  1768. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1769. [](unsigned char c) { return !std::isspace(c); });
  1770. return output;
  1771. }
  1772. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1773. auto host = "httpbingo.org";
  1774. auto path = std::string{"/basic-auth/hello/world"};
  1775. #ifdef CPPHTTPLIB_SSL_ENABLED
  1776. auto port = 443;
  1777. SSLClient cli(host, port);
  1778. #else
  1779. auto port = 80;
  1780. Client cli(host, port);
  1781. #endif
  1782. {
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1786. }
  1787. {
  1788. auto res =
  1789. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1790. ASSERT_TRUE(res);
  1791. auto body = remove_whitespace(res->body);
  1792. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1793. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1794. EXPECT_EQ(StatusCode::OK_200, res->status);
  1795. }
  1796. {
  1797. cli.set_basic_auth("hello", "world");
  1798. auto res = cli.Get(path);
  1799. ASSERT_TRUE(res);
  1800. auto body = remove_whitespace(res->body);
  1801. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1802. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1803. EXPECT_EQ(StatusCode::OK_200, res->status);
  1804. }
  1805. {
  1806. cli.set_basic_auth("hello", "bad");
  1807. auto res = cli.Get(path);
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1810. }
  1811. {
  1812. cli.set_basic_auth("bad", "world");
  1813. auto res = cli.Get(path);
  1814. ASSERT_TRUE(res);
  1815. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1816. }
  1817. }
  1818. #ifdef CPPHTTPLIB_SSL_ENABLED
  1819. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1820. auto host = "httpbingo.org";
  1821. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1822. auto paths = std::vector<std::string>{
  1823. "/digest-auth/auth/hello/world/MD5",
  1824. "/digest-auth/auth/hello/world/SHA-256",
  1825. };
  1826. auto port = 443;
  1827. SSLClient cli(host, port);
  1828. {
  1829. auto res = cli.Get(unauth_path);
  1830. ASSERT_TRUE(res);
  1831. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1832. }
  1833. {
  1834. cli.set_digest_auth("hello", "world");
  1835. for (const auto &path : paths) {
  1836. auto res = cli.Get(path.c_str());
  1837. ASSERT_TRUE(res);
  1838. auto body = remove_whitespace(res->body);
  1839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. }
  1843. cli.set_digest_auth("hello", "bad");
  1844. for (const auto &path : paths) {
  1845. auto res = cli.Get(path.c_str());
  1846. ASSERT_TRUE(res);
  1847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1848. }
  1849. }
  1850. }
  1851. #endif
  1852. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1853. auto host = "google.com";
  1854. auto another_host = "example.com";
  1855. auto wrong_ip = "0.0.0.0";
  1856. #ifdef CPPHTTPLIB_SSL_ENABLED
  1857. SSLClient cli(host);
  1858. #else
  1859. Client cli(host);
  1860. #endif
  1861. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1862. auto res = cli.Get("/");
  1863. ASSERT_TRUE(res);
  1864. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1865. }
  1866. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1867. auto host = "google.com";
  1868. auto wrong_ip = "0.0.0.0";
  1869. #ifdef CPPHTTPLIB_SSL_ENABLED
  1870. SSLClient cli(host);
  1871. #else
  1872. Client cli(host);
  1873. #endif
  1874. cli.set_hostname_addr_map({{host, wrong_ip}});
  1875. auto res = cli.Get("/");
  1876. ASSERT_TRUE(!res);
  1877. EXPECT_EQ(Error::Connection, res.error());
  1878. }
  1879. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1880. auto host = "httpbingo.org";
  1881. auto path = std::string{"/absolute-redirect/3"};
  1882. #ifdef CPPHTTPLIB_SSL_ENABLED
  1883. SSLClient cli(host);
  1884. #else
  1885. Client cli(host);
  1886. #endif
  1887. cli.set_follow_location(true);
  1888. auto res = cli.Get(path);
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::OK_200, res->status);
  1891. }
  1892. TEST(RedirectTest, Redirect_Online) {
  1893. auto host = "httpbingo.org";
  1894. auto path = std::string{"/redirect/3"};
  1895. #ifdef CPPHTTPLIB_SSL_ENABLED
  1896. SSLClient cli(host);
  1897. #else
  1898. Client cli(host);
  1899. #endif
  1900. cli.set_follow_location(true);
  1901. auto res = cli.Get(path);
  1902. ASSERT_TRUE(res);
  1903. EXPECT_EQ(StatusCode::OK_200, res->status);
  1904. }
  1905. TEST(RelativeRedirectTest, Redirect_Online) {
  1906. auto host = "httpbingo.org";
  1907. auto path = std::string{"/relative-redirect/3"};
  1908. #ifdef CPPHTTPLIB_SSL_ENABLED
  1909. SSLClient cli(host);
  1910. #else
  1911. Client cli(host);
  1912. #endif
  1913. cli.set_follow_location(true);
  1914. auto res = cli.Get(path);
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::OK_200, res->status);
  1917. }
  1918. TEST(TooManyRedirectTest, Redirect_Online) {
  1919. auto host = "httpbingo.org";
  1920. auto path = std::string{"/redirect/21"};
  1921. #ifdef CPPHTTPLIB_SSL_ENABLED
  1922. SSLClient cli(host);
  1923. #else
  1924. Client cli(host);
  1925. #endif
  1926. cli.set_follow_location(true);
  1927. auto res = cli.Get(path);
  1928. ASSERT_TRUE(!res);
  1929. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1930. }
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. TEST(YahooRedirectTest, Redirect_Online) {
  1933. Client cli("yahoo.com");
  1934. auto res = cli.Get("/");
  1935. ASSERT_TRUE(res);
  1936. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1937. cli.set_follow_location(true);
  1938. res = cli.Get("/");
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(StatusCode::OK_200, res->status);
  1941. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1942. }
  1943. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1944. #define REDIR_HOST "httpbingo.org"
  1945. #define REDIR_PATH "/redirect-to"
  1946. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1947. SSLClient cli(REDIR_HOST);
  1948. cli.set_follow_location(true);
  1949. auto res =
  1950. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. }
  1954. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1955. SSLClient cli(REDIR_HOST);
  1956. cli.set_follow_location(true);
  1957. Params params;
  1958. params.emplace("url", "http://example.com");
  1959. params.emplace("status_code", "302");
  1960. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. }
  1964. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1965. SSLClient cli(REDIR_HOST);
  1966. cli.set_follow_location(true);
  1967. Params params;
  1968. params.emplace("url", "http://example.com");
  1969. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. }
  1973. TEST(UrlWithSpace, Redirect_Online) {
  1974. SSLClient cli("edge.forgecdn.net");
  1975. cli.set_follow_location(true);
  1976. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(StatusCode::OK_200, res->status);
  1979. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1980. }
  1981. #endif
  1982. #if !defined(_WIN32) && !defined(_WIN64)
  1983. TEST(ReceiveSignals, Signal) {
  1984. auto setupSignalHandlers = []() {
  1985. struct sigaction act;
  1986. sigemptyset(&act.sa_mask);
  1987. act.sa_flags = SA_SIGINFO;
  1988. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1989. switch (sig) {
  1990. case SIGINT:
  1991. default: break;
  1992. }
  1993. };
  1994. ::sigaction(SIGINT, &act, nullptr);
  1995. };
  1996. Server svr;
  1997. int port = 0;
  1998. auto thread = std::thread([&]() {
  1999. setupSignalHandlers();
  2000. port = svr.bind_to_any_port(HOST);
  2001. svr.listen_after_bind();
  2002. });
  2003. auto se = detail::scope_exit([&] {
  2004. svr.stop();
  2005. thread.join();
  2006. ASSERT_FALSE(svr.is_running());
  2007. });
  2008. svr.wait_until_ready();
  2009. ASSERT_TRUE(svr.is_running());
  2010. pthread_kill(thread.native_handle(), SIGINT);
  2011. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2012. ASSERT_TRUE(svr.is_running());
  2013. }
  2014. #endif
  2015. TEST(RedirectToDifferentPort, Redirect) {
  2016. Server svr1;
  2017. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. int svr1_port = 0;
  2021. auto thread1 = std::thread([&]() {
  2022. svr1_port = svr1.bind_to_any_port(HOST);
  2023. svr1.listen_after_bind();
  2024. });
  2025. Server svr2;
  2026. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2027. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2028. });
  2029. int svr2_port = 0;
  2030. auto thread2 = std::thread([&]() {
  2031. svr2_port = svr2.bind_to_any_port(HOST);
  2032. svr2.listen_after_bind();
  2033. });
  2034. auto se = detail::scope_exit([&] {
  2035. svr2.stop();
  2036. thread2.join();
  2037. svr1.stop();
  2038. thread1.join();
  2039. ASSERT_FALSE(svr2.is_running());
  2040. ASSERT_FALSE(svr1.is_running());
  2041. });
  2042. svr1.wait_until_ready();
  2043. svr2.wait_until_ready();
  2044. Client cli("localhost", svr2_port);
  2045. cli.set_follow_location(true);
  2046. auto res = cli.Get("/2");
  2047. ASSERT_TRUE(res);
  2048. EXPECT_EQ(StatusCode::OK_200, res->status);
  2049. EXPECT_EQ("Hello World!", res->body);
  2050. }
  2051. static void
  2052. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2053. Server svr1;
  2054. std::string captured_authorization;
  2055. svr1.Get("/target", [&](const Request &req, Response &res) {
  2056. captured_authorization = req.get_header_value("Authorization");
  2057. res.set_content("OK", "text/plain");
  2058. });
  2059. int svr1_port = 0;
  2060. auto thread1 = std::thread([&]() {
  2061. svr1_port = svr1.bind_to_any_port(HOST);
  2062. svr1.listen_after_bind();
  2063. });
  2064. Server svr2;
  2065. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2066. res.set_redirect(
  2067. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  2068. });
  2069. int svr2_port = 0;
  2070. auto thread2 = std::thread([&]() {
  2071. svr2_port = svr2.bind_to_any_port(HOST);
  2072. svr2.listen_after_bind();
  2073. });
  2074. auto se = detail::scope_exit([&] {
  2075. svr2.stop();
  2076. thread2.join();
  2077. svr1.stop();
  2078. thread1.join();
  2079. ASSERT_FALSE(svr2.is_running());
  2080. ASSERT_FALSE(svr1.is_running());
  2081. });
  2082. svr1.wait_until_ready();
  2083. svr2.wait_until_ready();
  2084. Client cli("localhost", svr2_port);
  2085. cli.set_follow_location(true);
  2086. set_auth(cli);
  2087. auto res = cli.Get("/redir");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. // RFC 9110: credentials MUST NOT be forwarded to a different host
  2091. EXPECT_TRUE(captured_authorization.empty());
  2092. }
  2093. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  2094. TestDoNotForwardCredentialsOnRedirect(
  2095. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  2096. }
  2097. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  2098. TestDoNotForwardCredentialsOnRedirect(
  2099. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  2100. }
  2101. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  2102. Server svr;
  2103. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  2104. // Port number that overflows int — should not crash
  2105. res.set_redirect("http://localhost:99999999999999999999/target");
  2106. });
  2107. auto port = svr.bind_to_any_port(HOST);
  2108. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2109. auto se = detail::scope_exit([&] {
  2110. svr.stop();
  2111. thread.join();
  2112. ASSERT_FALSE(svr.is_running());
  2113. });
  2114. svr.wait_until_ready();
  2115. Client cli(HOST, port);
  2116. cli.set_follow_location(true);
  2117. auto res = cli.Get("/redir");
  2118. // Should fail gracefully, not crash (no valid response due to bad port)
  2119. EXPECT_FALSE(res);
  2120. }
  2121. TEST(RedirectFromPageWithContent, Redirect) {
  2122. Server svr;
  2123. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2124. res.set_content("___", "text/plain");
  2125. res.set_redirect("/2");
  2126. });
  2127. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2128. res.set_content("Hello World!", "text/plain");
  2129. });
  2130. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2131. auto se = detail::scope_exit([&] {
  2132. svr.stop();
  2133. th.join();
  2134. ASSERT_FALSE(svr.is_running());
  2135. });
  2136. svr.wait_until_ready();
  2137. {
  2138. Client cli("localhost", PORT);
  2139. cli.set_follow_location(true);
  2140. std::string body;
  2141. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2142. body.append(data, data_length);
  2143. return true;
  2144. });
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. EXPECT_EQ("Hello World!", body);
  2148. }
  2149. {
  2150. Client cli("localhost", PORT);
  2151. std::string body;
  2152. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2153. body.append(data, data_length);
  2154. return true;
  2155. });
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(StatusCode::Found_302, res->status);
  2158. EXPECT_EQ("___", body);
  2159. }
  2160. }
  2161. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2162. Server svr;
  2163. auto port_str = std::to_string(PORT);
  2164. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2165. auto expected_host = "[::1]:" + port_str;
  2166. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2167. res.set_content("___", "text/plain");
  2168. // res.set_redirect("/2");
  2169. res.set_redirect(redirect_url);
  2170. });
  2171. svr.Get("/2", [&](const Request &req, Response &res) {
  2172. auto host_header = req.headers.find("Host");
  2173. ASSERT_TRUE(host_header != req.headers.end());
  2174. EXPECT_EQ(expected_host, host_header->second);
  2175. res.set_content("Hello World!", "text/plain");
  2176. });
  2177. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. th.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2184. // actually starts anything, so the condition !svr.is_running() will
  2185. // always remain true, and the loop never stops.
  2186. // This basically counts how many milliseconds have passed since the
  2187. // call to svr.listen(), and if after 5 seconds nothing started yet
  2188. // aborts the test.
  2189. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2191. ASSERT_LT(milliseconds, 5000U);
  2192. }
  2193. {
  2194. Client cli("::1", PORT);
  2195. cli.set_follow_location(true);
  2196. std::string body;
  2197. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2198. body.append(data, data_length);
  2199. return true;
  2200. });
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(StatusCode::OK_200, res->status);
  2203. EXPECT_EQ("Hello World!", body);
  2204. }
  2205. {
  2206. Client cli("::1", PORT);
  2207. std::string body;
  2208. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2209. body.append(data, data_length);
  2210. return true;
  2211. });
  2212. ASSERT_TRUE(res);
  2213. EXPECT_EQ(StatusCode::Found_302, res->status);
  2214. EXPECT_EQ("___", body);
  2215. }
  2216. }
  2217. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2218. Server svr;
  2219. svr.Get("/foo", [](const Request &req, Response &res) {
  2220. auto a = req.params.find("a");
  2221. if (a != req.params.end()) {
  2222. res.set_content((*a).second, "text/plain");
  2223. res.status = StatusCode::OK_200;
  2224. } else {
  2225. res.status = StatusCode::BadRequest_400;
  2226. }
  2227. });
  2228. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. thread.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. {
  2236. Client cli(HOST, PORT);
  2237. cli.set_path_encode(false);
  2238. auto res = cli.Get("/foo?a=explicitly+encoded");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. // This expects it back with a space, as the `+` won't have been
  2242. // url-encoded, and server-side the params get decoded turning `+`
  2243. // into spaces.
  2244. EXPECT_EQ("explicitly encoded", res->body);
  2245. }
  2246. }
  2247. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2248. Server svr;
  2249. svr.Get("/", [](const Request &req, Response &) {
  2250. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2251. });
  2252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2253. auto se = detail::scope_exit([&] {
  2254. svr.stop();
  2255. thread.join();
  2256. ASSERT_FALSE(svr.is_running());
  2257. });
  2258. svr.wait_until_ready();
  2259. {
  2260. Client cli(HOST, PORT);
  2261. cli.set_path_encode(false);
  2262. auto res = cli.Get("/?something=%0A");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::OK_200, res->status);
  2265. }
  2266. }
  2267. TEST(BindServerTest, BindDualStack) {
  2268. Server svr;
  2269. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2270. res.set_content("Hello World!", "text/plain");
  2271. });
  2272. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2273. auto se = detail::scope_exit([&] {
  2274. svr.stop();
  2275. thread.join();
  2276. ASSERT_FALSE(svr.is_running());
  2277. });
  2278. svr.wait_until_ready();
  2279. {
  2280. Client cli("127.0.0.1", PORT);
  2281. auto res = cli.Get("/1");
  2282. ASSERT_TRUE(res);
  2283. EXPECT_EQ(StatusCode::OK_200, res->status);
  2284. EXPECT_EQ("Hello World!", res->body);
  2285. }
  2286. {
  2287. Client cli("::1", PORT);
  2288. auto res = cli.Get("/1");
  2289. ASSERT_TRUE(res);
  2290. EXPECT_EQ(StatusCode::OK_200, res->status);
  2291. EXPECT_EQ("Hello World!", res->body);
  2292. }
  2293. }
  2294. TEST(BindServerTest, BindAndListenSeparately) {
  2295. Server svr;
  2296. int port = svr.bind_to_any_port("0.0.0.0");
  2297. ASSERT_TRUE(svr.is_valid());
  2298. ASSERT_TRUE(port > 0);
  2299. svr.stop();
  2300. }
  2301. #ifdef CPPHTTPLIB_SSL_ENABLED
  2302. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2304. CLIENT_CA_CERT_DIR);
  2305. int port = svr.bind_to_any_port("0.0.0.0");
  2306. ASSERT_TRUE(svr.is_valid());
  2307. ASSERT_TRUE(port > 0);
  2308. svr.stop();
  2309. }
  2310. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2311. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2312. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2313. int port = svr.bind_to_any_port("0.0.0.0");
  2314. ASSERT_TRUE(svr.is_valid());
  2315. ASSERT_TRUE(port > 0);
  2316. svr.stop();
  2317. }
  2318. TEST(BindServerTest, UpdateCertsPem) {
  2319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2320. int port = svr.bind_to_any_port("0.0.0.0");
  2321. ASSERT_TRUE(svr.is_valid());
  2322. ASSERT_TRUE(port > 0);
  2323. // Read PEM files
  2324. std::string cert_pem, key_pem, ca_pem;
  2325. read_file(SERVER_CERT_FILE, cert_pem);
  2326. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2327. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2328. // Update server certificates using PEM API
  2329. ASSERT_TRUE(
  2330. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2331. ASSERT_TRUE(svr.is_valid());
  2332. svr.stop();
  2333. }
  2334. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2335. // Start server with client CA (enables client auth)
  2336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2337. ASSERT_TRUE(svr.is_valid());
  2338. bool handler_called = false;
  2339. svr.Get("/test", [&](const Request &req, Response &res) {
  2340. handler_called = true;
  2341. // Verify client certificate is present
  2342. auto cert = req.peer_cert();
  2343. EXPECT_TRUE(static_cast<bool>(cert));
  2344. res.set_content("ok", "text/plain");
  2345. });
  2346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. t.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. // Read PEM files
  2354. std::string cert_pem, key_pem, ca_pem;
  2355. read_file(SERVER_CERT_FILE, cert_pem);
  2356. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2357. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2358. // Update server certificates and client CA using PEM API while server running
  2359. ASSERT_TRUE(
  2360. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2361. // Connect with client certificate
  2362. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2363. cli.enable_server_certificate_verification(false);
  2364. cli.set_connection_timeout(30);
  2365. auto res = cli.Get("/test");
  2366. ASSERT_TRUE(res);
  2367. ASSERT_EQ(StatusCode::OK_200, res->status);
  2368. ASSERT_TRUE(handler_called);
  2369. EXPECT_EQ("ok", res->body);
  2370. }
  2371. #endif
  2372. TEST(ErrorHandlerTest, ContentLength) {
  2373. Server svr;
  2374. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2375. res.status = StatusCode::OK_200;
  2376. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2377. "text/html"); // <= Content-Length still 13
  2378. });
  2379. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2380. res.set_content("Hello World!\n", "text/plain");
  2381. res.status = 524;
  2382. });
  2383. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2384. auto se = detail::scope_exit([&] {
  2385. svr.stop();
  2386. thread.join();
  2387. ASSERT_FALSE(svr.is_running());
  2388. });
  2389. svr.wait_until_ready();
  2390. {
  2391. Client cli(HOST, PORT);
  2392. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2393. ASSERT_TRUE(res);
  2394. EXPECT_EQ(StatusCode::OK_200, res->status);
  2395. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2397. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2398. }
  2399. }
  2400. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2401. TEST(ExceptionTest, WithoutExceptionHandler) {
  2402. Server svr;
  2403. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2404. throw std::runtime_error("exception...");
  2405. });
  2406. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2407. throw std::runtime_error("exception\r\n...");
  2408. });
  2409. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2410. auto se = detail::scope_exit([&] {
  2411. svr.stop();
  2412. listen_thread.join();
  2413. ASSERT_FALSE(svr.is_running());
  2414. });
  2415. svr.wait_until_ready();
  2416. Client cli("localhost", PORT);
  2417. {
  2418. auto res = cli.Get("/exception");
  2419. ASSERT_TRUE(res);
  2420. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2421. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2422. }
  2423. {
  2424. auto res = cli.Get("/unknown");
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2427. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2428. }
  2429. }
  2430. TEST(ExceptionTest, WithExceptionHandler) {
  2431. Server svr;
  2432. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2433. std::exception_ptr ep) {
  2434. EXPECT_FALSE(ep == nullptr);
  2435. try {
  2436. std::rethrow_exception(ep);
  2437. } catch (std::exception &e) {
  2438. EXPECT_EQ("abc", std::string(e.what()));
  2439. } catch (...) {}
  2440. res.status = StatusCode::InternalServerError_500;
  2441. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2442. "text/html"); // <= Content-Length still 13 at this point
  2443. });
  2444. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2445. res.set_content("Hello World!\n", "text/plain");
  2446. throw std::runtime_error("abc");
  2447. });
  2448. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2449. auto se = detail::scope_exit([&] {
  2450. svr.stop();
  2451. thread.join();
  2452. ASSERT_FALSE(svr.is_running());
  2453. });
  2454. svr.wait_until_ready();
  2455. for (size_t i = 0; i < 10; i++) {
  2456. Client cli(HOST, PORT);
  2457. for (size_t j = 0; j < 100; j++) {
  2458. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2459. ASSERT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2461. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2462. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2463. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2464. }
  2465. cli.set_keep_alive(true);
  2466. for (size_t j = 0; j < 100; j++) {
  2467. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2468. ASSERT_TRUE(res);
  2469. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2470. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2471. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2473. }
  2474. }
  2475. }
  2476. TEST(ExceptionTest, AndErrorHandler) {
  2477. Server svr;
  2478. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2479. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2480. });
  2481. svr.set_exception_handler(
  2482. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2483. EXPECT_FALSE(ep == nullptr);
  2484. try {
  2485. std::rethrow_exception(ep);
  2486. } catch (std::exception &e) {
  2487. res.set_content(e.what(), "text/html");
  2488. } catch (...) {}
  2489. res.status = StatusCode::InternalServerError_500;
  2490. });
  2491. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2492. throw std::runtime_error("EXCEPTION");
  2493. });
  2494. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2495. res.set_content("ERROR", "text/html");
  2496. res.status = StatusCode::InternalServerError_500;
  2497. });
  2498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. thread.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, PORT);
  2506. {
  2507. auto res = cli.Get("/exception");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2510. EXPECT_EQ("EXCEPTION", res->body);
  2511. }
  2512. {
  2513. auto res = cli.Get("/error");
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2516. EXPECT_EQ("ERROR", res->body);
  2517. }
  2518. {
  2519. auto res = cli.Get("/invalid");
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2522. EXPECT_EQ("NOT_FOUND", res->body);
  2523. }
  2524. }
  2525. #endif
  2526. TEST(NoContentTest, ContentLength) {
  2527. Server svr;
  2528. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2529. res.status = StatusCode::NoContent_204;
  2530. });
  2531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2532. auto se = detail::scope_exit([&] {
  2533. svr.stop();
  2534. thread.join();
  2535. ASSERT_FALSE(svr.is_running());
  2536. });
  2537. svr.wait_until_ready();
  2538. {
  2539. Client cli(HOST, PORT);
  2540. auto res = cli.Get("/hi");
  2541. ASSERT_TRUE(res);
  2542. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2543. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2544. }
  2545. }
  2546. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2547. #ifdef CPPHTTPLIB_SSL_ENABLED
  2548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2549. ASSERT_TRUE(svr.is_valid());
  2550. #else
  2551. Server svr;
  2552. #endif
  2553. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2554. if (req.path == "/routing_handler") {
  2555. res.set_header("PRE_ROUTING", "on");
  2556. res.set_content("Routing Handler", "text/plain");
  2557. return httplib::Server::HandlerResponse::Handled;
  2558. }
  2559. return httplib::Server::HandlerResponse::Unhandled;
  2560. });
  2561. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2562. res.set_content("Error", "text/html");
  2563. });
  2564. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2565. if (req.path == "/routing_handler") {
  2566. res.set_header("POST_ROUTING", "on");
  2567. }
  2568. });
  2569. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2570. res.set_content("Hello World!\n", "text/plain");
  2571. });
  2572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2573. auto se = detail::scope_exit([&] {
  2574. svr.stop();
  2575. thread.join();
  2576. ASSERT_FALSE(svr.is_running());
  2577. });
  2578. svr.wait_until_ready();
  2579. {
  2580. #ifdef CPPHTTPLIB_SSL_ENABLED
  2581. SSLClient cli(HOST, PORT);
  2582. cli.enable_server_certificate_verification(false);
  2583. #else
  2584. Client cli(HOST, PORT);
  2585. #endif
  2586. auto res = cli.Get("/routing_handler");
  2587. ASSERT_TRUE(res);
  2588. EXPECT_EQ(StatusCode::OK_200, res->status);
  2589. EXPECT_EQ("Routing Handler", res->body);
  2590. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2591. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2592. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2593. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2594. }
  2595. {
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. SSLClient cli(HOST, PORT);
  2598. cli.enable_server_certificate_verification(false);
  2599. #else
  2600. Client cli(HOST, PORT);
  2601. #endif
  2602. auto res = cli.Get("/hi");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(StatusCode::OK_200, res->status);
  2605. EXPECT_EQ("Hello World!\n", res->body);
  2606. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2607. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2608. }
  2609. {
  2610. #ifdef CPPHTTPLIB_SSL_ENABLED
  2611. SSLClient cli(HOST, PORT);
  2612. cli.enable_server_certificate_verification(false);
  2613. #else
  2614. Client cli(HOST, PORT);
  2615. #endif
  2616. auto res = cli.Get("/aaa");
  2617. ASSERT_TRUE(res);
  2618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2619. EXPECT_EQ("Error", res->body);
  2620. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2621. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2622. }
  2623. }
  2624. TEST(RequestHandlerTest, PreRequestHandler) {
  2625. auto route_path = "/user/:user";
  2626. Server svr;
  2627. svr.Get("/hi", [](const Request &, Response &res) {
  2628. res.set_content("hi", "text/plain");
  2629. });
  2630. svr.Get(route_path, [](const Request &req, Response &res) {
  2631. res.set_content(req.path_params.at("user"), "text/plain");
  2632. });
  2633. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2634. if (req.matched_route == route_path) {
  2635. auto user = req.path_params.at("user");
  2636. if (user != "john") {
  2637. res.status = StatusCode::Forbidden_403;
  2638. res.set_content("error", "text/html");
  2639. return Server::HandlerResponse::Handled;
  2640. }
  2641. }
  2642. return Server::HandlerResponse::Unhandled;
  2643. });
  2644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2645. auto se = detail::scope_exit([&] {
  2646. svr.stop();
  2647. thread.join();
  2648. ASSERT_FALSE(svr.is_running());
  2649. });
  2650. svr.wait_until_ready();
  2651. Client cli(HOST, PORT);
  2652. {
  2653. auto res = cli.Get("/hi");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("hi", res->body);
  2657. }
  2658. {
  2659. auto res = cli.Get("/user/john");
  2660. ASSERT_TRUE(res);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. EXPECT_EQ("john", res->body);
  2663. }
  2664. {
  2665. auto res = cli.Get("/user/invalid-user");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2668. EXPECT_EQ("error", res->body);
  2669. }
  2670. }
  2671. TEST(UserDataTest, BasicOperations) {
  2672. httplib::UserData ud;
  2673. // Initially empty
  2674. EXPECT_FALSE(ud.has("key"));
  2675. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2676. // set and get
  2677. ud.set("key", 42);
  2678. EXPECT_TRUE(ud.has("key"));
  2679. auto *p = ud.get<int>("key");
  2680. ASSERT_NE(nullptr, p);
  2681. EXPECT_EQ(42, *p);
  2682. // Type mismatch → nullptr
  2683. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2684. // Overwrite with different type
  2685. ud.set("key", std::string("hello"));
  2686. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2687. auto *s = ud.get<std::string>("key");
  2688. ASSERT_NE(nullptr, s);
  2689. EXPECT_EQ("hello", *s);
  2690. // erase
  2691. ud.erase("key");
  2692. EXPECT_FALSE(ud.has("key"));
  2693. // clear
  2694. ud.set("a", 1);
  2695. ud.set("b", 2);
  2696. ud.clear();
  2697. EXPECT_FALSE(ud.has("a"));
  2698. EXPECT_FALSE(ud.has("b"));
  2699. }
  2700. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2701. struct AuthCtx {
  2702. std::string user_id;
  2703. };
  2704. Server svr;
  2705. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2706. res.user_data.set("auth", AuthCtx{"alice"});
  2707. return Server::HandlerResponse::Unhandled;
  2708. });
  2709. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2710. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2711. ASSERT_NE(nullptr, ctx);
  2712. res.set_content("Hello " + ctx->user_id, "text/plain");
  2713. });
  2714. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2715. auto se = detail::scope_exit([&] {
  2716. svr.stop();
  2717. thread.join();
  2718. ASSERT_FALSE(svr.is_running());
  2719. });
  2720. svr.wait_until_ready();
  2721. Client cli(HOST, PORT);
  2722. auto res = cli.Get("/me");
  2723. ASSERT_TRUE(res);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. EXPECT_EQ("Hello alice", res->body);
  2726. }
  2727. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2728. struct RoleCtx {
  2729. std::string role;
  2730. };
  2731. Server svr;
  2732. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2733. res.user_data.set("role", RoleCtx{"admin"});
  2734. return Server::HandlerResponse::Unhandled;
  2735. });
  2736. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2737. auto *ctx = res.user_data.get<RoleCtx>("role");
  2738. ASSERT_NE(nullptr, ctx);
  2739. res.set_content(ctx->role, "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. auto res = cli.Get("/role");
  2750. ASSERT_TRUE(res);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. EXPECT_EQ("admin", res->body);
  2753. }
  2754. TEST(InvalidFormatTest, StatusCode) {
  2755. Server svr;
  2756. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2757. res.set_content("Hello World!\n", "text/plain");
  2758. res.status = 9999; // Status should be a three-digit code...
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. {
  2768. Client cli(HOST, PORT);
  2769. auto res = cli.Get("/hi");
  2770. ASSERT_FALSE(res);
  2771. }
  2772. }
  2773. TEST(URLFragmentTest, WithFragment) {
  2774. Server svr;
  2775. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2776. EXPECT_TRUE(req.target == "/hi");
  2777. });
  2778. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2779. auto se = detail::scope_exit([&] {
  2780. svr.stop();
  2781. thread.join();
  2782. ASSERT_FALSE(svr.is_running());
  2783. });
  2784. svr.wait_until_ready();
  2785. {
  2786. Client cli(HOST, PORT);
  2787. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2788. EXPECT_TRUE(res);
  2789. EXPECT_EQ(StatusCode::OK_200, res->status);
  2790. res = cli.Get("/hi%23key1=val1=key2=val2");
  2791. EXPECT_TRUE(res);
  2792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2793. }
  2794. }
  2795. TEST(HeaderWriter, SetHeaderWriter) {
  2796. Server svr;
  2797. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2798. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2799. return detail::write_headers(strm, hdrs);
  2800. });
  2801. svr.Get("/hi", [](const Request &req, Response &res) {
  2802. auto it = req.headers.find("CustomClientHeader");
  2803. EXPECT_TRUE(it != req.headers.end());
  2804. EXPECT_EQ(it->second, "CustomClientValue");
  2805. res.set_content("Hello World!\n", "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. {
  2815. Client cli(HOST, PORT);
  2816. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2817. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2818. return detail::write_headers(strm, hdrs);
  2819. });
  2820. auto res = cli.Get("/hi");
  2821. EXPECT_TRUE(res);
  2822. EXPECT_EQ(StatusCode::OK_200, res->status);
  2823. auto it = res->headers.find("CustomServerHeader");
  2824. EXPECT_TRUE(it != res->headers.end());
  2825. EXPECT_EQ(it->second, "CustomServerValue");
  2826. }
  2827. }
  2828. class ServerTest : public ::testing::Test {
  2829. protected:
  2830. ServerTest()
  2831. : cli_(HOST, PORT)
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. ,
  2834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2835. #endif
  2836. {
  2837. #ifdef CPPHTTPLIB_SSL_ENABLED
  2838. cli_.enable_server_certificate_verification(false);
  2839. #endif
  2840. // Allow LARGE_DATA (100MB) responses
  2841. cli_.set_payload_max_length(200 * 1024 * 1024);
  2842. }
  2843. virtual void SetUp() {
  2844. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2845. svr_.set_payload_max_length(200 * 1024 * 1024);
  2846. svr_.set_mount_point("/", "./www");
  2847. svr_.set_mount_point("/mount", "./www2");
  2848. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2849. svr_.Get("/hi",
  2850. [&](const Request & /*req*/, Response &res) {
  2851. res.set_content("Hello World!", "text/plain");
  2852. })
  2853. .Get("/file_content",
  2854. [&](const Request & /*req*/, Response &res) {
  2855. res.set_file_content("./www/dir/test.html");
  2856. })
  2857. .Get("/file_content_with_content_type",
  2858. [&](const Request & /*req*/, Response &res) {
  2859. res.set_file_content("./www/file", "text/plain");
  2860. })
  2861. .Get("/invalid_file_content",
  2862. [&](const Request & /*req*/, Response &res) {
  2863. res.set_file_content("./www/dir/invalid_file_path");
  2864. })
  2865. .Get("/http_response_splitting",
  2866. [&](const Request & /*req*/, Response &res) {
  2867. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2868. EXPECT_EQ(0U, res.headers.size());
  2869. EXPECT_FALSE(res.has_header("a"));
  2870. res.set_header("a", "1\nSet-Cookie: a=1");
  2871. EXPECT_EQ(0U, res.headers.size());
  2872. EXPECT_FALSE(res.has_header("a"));
  2873. res.set_header("a", "1\rSet-Cookie: a=1");
  2874. EXPECT_EQ(0U, res.headers.size());
  2875. EXPECT_FALSE(res.has_header("a"));
  2876. res.set_header("a\r\nb", "0");
  2877. EXPECT_EQ(0U, res.headers.size());
  2878. EXPECT_FALSE(res.has_header("a"));
  2879. res.set_header("a\rb", "0");
  2880. EXPECT_EQ(0U, res.headers.size());
  2881. EXPECT_FALSE(res.has_header("a"));
  2882. res.set_header("a\nb", "0");
  2883. EXPECT_EQ(0U, res.headers.size());
  2884. EXPECT_FALSE(res.has_header("a"));
  2885. res.set_redirect("1\r\nSet-Cookie: a=1");
  2886. EXPECT_EQ(0U, res.headers.size());
  2887. EXPECT_FALSE(res.has_header("Location"));
  2888. })
  2889. .Get("/slow",
  2890. [&](const Request & /*req*/, Response &res) {
  2891. std::this_thread::sleep_for(std::chrono::seconds(4));
  2892. res.set_content("slow", "text/plain");
  2893. })
  2894. #if 0
  2895. .Post("/slowpost",
  2896. [&](const Request & /*req*/, Response &res) {
  2897. std::this_thread::sleep_for(std::chrono::seconds(2));
  2898. res.set_content("slow", "text/plain");
  2899. })
  2900. #endif
  2901. .Get("/remote_addr",
  2902. [&](const Request &req, Response &res) {
  2903. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2904. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2905. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2906. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2907. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2908. #endif
  2909. res.set_content(req.remote_addr, "text/plain");
  2910. })
  2911. .Get("/local_addr",
  2912. [&](const Request &req, Response &res) {
  2913. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2914. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2915. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2916. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2917. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2918. #endif
  2919. auto local_addr = req.local_addr;
  2920. auto local_port = std::to_string(req.local_port);
  2921. res.set_content(local_addr.append(":").append(local_port),
  2922. "text/plain");
  2923. })
  2924. .Get("/endwith%",
  2925. [&](const Request & /*req*/, Response &res) {
  2926. res.set_content("Hello World!", "text/plain");
  2927. })
  2928. .Get("/a\\+\\+b",
  2929. [&](const Request &req, Response &res) {
  2930. ASSERT_TRUE(req.has_param("a +b"));
  2931. auto val = req.get_param_value("a +b");
  2932. res.set_content(val, "text/plain");
  2933. })
  2934. .Get("/", [&](const Request & /*req*/,
  2935. Response &res) { res.set_redirect("/hi"); })
  2936. .Post("/1",
  2937. [](const Request & /*req*/, Response &res) {
  2938. res.set_redirect("/2", StatusCode::SeeOther_303);
  2939. })
  2940. .Get("/2",
  2941. [](const Request & /*req*/, Response &res) {
  2942. res.set_content("redirected.", "text/plain");
  2943. res.status = StatusCode::OK_200;
  2944. })
  2945. .Post("/person",
  2946. [&](const Request &req, Response &res) {
  2947. if (req.has_param("name") && req.has_param("note")) {
  2948. persons_[req.get_param_value("name")] =
  2949. req.get_param_value("note");
  2950. } else {
  2951. res.status = StatusCode::BadRequest_400;
  2952. }
  2953. })
  2954. .Put("/person",
  2955. [&](const Request &req, Response &res) {
  2956. if (req.has_param("name") && req.has_param("note")) {
  2957. persons_[req.get_param_value("name")] =
  2958. req.get_param_value("note");
  2959. } else {
  2960. res.status = StatusCode::BadRequest_400;
  2961. }
  2962. })
  2963. .Get("/person/(.*)",
  2964. [&](const Request &req, Response &res) {
  2965. string name = req.matches[1];
  2966. if (persons_.find(name) != persons_.end()) {
  2967. auto note = persons_[name];
  2968. res.set_content(note, "text/plain");
  2969. } else {
  2970. res.status = StatusCode::NotFound_404;
  2971. }
  2972. })
  2973. .Delete("/person",
  2974. [&](const Request &req, Response &res) {
  2975. if (req.has_param("name")) {
  2976. string name = req.get_param_value("name");
  2977. if (persons_.find(name) != persons_.end()) {
  2978. persons_.erase(name);
  2979. res.set_content("DELETED", "text/plain");
  2980. } else {
  2981. res.status = StatusCode::NotFound_404;
  2982. }
  2983. } else {
  2984. res.status = StatusCode::BadRequest_400;
  2985. }
  2986. })
  2987. .Post("/x-www-form-urlencoded-json",
  2988. [&](const Request &req, Response &res) {
  2989. auto json = req.get_param_value("json");
  2990. ASSERT_EQ(JSON_DATA, json);
  2991. res.set_content(json, "appliation/json");
  2992. res.status = StatusCode::OK_200;
  2993. })
  2994. .Get("/streamed-chunked",
  2995. [&](const Request & /*req*/, Response &res) {
  2996. res.set_chunked_content_provider(
  2997. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2998. sink.os << "123";
  2999. sink.os << "456";
  3000. sink.os << "789";
  3001. sink.done();
  3002. return true;
  3003. });
  3004. })
  3005. .Get("/streamed-chunked-with-prohibited-trailer",
  3006. [&](const Request & /*req*/, Response &res) {
  3007. auto i = new int(0);
  3008. // Declare both a prohibited trailer (Content-Length) and an
  3009. // allowed one
  3010. res.set_header("Trailer", "Content-Length, X-Allowed");
  3011. res.set_chunked_content_provider(
  3012. "text/plain",
  3013. [i](size_t /*offset*/, DataSink &sink) {
  3014. switch (*i) {
  3015. case 0: sink.os << "123"; break;
  3016. case 1: sink.os << "456"; break;
  3017. case 2: sink.os << "789"; break;
  3018. case 3: {
  3019. sink.done_with_trailer(
  3020. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  3021. } break;
  3022. }
  3023. (*i)++;
  3024. return true;
  3025. },
  3026. [i](bool success) {
  3027. EXPECT_TRUE(success);
  3028. delete i;
  3029. });
  3030. })
  3031. .Get("/streamed-chunked2",
  3032. [&](const Request & /*req*/, Response &res) {
  3033. auto i = new int(0);
  3034. res.set_chunked_content_provider(
  3035. "text/plain",
  3036. [i](size_t /*offset*/, DataSink &sink) {
  3037. switch (*i) {
  3038. case 0: sink.os << "123"; break;
  3039. case 1: sink.os << "456"; break;
  3040. case 2: sink.os << "789"; break;
  3041. case 3: sink.done(); break;
  3042. }
  3043. (*i)++;
  3044. return true;
  3045. },
  3046. [i](bool success) {
  3047. EXPECT_TRUE(success);
  3048. delete i;
  3049. });
  3050. })
  3051. .Get("/streamed-chunked-with-trailer",
  3052. [&](const Request & /*req*/, Response &res) {
  3053. auto i = new int(0);
  3054. res.set_header("Trailer", "Dummy1, Dummy2");
  3055. res.set_chunked_content_provider(
  3056. "text/plain",
  3057. [i](size_t /*offset*/, DataSink &sink) {
  3058. switch (*i) {
  3059. case 0: sink.os << "123"; break;
  3060. case 1: sink.os << "456"; break;
  3061. case 2: sink.os << "789"; break;
  3062. case 3: {
  3063. sink.done_with_trailer(
  3064. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  3065. } break;
  3066. }
  3067. (*i)++;
  3068. return true;
  3069. },
  3070. [i](bool success) {
  3071. EXPECT_TRUE(success);
  3072. delete i;
  3073. });
  3074. })
  3075. .Get("/streamed",
  3076. [&](const Request & /*req*/, Response &res) {
  3077. res.set_content_provider(
  3078. 6, "text/plain",
  3079. [](size_t offset, size_t /*length*/, DataSink &sink) {
  3080. sink.os << (offset < 3 ? "a" : "b");
  3081. return true;
  3082. });
  3083. })
  3084. .Get("/streamed-with-range",
  3085. [&](const Request &req, Response &res) {
  3086. auto data = new std::string("abcdefg");
  3087. res.set_content_provider(
  3088. data->size(), "text/plain",
  3089. [data](size_t offset, size_t length, DataSink &sink) {
  3090. size_t DATA_CHUNK_SIZE = 4;
  3091. const auto &d = *data;
  3092. auto out_len =
  3093. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  3094. auto ret =
  3095. sink.write(&d[static_cast<size_t>(offset)], out_len);
  3096. EXPECT_TRUE(ret);
  3097. return true;
  3098. },
  3099. [data, &req](bool success) {
  3100. EXPECT_EQ(success, !req.has_param("error"));
  3101. delete data;
  3102. });
  3103. })
  3104. .Get("/streamed-cancel",
  3105. [&](const Request & /*req*/, Response &res) {
  3106. res.set_content_provider(
  3107. size_t(-1), "text/plain",
  3108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3109. sink.os << "data_chunk";
  3110. return true;
  3111. });
  3112. })
  3113. .Get("/regex-with-delimiter",
  3114. [&](const Request &req, Response & /*res*/) {
  3115. ASSERT_TRUE(req.has_param("key"));
  3116. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  3117. })
  3118. .Get("/with-range",
  3119. [&](const Request & /*req*/, Response &res) {
  3120. res.set_content("abcdefg", "text/plain");
  3121. })
  3122. .Get("/test-start-time",
  3123. [&](const Request &req, Response & /*res*/) {
  3124. EXPECT_NE(req.start_time_,
  3125. std::chrono::steady_clock::time_point::min());
  3126. })
  3127. .Get("/with-range-customized-response",
  3128. [&](const Request & /*req*/, Response &res) {
  3129. res.status = StatusCode::BadRequest_400;
  3130. res.set_content(JSON_DATA, "application/json");
  3131. })
  3132. .Post("/chunked",
  3133. [&](const Request &req, Response & /*res*/) {
  3134. EXPECT_EQ(req.body, "dechunked post body");
  3135. })
  3136. .Post("/large-chunked",
  3137. [&](const Request &req, Response & /*res*/) {
  3138. std::string expected(6 * 30 * 1024u, 'a');
  3139. EXPECT_EQ(req.body, expected);
  3140. })
  3141. .Post("/multipart",
  3142. [&](const Request &req, Response & /*res*/) {
  3143. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3144. req.form.get_field_count("text2") +
  3145. req.form.get_field_count("file3") +
  3146. req.form.get_field_count("file4"));
  3147. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3148. req.form.get_file_count("file2"));
  3149. ASSERT_TRUE(!req.form.has_file("???"));
  3150. ASSERT_TRUE(!req.form.has_field("???"));
  3151. ASSERT_TRUE(req.body.empty());
  3152. {
  3153. const auto &text = req.form.get_field("text1");
  3154. EXPECT_EQ("text default", text);
  3155. }
  3156. {
  3157. const auto &text = req.form.get_field("text2");
  3158. EXPECT_EQ("aωb", text);
  3159. }
  3160. {
  3161. const auto &file = req.form.get_file("file1");
  3162. EXPECT_EQ("hello.txt", file.filename);
  3163. EXPECT_EQ("text/plain", file.content_type);
  3164. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3165. }
  3166. {
  3167. const auto &file = req.form.get_file("file2");
  3168. EXPECT_EQ("world.json", file.filename);
  3169. EXPECT_EQ("application/json", file.content_type);
  3170. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3171. }
  3172. {
  3173. const auto &text = req.form.get_field("file3");
  3174. EXPECT_EQ(0u, text.size());
  3175. }
  3176. {
  3177. const auto &text = req.form.get_field("file4");
  3178. EXPECT_EQ(0u, text.size());
  3179. }
  3180. })
  3181. .Post("/multipart/multi_file_values",
  3182. [&](const Request &req, Response & /*res*/) {
  3183. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3184. req.form.get_field_count("multi_text1"));
  3185. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3186. ASSERT_TRUE(!req.form.has_file("???"));
  3187. ASSERT_TRUE(!req.form.has_field("???"));
  3188. ASSERT_TRUE(req.body.empty());
  3189. {
  3190. const auto &text = req.form.get_field("text");
  3191. EXPECT_EQ("default text", text);
  3192. }
  3193. {
  3194. const auto &text1_values = req.form.get_fields("multi_text1");
  3195. EXPECT_EQ(2u, text1_values.size());
  3196. EXPECT_EQ("aaaaa", text1_values[0]);
  3197. EXPECT_EQ("bbbbb", text1_values[1]);
  3198. }
  3199. {
  3200. const auto &file1_values = req.form.get_files("multi_file1");
  3201. EXPECT_EQ(2u, file1_values.size());
  3202. auto file1 = file1_values[0];
  3203. EXPECT_EQ(file1.filename, "hello.txt");
  3204. EXPECT_EQ(file1.content_type, "text/plain");
  3205. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3206. auto file2 = file1_values[1];
  3207. EXPECT_EQ(file2.filename, "world.json");
  3208. EXPECT_EQ(file2.content_type, "application/json");
  3209. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3210. }
  3211. })
  3212. .Post("/empty",
  3213. [&](const Request &req, Response &res) {
  3214. EXPECT_EQ(req.body, "");
  3215. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3216. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3217. res.set_content("empty", "text/plain");
  3218. })
  3219. .Post("/empty-no-content-type",
  3220. [&](const Request &req, Response &res) {
  3221. EXPECT_EQ(req.body, "");
  3222. EXPECT_FALSE(req.has_header("Content-Type"));
  3223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3224. res.set_content("empty-no-content-type", "text/plain");
  3225. })
  3226. .Post("/path-only",
  3227. [&](const Request &req, Response &res) {
  3228. EXPECT_EQ(req.body, "");
  3229. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3230. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3231. res.set_content("path-only", "text/plain");
  3232. })
  3233. .Post("/path-headers-only",
  3234. [&](const Request &req, Response &res) {
  3235. EXPECT_EQ(req.body, "");
  3236. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3237. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3238. EXPECT_EQ("world", req.get_header_value("hello"));
  3239. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3240. res.set_content("path-headers-only", "text/plain");
  3241. })
  3242. .Post("/post-large",
  3243. [&](const Request &req, Response &res) {
  3244. EXPECT_EQ(req.body, LARGE_DATA);
  3245. res.set_content(req.body, "text/plain");
  3246. })
  3247. .Post("/post-loopback",
  3248. [&](const Request &, Response &res,
  3249. ContentReader const &content_reader) {
  3250. std::string body;
  3251. content_reader([&](const char *data, size_t data_length) {
  3252. body.append(data, data_length);
  3253. return true;
  3254. });
  3255. res.set_content(body, "text/plain");
  3256. })
  3257. .Put("/put-loopback",
  3258. [&](const Request &, Response &res,
  3259. ContentReader const &content_reader) {
  3260. std::string body;
  3261. content_reader([&](const char *data, size_t data_length) {
  3262. body.append(data, data_length);
  3263. return true;
  3264. });
  3265. res.set_content(body, "text/plain");
  3266. })
  3267. .Patch("/patch-loopback",
  3268. [&](const Request &, Response &res,
  3269. ContentReader const &content_reader) {
  3270. std::string body;
  3271. content_reader([&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. res.set_content(body, "text/plain");
  3276. })
  3277. .Put("/empty-no-content-type",
  3278. [&](const Request &req, Response &res) {
  3279. EXPECT_EQ(req.body, "");
  3280. EXPECT_FALSE(req.has_header("Content-Type"));
  3281. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3282. res.set_content("empty-no-content-type", "text/plain");
  3283. })
  3284. .Put("/put",
  3285. [&](const Request &req, Response &res) {
  3286. EXPECT_EQ(req.body, "PUT");
  3287. res.set_content(req.body, "text/plain");
  3288. })
  3289. .Put("/put-large",
  3290. [&](const Request &req, Response &res) {
  3291. EXPECT_EQ(req.body, LARGE_DATA);
  3292. res.set_content(req.body, "text/plain");
  3293. })
  3294. .Patch("/patch",
  3295. [&](const Request &req, Response &res) {
  3296. EXPECT_EQ(req.body, "PATCH");
  3297. res.set_content(req.body, "text/plain");
  3298. })
  3299. .Delete("/delete",
  3300. [&](const Request & /*req*/, Response &res) {
  3301. res.set_content("DELETE", "text/plain");
  3302. })
  3303. .Delete("/delete-body",
  3304. [&](const Request &req, Response &res) {
  3305. EXPECT_EQ(req.body, "content");
  3306. res.set_content(req.body, "text/plain");
  3307. })
  3308. .Options(R"(\*)",
  3309. [&](const Request & /*req*/, Response &res) {
  3310. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3311. })
  3312. .Get("/request-target",
  3313. [&](const Request &req, Response & /*res*/) {
  3314. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3315. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3316. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3317. })
  3318. .Get("/long-query-value",
  3319. [&](const Request &req, Response & /*res*/) {
  3320. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3321. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3322. })
  3323. .Get("/too-long-query-value",
  3324. [&](const Request &req, Response & /*res*/) {
  3325. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3326. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3327. })
  3328. .Get("/array-param",
  3329. [&](const Request &req, Response & /*res*/) {
  3330. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3331. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3332. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3333. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3334. })
  3335. .Get("/array-param-values",
  3336. [&](const Request &req, Response & /*res*/) {
  3337. auto values = req.get_param_values("array");
  3338. EXPECT_EQ(3u, values.size());
  3339. EXPECT_EQ("value1", values[0]);
  3340. EXPECT_EQ("value2", values[1]);
  3341. EXPECT_EQ("value3", values[2]);
  3342. auto empty = req.get_param_values("nonexistent");
  3343. EXPECT_TRUE(empty.empty());
  3344. })
  3345. .Post("/validate-no-multiple-headers",
  3346. [&](const Request &req, Response & /*res*/) {
  3347. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3348. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3349. })
  3350. .Post("/content_receiver",
  3351. [&](const Request &req, Response &res,
  3352. const ContentReader &content_reader) {
  3353. if (req.is_multipart_form_data()) {
  3354. std::vector<FormData> items;
  3355. content_reader(
  3356. [&](const FormData &file) {
  3357. items.push_back(file);
  3358. return true;
  3359. },
  3360. [&](const char *data, size_t data_length) {
  3361. items.back().content.append(data, data_length);
  3362. return true;
  3363. });
  3364. EXPECT_EQ(5u, items.size());
  3365. {
  3366. const auto &file = get_file_value(items, "text1");
  3367. EXPECT_TRUE(file.filename.empty());
  3368. EXPECT_EQ("text default", file.content);
  3369. }
  3370. {
  3371. const auto &file = get_file_value(items, "text2");
  3372. EXPECT_TRUE(file.filename.empty());
  3373. EXPECT_EQ("aωb", file.content);
  3374. }
  3375. {
  3376. const auto &file = get_file_value(items, "file1");
  3377. EXPECT_EQ("hello.txt", file.filename);
  3378. EXPECT_EQ("text/plain", file.content_type);
  3379. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3380. }
  3381. {
  3382. const auto &file = get_file_value(items, "file2");
  3383. EXPECT_EQ("world.json", file.filename);
  3384. EXPECT_EQ("application/json", file.content_type);
  3385. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3386. }
  3387. {
  3388. const auto &file = get_file_value(items, "file3");
  3389. EXPECT_TRUE(file.filename.empty());
  3390. EXPECT_EQ("application/octet-stream", file.content_type);
  3391. EXPECT_EQ(0u, file.content.size());
  3392. }
  3393. } else {
  3394. std::string body;
  3395. content_reader([&](const char *data, size_t data_length) {
  3396. EXPECT_EQ(7U, data_length);
  3397. body.append(data, data_length);
  3398. return true;
  3399. });
  3400. EXPECT_EQ(body, "content");
  3401. res.set_content(body, "text/plain");
  3402. }
  3403. })
  3404. .Put("/content_receiver",
  3405. [&](const Request & /*req*/, Response &res,
  3406. const ContentReader &content_reader) {
  3407. std::string body;
  3408. content_reader([&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. EXPECT_EQ(body, "content");
  3413. res.set_content(body, "text/plain");
  3414. })
  3415. .Patch("/content_receiver",
  3416. [&](const Request & /*req*/, Response &res,
  3417. const ContentReader &content_reader) {
  3418. std::string body;
  3419. content_reader([&](const char *data, size_t data_length) {
  3420. body.append(data, data_length);
  3421. return true;
  3422. });
  3423. EXPECT_EQ(body, "content");
  3424. res.set_content(body, "text/plain");
  3425. })
  3426. .Post("/query-string-and-body",
  3427. [&](const Request &req, Response & /*res*/) {
  3428. ASSERT_TRUE(req.has_param("key"));
  3429. EXPECT_EQ(req.get_param_value("key"), "value");
  3430. EXPECT_EQ(req.body, "content");
  3431. })
  3432. .Get("/last-request",
  3433. [&](const Request &req, Response & /*res*/) {
  3434. EXPECT_EQ("close", req.get_header_value("Connection"));
  3435. })
  3436. .Get(R"(/redirect/(\d+))",
  3437. [&](const Request &req, Response &res) {
  3438. auto num = std::stoi(req.matches[1]) + 1;
  3439. std::string url = "/redirect/" + std::to_string(num);
  3440. res.set_redirect(url);
  3441. })
  3442. .Post("/binary",
  3443. [&](const Request &req, Response &res) {
  3444. EXPECT_EQ(4U, req.body.size());
  3445. EXPECT_EQ("application/octet-stream",
  3446. req.get_header_value("Content-Type"));
  3447. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3448. res.set_content(req.body, "application/octet-stream");
  3449. })
  3450. .Put("/binary",
  3451. [&](const Request &req, Response &res) {
  3452. EXPECT_EQ(4U, req.body.size());
  3453. EXPECT_EQ("application/octet-stream",
  3454. req.get_header_value("Content-Type"));
  3455. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3456. res.set_content(req.body, "application/octet-stream");
  3457. })
  3458. .Patch("/binary",
  3459. [&](const Request &req, Response &res) {
  3460. EXPECT_EQ(4U, req.body.size());
  3461. EXPECT_EQ("application/octet-stream",
  3462. req.get_header_value("Content-Type"));
  3463. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3464. res.set_content(req.body, "application/octet-stream");
  3465. })
  3466. .Delete("/binary",
  3467. [&](const Request &req, Response &res) {
  3468. EXPECT_EQ(4U, req.body.size());
  3469. EXPECT_EQ("application/octet-stream",
  3470. req.get_header_value("Content-Type"));
  3471. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3472. res.set_content(req.body, "application/octet-stream");
  3473. })
  3474. .Get("/issue1772",
  3475. [&](const Request & /*req*/, Response &res) {
  3476. res.status = 401;
  3477. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3478. })
  3479. .Delete("/issue609",
  3480. [](const httplib::Request &, httplib::Response &res,
  3481. const httplib::ContentReader &) {
  3482. res.set_content("ok", "text/plain");
  3483. })
  3484. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3485. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3486. .Get("/compress",
  3487. [&](const Request & /*req*/, Response &res) {
  3488. res.set_content(
  3489. "12345678901234567890123456789012345678901234567890123456789"
  3490. "01234567890123456789012345678901234567890",
  3491. "text/plain");
  3492. })
  3493. .Get("/compress-with-charset",
  3494. [&](const Request & /*req*/, Response &res) {
  3495. res.set_content(
  3496. "12345678901234567890123456789012345678901234567890123456789"
  3497. "01234567890123456789012345678901234567890",
  3498. "application/json; charset=utf-8");
  3499. })
  3500. .Get("/nocompress",
  3501. [&](const Request & /*req*/, Response &res) {
  3502. res.set_content(
  3503. "12345678901234567890123456789012345678901234567890123456789"
  3504. "01234567890123456789012345678901234567890",
  3505. "application/octet-stream");
  3506. })
  3507. .Post("/compress-multipart",
  3508. [&](const Request &req, Response & /*res*/) {
  3509. EXPECT_EQ(2u, req.form.fields.size());
  3510. ASSERT_TRUE(!req.form.has_field("???"));
  3511. {
  3512. const auto &text = req.form.get_field("key1");
  3513. EXPECT_EQ("test", text);
  3514. }
  3515. {
  3516. const auto &text = req.form.get_field("key2");
  3517. EXPECT_EQ("--abcdefg123", text);
  3518. }
  3519. })
  3520. #endif
  3521. ;
  3522. persons_["john"] = "programmer";
  3523. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3524. svr_.wait_until_ready();
  3525. }
  3526. virtual void TearDown() {
  3527. svr_.stop();
  3528. if (!request_threads_.empty()) {
  3529. std::this_thread::sleep_for(std::chrono::seconds(1));
  3530. for (auto &t : request_threads_) {
  3531. t.join();
  3532. }
  3533. }
  3534. t_.join();
  3535. }
  3536. map<string, string> persons_;
  3537. #ifdef CPPHTTPLIB_SSL_ENABLED
  3538. SSLClient cli_;
  3539. SSLServer svr_;
  3540. #else
  3541. Client cli_;
  3542. Server svr_;
  3543. #endif
  3544. thread t_;
  3545. std::vector<thread> request_threads_;
  3546. };
  3547. TEST_F(ServerTest, GetMethod200) {
  3548. auto res = cli_.Get("/hi");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ("HTTP/1.1", res->version);
  3551. EXPECT_EQ(StatusCode::OK_200, res->status);
  3552. EXPECT_EQ("OK", res->reason);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3555. EXPECT_EQ("Hello World!", res->body);
  3556. }
  3557. TEST_F(ServerTest, GetEmptyFile) {
  3558. auto res = cli_.Get("/empty_file");
  3559. ASSERT_TRUE(res);
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3562. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3563. EXPECT_EQ("", res->body);
  3564. }
  3565. TEST_F(ServerTest, GetFileContent) {
  3566. auto res = cli_.Get("/file_content");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::OK_200, res->status);
  3569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3570. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3571. EXPECT_EQ("test.html", res->body);
  3572. }
  3573. TEST_F(ServerTest, GetFileContentWithRange) {
  3574. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3578. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3579. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3580. EXPECT_EQ("est", res->body);
  3581. }
  3582. TEST_F(ServerTest, GetFileContentWithContentType) {
  3583. auto res = cli_.Get("/file_content_with_content_type");
  3584. ASSERT_TRUE(res);
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3587. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3588. EXPECT_EQ("file\n", res->body);
  3589. }
  3590. TEST_F(ServerTest, GetInvalidFileContent) {
  3591. auto res = cli_.Get("/invalid_file_content");
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3596. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3597. ASSERT_TRUE(res);
  3598. EXPECT_EQ("HTTP/1.1", res->version);
  3599. EXPECT_EQ(StatusCode::OK_200, res->status);
  3600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3601. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3602. EXPECT_EQ("Hello World!", res->body);
  3603. }
  3604. TEST_F(ServerTest, GetMethod302) {
  3605. auto res = cli_.Get("/");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(StatusCode::Found_302, res->status);
  3608. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3609. }
  3610. TEST_F(ServerTest, GetMethod302Redirect) {
  3611. cli_.set_follow_location(true);
  3612. auto res = cli_.Get("/");
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. EXPECT_EQ("Hello World!", res->body);
  3616. EXPECT_EQ("/hi", res->location);
  3617. }
  3618. TEST_F(ServerTest, GetMethod404) {
  3619. auto res = cli_.Get("/invalid");
  3620. ASSERT_TRUE(res);
  3621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3622. }
  3623. TEST_F(ServerTest, HeadMethod200) {
  3624. auto res = cli_.Head("/hi");
  3625. ASSERT_TRUE(res);
  3626. EXPECT_EQ(StatusCode::OK_200, res->status);
  3627. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3628. EXPECT_TRUE(res->body.empty());
  3629. }
  3630. TEST_F(ServerTest, HeadMethod200Static) {
  3631. auto res = cli_.Head("/mount/dir/index.html");
  3632. ASSERT_TRUE(res);
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3635. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3636. EXPECT_TRUE(res->body.empty());
  3637. }
  3638. TEST_F(ServerTest, HeadMethod404) {
  3639. auto res = cli_.Head("/invalid");
  3640. ASSERT_TRUE(res);
  3641. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3642. EXPECT_TRUE(res->body.empty());
  3643. }
  3644. TEST_F(ServerTest, GetMethodPersonJohn) {
  3645. auto res = cli_.Get("/person/john");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3649. EXPECT_EQ("programmer", res->body);
  3650. }
  3651. TEST_F(ServerTest, PostMethod1) {
  3652. auto res = cli_.Get("/person/john1");
  3653. ASSERT_TRUE(res);
  3654. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3655. res = cli_.Post("/person", "name=john1&note=coder",
  3656. "application/x-www-form-urlencoded");
  3657. ASSERT_TRUE(res);
  3658. ASSERT_EQ(StatusCode::OK_200, res->status);
  3659. res = cli_.Get("/person/john1");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3663. ASSERT_EQ("coder", res->body);
  3664. }
  3665. TEST_F(ServerTest, PostMethod2) {
  3666. auto res = cli_.Get("/person/john2");
  3667. ASSERT_TRUE(res);
  3668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3669. Params params;
  3670. params.emplace("name", "john2");
  3671. params.emplace("note", "coder");
  3672. res = cli_.Post("/person", params);
  3673. ASSERT_TRUE(res);
  3674. ASSERT_EQ(StatusCode::OK_200, res->status);
  3675. res = cli_.Get("/person/john2");
  3676. ASSERT_TRUE(res);
  3677. ASSERT_EQ(StatusCode::OK_200, res->status);
  3678. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3679. ASSERT_EQ("coder", res->body);
  3680. }
  3681. TEST_F(ServerTest, PutMethod3) {
  3682. auto res = cli_.Get("/person/john3");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3685. Params params;
  3686. params.emplace("name", "john3");
  3687. params.emplace("note", "coder");
  3688. res = cli_.Put("/person", params);
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. res = cli_.Get("/person/john3");
  3692. ASSERT_TRUE(res);
  3693. ASSERT_EQ(StatusCode::OK_200, res->status);
  3694. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3695. ASSERT_EQ("coder", res->body);
  3696. }
  3697. TEST_F(ServerTest, DeleteMethod1) {
  3698. auto res = cli_.Get("/person/john4");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3701. Params params;
  3702. params.emplace("name", "john4");
  3703. params.emplace("note", "coder");
  3704. res = cli_.Post("/person", params);
  3705. ASSERT_TRUE(res);
  3706. ASSERT_EQ(StatusCode::OK_200, res->status);
  3707. res = cli_.Get("/person/john4");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3711. ASSERT_EQ("coder", res->body);
  3712. Params delete_params;
  3713. delete_params.emplace("name", "john4");
  3714. res = cli_.Delete("/person", delete_params);
  3715. ASSERT_TRUE(res);
  3716. ASSERT_EQ(StatusCode::OK_200, res->status);
  3717. ASSERT_EQ("DELETED", res->body);
  3718. res = cli_.Get("/person/john4");
  3719. ASSERT_TRUE(res);
  3720. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3721. }
  3722. TEST_F(ServerTest, DeleteMethod2) {
  3723. auto res = cli_.Get("/person/john5");
  3724. ASSERT_TRUE(res);
  3725. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3726. Params params;
  3727. params.emplace("name", "john5");
  3728. params.emplace("note", "developer");
  3729. res = cli_.Post("/person", params);
  3730. ASSERT_TRUE(res);
  3731. ASSERT_EQ(StatusCode::OK_200, res->status);
  3732. res = cli_.Get("/person/john5");
  3733. ASSERT_TRUE(res);
  3734. ASSERT_EQ(StatusCode::OK_200, res->status);
  3735. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3736. ASSERT_EQ("developer", res->body);
  3737. Params delete_params;
  3738. delete_params.emplace("name", "john5");
  3739. Headers headers;
  3740. headers.emplace("Custom-Header", "test-value");
  3741. res = cli_.Delete("/person", headers, delete_params);
  3742. ASSERT_TRUE(res);
  3743. ASSERT_EQ(StatusCode::OK_200, res->status);
  3744. ASSERT_EQ("DELETED", res->body);
  3745. res = cli_.Get("/person/john5");
  3746. ASSERT_TRUE(res);
  3747. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3748. }
  3749. TEST_F(ServerTest, DeleteMethod3) {
  3750. auto res = cli_.Get("/person/john6");
  3751. ASSERT_TRUE(res);
  3752. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3753. Params params;
  3754. params.emplace("name", "john6");
  3755. params.emplace("note", "tester");
  3756. res = cli_.Post("/person", params);
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::OK_200, res->status);
  3759. res = cli_.Get("/person/john6");
  3760. ASSERT_TRUE(res);
  3761. ASSERT_EQ(StatusCode::OK_200, res->status);
  3762. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3763. ASSERT_EQ("tester", res->body);
  3764. Params delete_params;
  3765. delete_params.emplace("name", "john6");
  3766. Headers headers;
  3767. headers.emplace("Custom-Header", "test-value");
  3768. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3769. ASSERT_TRUE(res);
  3770. ASSERT_EQ(StatusCode::OK_200, res->status);
  3771. ASSERT_EQ("DELETED", res->body);
  3772. res = cli_.Get("/person/john6");
  3773. ASSERT_TRUE(res);
  3774. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3775. }
  3776. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3777. Params params;
  3778. params.emplace("json", JSON_DATA);
  3779. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3780. ASSERT_TRUE(res);
  3781. ASSERT_EQ(StatusCode::OK_200, res->status);
  3782. ASSERT_EQ(JSON_DATA, res->body);
  3783. }
  3784. TEST_F(ServerTest, PostEmptyContent) {
  3785. auto res = cli_.Post("/empty", "", "text/plain");
  3786. ASSERT_TRUE(res);
  3787. ASSERT_EQ(StatusCode::OK_200, res->status);
  3788. ASSERT_EQ("empty", res->body);
  3789. }
  3790. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3791. auto res = cli_.Post("/empty-no-content-type");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ("empty-no-content-type", res->body);
  3795. }
  3796. TEST_F(ServerTest, PostPathOnly) {
  3797. auto res = cli_.Post("/path-only");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::OK_200, res->status);
  3800. ASSERT_EQ("path-only", res->body);
  3801. }
  3802. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3803. auto res = cli_.Post("/path-headers-only",
  3804. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3805. ASSERT_TRUE(res);
  3806. ASSERT_EQ(StatusCode::OK_200, res->status);
  3807. ASSERT_EQ("path-headers-only", res->body);
  3808. }
  3809. TEST_F(ServerTest, PostLarge) {
  3810. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. EXPECT_EQ(LARGE_DATA, res->body);
  3814. }
  3815. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3816. auto res = cli_.Put("/empty-no-content-type");
  3817. ASSERT_TRUE(res);
  3818. ASSERT_EQ(StatusCode::OK_200, res->status);
  3819. ASSERT_EQ("empty-no-content-type", res->body);
  3820. }
  3821. TEST_F(ServerTest, GetMethodDir) {
  3822. auto res = cli_.Get("/dir/");
  3823. ASSERT_TRUE(res);
  3824. EXPECT_EQ(StatusCode::OK_200, res->status);
  3825. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3826. auto body = R"(<html>
  3827. <head>
  3828. </head>
  3829. <body>
  3830. <a href="/dir/test.html">Test</a>
  3831. <a href="/hi">hi</a>
  3832. </body>
  3833. </html>
  3834. )";
  3835. EXPECT_EQ(body, res->body);
  3836. }
  3837. TEST_F(ServerTest, GetMethodDirTest) {
  3838. auto res = cli_.Get("/dir/test.html");
  3839. ASSERT_TRUE(res);
  3840. EXPECT_EQ(StatusCode::OK_200, res->status);
  3841. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3842. EXPECT_EQ("test.html", res->body);
  3843. }
  3844. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3845. auto res = cli_.Get("/dir/../dir/test.html");
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::OK_200, res->status);
  3848. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3849. EXPECT_EQ("test.html", res->body);
  3850. }
  3851. TEST_F(ServerTest, GetMethodInvalidPath) {
  3852. auto res = cli_.Get("/dir/../test.html");
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3855. }
  3856. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3857. auto res = cli_.Get("/../www/dir/test.html");
  3858. ASSERT_TRUE(res);
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. }
  3861. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3862. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3865. }
  3866. TEST_F(ServerTest, GetMethodDirMountTest) {
  3867. auto res = cli_.Get("/mount/dir/test.html");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3871. EXPECT_EQ("test.html", res->body);
  3872. }
  3873. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3874. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(StatusCode::OK_200, res->status);
  3877. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3878. EXPECT_EQ("test.html", res->body);
  3879. }
  3880. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3881. auto res = cli_.Get("/mount/dir/../test.html");
  3882. ASSERT_TRUE(res);
  3883. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3884. }
  3885. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3886. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3889. }
  3890. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3891. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3892. ASSERT_TRUE(res);
  3893. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3894. }
  3895. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3896. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3899. }
  3900. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3901. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3904. }
  3905. TEST_F(ServerTest, PostMethod303) {
  3906. auto res = cli_.Post("/1", "body", "text/plain");
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3909. EXPECT_EQ("/2", res->get_header_value("Location"));
  3910. }
  3911. TEST_F(ServerTest, PostMethod303Redirect) {
  3912. cli_.set_follow_location(true);
  3913. auto res = cli_.Post("/1", "body", "text/plain");
  3914. ASSERT_TRUE(res);
  3915. EXPECT_EQ(StatusCode::OK_200, res->status);
  3916. EXPECT_EQ("redirected.", res->body);
  3917. EXPECT_EQ("/2", res->location);
  3918. }
  3919. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3920. auto res = cli_.Get("/dir/test.abcde");
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3924. EXPECT_EQ("abcde", res->body);
  3925. }
  3926. TEST_F(ServerTest, StaticFileRange) {
  3927. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3930. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3931. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(true, res->has_header("Content-Range"));
  3933. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3934. EXPECT_EQ(std::string("cd"), res->body);
  3935. }
  3936. TEST_F(ServerTest, StaticFileRanges) {
  3937. auto res =
  3938. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3941. EXPECT_TRUE(
  3942. res->get_header_value("Content-Type")
  3943. .find(
  3944. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3945. 0);
  3946. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3947. }
  3948. TEST_F(ServerTest, StaticFileRangeHead) {
  3949. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3952. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3953. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3954. EXPECT_EQ(true, res->has_header("Content-Range"));
  3955. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3956. }
  3957. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3958. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3962. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3963. EXPECT_EQ(true, res->has_header("Content-Range"));
  3964. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3965. res->get_header_value("Content-Range"));
  3966. EXPECT_EQ("LAST\n", res->body);
  3967. }
  3968. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3969. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3970. ASSERT_TRUE(res);
  3971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3973. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3974. EXPECT_EQ(true, res->has_header("Content-Range"));
  3975. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3976. }
  3977. TEST_F(ServerTest, StaticFileBigFile) {
  3978. auto res = cli_.Get("/dir/1MB.txt");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3982. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3983. }
  3984. TEST_F(ServerTest, InvalidBaseDirMount) {
  3985. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3986. }
  3987. TEST_F(ServerTest, Binary) {
  3988. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3989. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3990. "application/octet-stream");
  3991. ASSERT_TRUE(res);
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_EQ(4U, res->body.size());
  3994. res = cli_.Put("/binary", binary.data(), binary.size(),
  3995. "application/octet-stream");
  3996. ASSERT_TRUE(res);
  3997. ASSERT_EQ(StatusCode::OK_200, res->status);
  3998. ASSERT_EQ(4U, res->body.size());
  3999. res = cli_.Patch("/binary", binary.data(), binary.size(),
  4000. "application/octet-stream");
  4001. ASSERT_TRUE(res);
  4002. ASSERT_EQ(StatusCode::OK_200, res->status);
  4003. ASSERT_EQ(4U, res->body.size());
  4004. res = cli_.Delete("/binary", binary.data(), binary.size(),
  4005. "application/octet-stream");
  4006. ASSERT_TRUE(res);
  4007. ASSERT_EQ(StatusCode::OK_200, res->status);
  4008. ASSERT_EQ(4U, res->body.size());
  4009. }
  4010. TEST_F(ServerTest, BinaryString) {
  4011. auto binary = std::string("\x00\x01\x02\x03", 4);
  4012. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  4013. ASSERT_TRUE(res);
  4014. ASSERT_EQ(StatusCode::OK_200, res->status);
  4015. ASSERT_EQ(4U, res->body.size());
  4016. res = cli_.Put("/binary", binary, "application/octet-stream");
  4017. ASSERT_TRUE(res);
  4018. ASSERT_EQ(StatusCode::OK_200, res->status);
  4019. ASSERT_EQ(4U, res->body.size());
  4020. res = cli_.Patch("/binary", binary, "application/octet-stream");
  4021. ASSERT_TRUE(res);
  4022. ASSERT_EQ(StatusCode::OK_200, res->status);
  4023. ASSERT_EQ(4U, res->body.size());
  4024. res = cli_.Delete("/binary", binary, "application/octet-stream");
  4025. ASSERT_TRUE(res);
  4026. ASSERT_EQ(StatusCode::OK_200, res->status);
  4027. ASSERT_EQ(4U, res->body.size());
  4028. }
  4029. TEST_F(ServerTest, EmptyRequest) {
  4030. auto res = cli_.Get("");
  4031. ASSERT_TRUE(!res);
  4032. EXPECT_EQ(Error::Connection, res.error());
  4033. }
  4034. TEST_F(ServerTest, LongRequest) {
  4035. std::string request;
  4036. for (size_t i = 0; i < 545; i++) {
  4037. request += "/TooLongRequest";
  4038. }
  4039. request += "OK";
  4040. auto res = cli_.Get(request.c_str());
  4041. ASSERT_TRUE(res);
  4042. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4043. }
  4044. TEST_F(ServerTest, TooLongRequest) {
  4045. std::string request;
  4046. for (size_t i = 0; i < 546; i++) {
  4047. request += "/TooLongRequest";
  4048. }
  4049. request += "_NG";
  4050. auto start = std::chrono::high_resolution_clock::now();
  4051. cli_.set_keep_alive(true);
  4052. auto res = cli_.Get(request.c_str());
  4053. auto end = std::chrono::high_resolution_clock::now();
  4054. auto elapsed =
  4055. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4056. .count();
  4057. ASSERT_TRUE(res);
  4058. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4059. EXPECT_LE(elapsed, 1000);
  4060. EXPECT_EQ("close", res->get_header_value("Connection"));
  4061. EXPECT_FALSE(cli_.is_socket_open());
  4062. }
  4063. TEST_F(ServerTest, AlmostTooLongRequest) {
  4064. // test for #2046 - URI length check shouldn't include other content on req
  4065. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  4066. // leading /, space, HTTP/1.1)
  4067. std::string request =
  4068. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  4069. auto res = cli_.Get(request.c_str());
  4070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4072. }
  4073. TEST_F(ServerTest, LongHeader) {
  4074. Request req;
  4075. req.method = "GET";
  4076. req.path = "/hi";
  4077. std::string host_and_port;
  4078. host_and_port += HOST;
  4079. host_and_port += ":";
  4080. host_and_port += std::to_string(PORT);
  4081. req.headers.emplace("Host", host_and_port.c_str());
  4082. req.headers.emplace("Accept", "*/*");
  4083. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4084. req.headers.emplace(
  4085. "Header-Name",
  4086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4114. "@@@@@@@@@@@@@@@@");
  4115. auto res = std::make_shared<Response>();
  4116. auto error = Error::Success;
  4117. auto ret = cli_.send(req, *res, error);
  4118. ASSERT_TRUE(ret);
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. }
  4121. TEST_F(ServerTest, LongQueryValue) {
  4122. auto start = std::chrono::high_resolution_clock::now();
  4123. cli_.set_keep_alive(true);
  4124. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4125. auto end = std::chrono::high_resolution_clock::now();
  4126. auto elapsed =
  4127. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4128. .count();
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4131. EXPECT_LE(elapsed, 1000);
  4132. EXPECT_EQ("close", res->get_header_value("Connection"));
  4133. EXPECT_FALSE(cli_.is_socket_open());
  4134. }
  4135. TEST_F(ServerTest, TooLongQueryValue) {
  4136. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4137. ASSERT_FALSE(res);
  4138. EXPECT_EQ(Error::Read, res.error());
  4139. }
  4140. TEST_F(ServerTest, TooLongHeader) {
  4141. Request req;
  4142. req.method = "GET";
  4143. req.path = "/hi";
  4144. std::string host_and_port;
  4145. host_and_port += HOST;
  4146. host_and_port += ":";
  4147. host_and_port += std::to_string(PORT);
  4148. req.headers.emplace("Host", host_and_port.c_str());
  4149. req.headers.emplace("Accept", "*/*");
  4150. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4151. req.headers.emplace(
  4152. "Header-Name",
  4153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4181. "@@@@@@@@@@@@@@@@@");
  4182. auto res = std::make_shared<Response>();
  4183. auto error = Error::Success;
  4184. auto ret = cli_.send(req, *res, error);
  4185. ASSERT_TRUE(ret);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. }
  4188. TEST_F(ServerTest, HeaderCountAtLimit) {
  4189. // Test with headers just under the 100 limit
  4190. httplib::Headers headers;
  4191. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4192. // This should keep us just under the 100 header limit
  4193. for (int i = 0; i < 95; i++) {
  4194. std::string name = "X-Test-Header-" + std::to_string(i);
  4195. std::string value = "value" + std::to_string(i);
  4196. headers.emplace(name, value);
  4197. }
  4198. // This should work fine as we're under the limit
  4199. auto res = cli_.Get("/hi", headers);
  4200. EXPECT_TRUE(res);
  4201. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4202. }
  4203. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4204. // Test with many headers to exceed the 100 limit
  4205. httplib::Headers headers;
  4206. // Add 150 headers to definitely exceed the 100 limit
  4207. for (int i = 0; i < 150; i++) {
  4208. std::string name = "X-Test-Header-" + std::to_string(i);
  4209. std::string value = "value" + std::to_string(i);
  4210. headers.emplace(name, value);
  4211. }
  4212. // This should fail due to exceeding header count limit
  4213. cli_.set_keep_alive(true);
  4214. auto res = cli_.Get("/hi", headers);
  4215. // The server should respond with 400 Bad Request
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4218. EXPECT_EQ("close", res->get_header_value("Connection"));
  4219. EXPECT_FALSE(cli_.is_socket_open());
  4220. }
  4221. TEST_F(ServerTest, PercentEncoding) {
  4222. auto res = cli_.Get("/e%6edwith%");
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::OK_200, res->status);
  4225. }
  4226. TEST_F(ServerTest, PercentEncodingUnicode) {
  4227. auto res = cli_.Get("/e%u006edwith%");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST_F(ServerTest, InvalidPercentEncoding) {
  4232. auto res = cli_.Get("/%endwith%");
  4233. ASSERT_TRUE(res);
  4234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4235. }
  4236. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4237. auto res = cli_.Get("/%uendwith%");
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4240. }
  4241. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4242. auto res = cli_.Get("/hello?aaa=bbb%");
  4243. ASSERT_TRUE(res);
  4244. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4245. }
  4246. TEST_F(ServerTest, PlusSignEncoding) {
  4247. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. EXPECT_EQ("a +b", res->body);
  4251. }
  4252. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4253. // This test simulates a potential DoS attack using many headers
  4254. // to verify our security fix prevents memory exhaustion
  4255. httplib::Headers attack_headers;
  4256. // Attempt to add many headers like an attacker would (200 headers to far
  4257. // exceed limit)
  4258. for (int i = 0; i < 200; i++) {
  4259. std::string name = "X-Attack-Header-" + std::to_string(i);
  4260. std::string value = "attack_payload_" + std::to_string(i);
  4261. attack_headers.emplace(name, value);
  4262. }
  4263. // Try to POST with excessive headers
  4264. cli_.set_keep_alive(true);
  4265. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4266. // Should either fail or return 400 Bad Request due to security limit
  4267. if (res) {
  4268. // If we get a response, it should be 400 Bad Request
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ("close", res->get_header_value("Connection"));
  4271. }
  4272. EXPECT_FALSE(cli_.is_socket_open());
  4273. }
  4274. TEST_F(ServerTest, MultipartFormData) {
  4275. UploadFormDataItems items = {
  4276. {"text1", "text default", "", ""},
  4277. {"text2", "aωb", "", ""},
  4278. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4279. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4280. {"file3", "", "", "application/octet-stream"},
  4281. {"file4", "", "", " application/json tmp-string "}};
  4282. auto res = cli_.Post("/multipart", items);
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. }
  4286. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4287. UploadFormDataItems items = {
  4288. {"text", "default text", "", ""},
  4289. {"multi_text1", "aaaaa", "", ""},
  4290. {"multi_text1", "bbbbb", "", ""},
  4291. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4292. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4293. "application/json"},
  4294. };
  4295. auto res = cli_.Post("/multipart/multi_file_values", items);
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. }
  4299. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4300. auto res = cli_.Get("/hi");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4304. EXPECT_EQ("Hello World!", res->body);
  4305. }
  4306. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4307. Request req;
  4308. req.method = "POST";
  4309. req.path = "/chunked";
  4310. std::string host_and_port;
  4311. host_and_port += HOST;
  4312. host_and_port += ":";
  4313. host_and_port += std::to_string(PORT);
  4314. req.headers.emplace("Host", host_and_port.c_str());
  4315. req.headers.emplace("Accept", "*/*");
  4316. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4317. req.headers.emplace("Content-Type", "text/plain");
  4318. req.headers.emplace("Content-Length", "0");
  4319. req.headers.emplace(
  4320. "Transfer-Encoding",
  4321. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4322. // Client does not chunk, so make a chunked body manually.
  4323. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4324. auto res = std::make_shared<Response>();
  4325. auto error = Error::Success;
  4326. auto ret = cli_.send(req, *res, error);
  4327. ASSERT_TRUE(ret);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. }
  4330. TEST_F(ServerTest, GetStreamed2) {
  4331. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4334. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4335. EXPECT_EQ(true, res->has_header("Content-Range"));
  4336. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4337. EXPECT_EQ(std::string("ab"), res->body);
  4338. }
  4339. TEST_F(ServerTest, GetStreamed) {
  4340. auto res = cli_.Get("/streamed");
  4341. ASSERT_TRUE(res);
  4342. EXPECT_EQ(StatusCode::OK_200, res->status);
  4343. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4344. EXPECT_EQ(std::string("aaabbb"), res->body);
  4345. }
  4346. TEST_F(ServerTest, GetStreamedWithRange1) {
  4347. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4350. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4351. EXPECT_EQ(true, res->has_header("Content-Range"));
  4352. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4353. EXPECT_EQ(std::string("def"), res->body);
  4354. }
  4355. TEST_F(ServerTest, GetStreamedWithRange2) {
  4356. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4357. ASSERT_TRUE(res);
  4358. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4359. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4360. EXPECT_EQ(true, res->has_header("Content-Range"));
  4361. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4362. EXPECT_EQ(std::string("bcdefg"), res->body);
  4363. }
  4364. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4365. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4368. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4369. EXPECT_EQ(true, res->has_header("Content-Range"));
  4370. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4371. EXPECT_EQ(std::string("efg"), res->body);
  4372. }
  4373. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4374. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4377. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4378. EXPECT_EQ(false, res->has_header("Content-Range"));
  4379. EXPECT_EQ(0U, res->body.size());
  4380. }
  4381. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4382. auto res = cli_.Get("/streamed-with-range",
  4383. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4384. "92233720368547758079223372036854775807"}});
  4385. ASSERT_TRUE(res);
  4386. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4387. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4388. EXPECT_EQ(false, res->has_header("Content-Range"));
  4389. EXPECT_EQ(0U, res->body.size());
  4390. }
  4391. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4392. auto res = cli_.Get(
  4393. "/with-range",
  4394. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4395. {"Accept-Encoding", ""}});
  4396. ASSERT_TRUE(res);
  4397. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4398. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4399. EXPECT_EQ(true, res->has_header("Content-Range"));
  4400. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4401. EXPECT_EQ(std::string("abcdefg"), res->body);
  4402. }
  4403. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4404. auto res = cli_.Get("/with-range", {
  4405. {"Range", "bytes=0-"},
  4406. {"Accept-Encoding", ""},
  4407. });
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4410. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4411. EXPECT_EQ(true, res->has_header("Content-Range"));
  4412. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4413. EXPECT_EQ(std::string("abcdefg"), res->body);
  4414. }
  4415. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4416. auto res =
  4417. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4418. ASSERT_TRUE(res);
  4419. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4420. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4421. EXPECT_EQ(false, res->has_header("Content-Range"));
  4422. EXPECT_EQ(267U, res->body.size());
  4423. // Check that both range contents are present
  4424. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4425. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4426. // Check that Content-Range headers are present for both ranges
  4427. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4428. std::string::npos);
  4429. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4430. std::string::npos);
  4431. }
  4432. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4433. Ranges ranges;
  4434. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4435. ranges.emplace_back(0, -1);
  4436. }
  4437. auto res =
  4438. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4439. ASSERT_TRUE(res);
  4440. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4441. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4442. EXPECT_EQ(false, res->has_header("Content-Range"));
  4443. EXPECT_EQ(0U, res->body.size());
  4444. }
  4445. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4446. auto res =
  4447. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4448. ASSERT_TRUE(res);
  4449. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4450. EXPECT_EQ(5U, res->body.size());
  4451. // Check that overlapping ranges are coalesced into a single range
  4452. EXPECT_EQ("bcdef", res->body);
  4453. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4454. // Should be single range, not multipart
  4455. EXPECT_TRUE(res->has_header("Content-Range"));
  4456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4457. }
  4458. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4459. auto res =
  4460. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4463. EXPECT_EQ(268U, res->body.size());
  4464. // Check that both range contents are present
  4465. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4466. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4467. // Check that Content-Range headers are present for both ranges
  4468. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4469. std::string::npos);
  4470. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4471. std::string::npos);
  4472. }
  4473. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4474. auto res =
  4475. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4476. ASSERT_TRUE(res);
  4477. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4478. EXPECT_EQ(269U, res->body.size());
  4479. // Check that both duplicate range contents are present
  4480. size_t first_abc = res->body.find("abc\r\n");
  4481. EXPECT_TRUE(first_abc != std::string::npos);
  4482. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4483. EXPECT_TRUE(second_abc != std::string::npos);
  4484. // Check that Content-Range headers are present for both ranges
  4485. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4486. EXPECT_TRUE(first_range != std::string::npos);
  4487. size_t second_range =
  4488. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4489. EXPECT_TRUE(second_range != std::string::npos);
  4490. }
  4491. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4492. auto res = cli_.Get("/streamed-with-range?error",
  4493. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4494. ASSERT_TRUE(res);
  4495. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4496. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4497. EXPECT_EQ(false, res->has_header("Content-Range"));
  4498. EXPECT_EQ(0U, res->body.size());
  4499. }
  4500. TEST_F(ServerTest, GetStreamedEndless) {
  4501. uint64_t offset = 0;
  4502. auto res = cli_.Get("/streamed-cancel",
  4503. [&](const char * /*data*/, uint64_t data_length) {
  4504. if (offset < 100) {
  4505. offset += data_length;
  4506. return true;
  4507. }
  4508. return false;
  4509. });
  4510. ASSERT_TRUE(!res);
  4511. EXPECT_EQ(Error::Canceled, res.error());
  4512. }
  4513. TEST_F(ServerTest, ClientStop) {
  4514. std::atomic_size_t count{4};
  4515. std::vector<std::thread> threads;
  4516. for (auto i = count.load(); i != 0; --i) {
  4517. threads.emplace_back([&]() {
  4518. auto res = cli_.Get("/streamed-cancel",
  4519. [&](const char *, uint64_t) { return true; });
  4520. --count;
  4521. ASSERT_TRUE(!res);
  4522. EXPECT_TRUE(res.error() == Error::Canceled ||
  4523. res.error() == Error::Read || res.error() == Error::Write);
  4524. });
  4525. }
  4526. std::this_thread::sleep_for(std::chrono::seconds(2));
  4527. while (count != 0) {
  4528. cli_.stop();
  4529. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4530. }
  4531. for (auto &t : threads) {
  4532. t.join();
  4533. }
  4534. }
  4535. TEST_F(ServerTest, GetWithRange1) {
  4536. auto res = cli_.Get("/with-range", {
  4537. make_range_header({{3, 5}}),
  4538. {"Accept-Encoding", ""},
  4539. });
  4540. ASSERT_TRUE(res);
  4541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4542. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4543. EXPECT_EQ(true, res->has_header("Content-Range"));
  4544. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4545. EXPECT_EQ(std::string("def"), res->body);
  4546. }
  4547. TEST_F(ServerTest, GetWithRange2) {
  4548. auto res = cli_.Get("/with-range", {
  4549. make_range_header({{1, -1}}),
  4550. {"Accept-Encoding", ""},
  4551. });
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4554. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4555. EXPECT_EQ(true, res->has_header("Content-Range"));
  4556. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4557. EXPECT_EQ(std::string("bcdefg"), res->body);
  4558. }
  4559. TEST_F(ServerTest, GetWithRange3) {
  4560. auto res = cli_.Get("/with-range", {
  4561. make_range_header({{0, 0}}),
  4562. {"Accept-Encoding", ""},
  4563. });
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4566. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4567. EXPECT_EQ(true, res->has_header("Content-Range"));
  4568. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4569. EXPECT_EQ(std::string("a"), res->body);
  4570. }
  4571. TEST_F(ServerTest, GetWithRange4) {
  4572. auto res = cli_.Get("/with-range", {
  4573. make_range_header({{-1, 2}}),
  4574. {"Accept-Encoding", ""},
  4575. });
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4578. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4579. EXPECT_EQ(true, res->has_header("Content-Range"));
  4580. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4581. EXPECT_EQ(std::string("fg"), res->body);
  4582. }
  4583. TEST_F(ServerTest, GetWithRange5) {
  4584. auto res = cli_.Get("/with-range", {
  4585. make_range_header({{0, 5}}),
  4586. {"Accept-Encoding", ""},
  4587. });
  4588. ASSERT_TRUE(res);
  4589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4590. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4591. EXPECT_EQ(true, res->has_header("Content-Range"));
  4592. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4593. EXPECT_EQ(std::string("abcdef"), res->body);
  4594. }
  4595. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4596. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4597. ASSERT_TRUE(res);
  4598. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4599. }
  4600. TEST_F(ServerTest, GetWithRangeMultipart) {
  4601. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4602. ASSERT_TRUE(res);
  4603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4604. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4605. EXPECT_EQ(false, res->has_header("Content-Range"));
  4606. EXPECT_EQ(267U, res->body.size());
  4607. }
  4608. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4609. auto res =
  4610. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4611. ASSERT_TRUE(res);
  4612. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4613. }
  4614. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4615. auto res = cli_.Get("/with-range-customized-response",
  4616. {{make_range_header({{1, 2}})}});
  4617. ASSERT_TRUE(res);
  4618. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4619. EXPECT_EQ(true, res->has_header("Content-Length"));
  4620. EXPECT_EQ(false, res->has_header("Content-Range"));
  4621. EXPECT_EQ(JSON_DATA, res->body);
  4622. }
  4623. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4624. auto res = cli_.Get("/with-range-customized-response",
  4625. {{make_range_header({{1, 2}, {4, 5}})}});
  4626. ASSERT_TRUE(res);
  4627. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4628. EXPECT_EQ(true, res->has_header("Content-Length"));
  4629. EXPECT_EQ(false, res->has_header("Content-Range"));
  4630. EXPECT_EQ(JSON_DATA, res->body);
  4631. }
  4632. TEST_F(ServerTest, Issue1772) {
  4633. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4636. }
  4637. TEST_F(ServerTest, Issue609) {
  4638. auto res = cli_.Delete("/issue609");
  4639. ASSERT_TRUE(res);
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ(std::string("ok"), res->body);
  4642. }
  4643. TEST_F(ServerTest, GetStreamedChunked) {
  4644. auto res = cli_.Get("/streamed-chunked");
  4645. ASSERT_TRUE(res);
  4646. EXPECT_EQ(StatusCode::OK_200, res->status);
  4647. EXPECT_EQ(std::string("123456789"), res->body);
  4648. }
  4649. TEST_F(ServerTest, GetStreamedChunked2) {
  4650. auto res = cli_.Get("/streamed-chunked2");
  4651. ASSERT_TRUE(res);
  4652. EXPECT_EQ(StatusCode::OK_200, res->status);
  4653. EXPECT_EQ(std::string("123456789"), res->body);
  4654. }
  4655. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4656. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4657. ASSERT_TRUE(res);
  4658. EXPECT_EQ(StatusCode::OK_200, res->status);
  4659. EXPECT_EQ(std::string("123456789"), res->body);
  4660. EXPECT_TRUE(res->has_header("Trailer"));
  4661. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4662. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4663. // Trailers are now stored separately from headers (security fix)
  4664. EXPECT_EQ(2U, res->trailers.size());
  4665. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4666. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4667. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4668. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4669. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4670. // Verify trailers are NOT in headers (security verification)
  4671. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4672. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4673. }
  4674. TEST_F(ServerTest, LargeChunkedPost) {
  4675. Request req;
  4676. req.method = "POST";
  4677. req.path = "/large-chunked";
  4678. std::string host_and_port;
  4679. host_and_port += HOST;
  4680. host_and_port += ":";
  4681. host_and_port += std::to_string(PORT);
  4682. req.headers.emplace("Host", host_and_port.c_str());
  4683. req.headers.emplace("Accept", "*/*");
  4684. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4685. req.headers.emplace("Content-Type", "text/plain");
  4686. req.headers.emplace("Content-Length", "0");
  4687. req.headers.emplace("Transfer-Encoding", "chunked");
  4688. std::string long_string(30 * 1024u, 'a');
  4689. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4690. // Attempt to make a large enough post to exceed OS buffers, to test that
  4691. // the server handles short reads if the full chunk data isn't available.
  4692. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4693. auto res = std::make_shared<Response>();
  4694. auto error = Error::Success;
  4695. auto ret = cli_.send(req, *res, error);
  4696. ASSERT_TRUE(ret);
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. }
  4699. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4700. auto res = cli_.Get("/remote_addr");
  4701. ASSERT_TRUE(res);
  4702. EXPECT_EQ(StatusCode::OK_200, res->status);
  4703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4704. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4705. }
  4706. TEST_F(ServerTest, GetMethodLocalAddr) {
  4707. auto res = cli_.Get("/local_addr");
  4708. ASSERT_TRUE(res);
  4709. EXPECT_EQ(StatusCode::OK_200, res->status);
  4710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4711. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4712. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4713. }
  4714. TEST_F(ServerTest, HTTPResponseSplitting) {
  4715. auto res = cli_.Get("/http_response_splitting");
  4716. ASSERT_TRUE(res);
  4717. EXPECT_EQ(StatusCode::OK_200, res->status);
  4718. }
  4719. TEST_F(ServerTest, SlowRequest) {
  4720. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4721. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4722. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4723. }
  4724. #if 0
  4725. TEST_F(ServerTest, SlowPost) {
  4726. char buffer[64 * 1024];
  4727. memset(buffer, 0x42, sizeof(buffer));
  4728. auto res = cli_.Post(
  4729. "/slowpost", 64 * 1024 * 1024,
  4730. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4731. auto ret = sink.write(buffer, sizeof(buffer));
  4732. EXPECT_TRUE(ret);
  4733. return true;
  4734. },
  4735. "text/plain");
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::OK_200, res->status);
  4738. }
  4739. TEST_F(ServerTest, SlowPostFail) {
  4740. char buffer[64 * 1024];
  4741. memset(buffer, 0x42, sizeof(buffer));
  4742. cli_.set_write_timeout(std::chrono::seconds(0));
  4743. auto res = cli_.Post(
  4744. "/slowpost", 64 * 1024 * 1024,
  4745. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4746. sink.write(buffer, sizeof(buffer));
  4747. return true;
  4748. },
  4749. "text/plain");
  4750. ASSERT_TRUE(!res);
  4751. EXPECT_EQ(Error::Write, res.error());
  4752. }
  4753. #endif
  4754. TEST_F(ServerTest, Put) {
  4755. auto res = cli_.Put("/put", "PUT", "text/plain");
  4756. ASSERT_TRUE(res);
  4757. EXPECT_EQ(StatusCode::OK_200, res->status);
  4758. EXPECT_EQ("PUT", res->body);
  4759. }
  4760. TEST_F(ServerTest, PutWithContentProvider) {
  4761. auto res = cli_.Put(
  4762. "/put", 3,
  4763. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4764. sink.os << "PUT";
  4765. return true;
  4766. },
  4767. "text/plain");
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ(StatusCode::OK_200, res->status);
  4770. EXPECT_EQ("PUT", res->body);
  4771. }
  4772. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4773. auto res = cli_.Post(
  4774. "/post", 42,
  4775. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4776. return false;
  4777. },
  4778. "text/plain");
  4779. ASSERT_TRUE(!res);
  4780. EXPECT_EQ(Error::Canceled, res.error());
  4781. }
  4782. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4783. auto res = cli_.Put(
  4784. "/put",
  4785. [](size_t /*offset*/, DataSink &sink) {
  4786. sink.os << "PUT";
  4787. sink.done();
  4788. return true;
  4789. },
  4790. "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ("PUT", res->body);
  4794. }
  4795. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4796. auto res = cli_.Post(
  4797. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4798. "text/plain");
  4799. ASSERT_TRUE(!res);
  4800. EXPECT_EQ(Error::Canceled, res.error());
  4801. }
  4802. TEST_F(ServerTest, PostLoopBack) {
  4803. std::string body;
  4804. auto res = cli_.Post(
  4805. "/post-loopback", 9,
  4806. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4807. EXPECT_EQ(9u, length);
  4808. sink.write("123", 3);
  4809. sink.write("456", 3);
  4810. sink.write("789", 3);
  4811. return true;
  4812. },
  4813. "text/plain",
  4814. [&body](const char *data, size_t data_length) {
  4815. body.append(data, data_length);
  4816. return true;
  4817. });
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. EXPECT_EQ("123456789", body);
  4821. }
  4822. TEST_F(ServerTest, PutLoopBack) {
  4823. std::string body;
  4824. auto res = cli_.Put(
  4825. "/put-loopback", 9,
  4826. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4827. EXPECT_EQ(9u, length);
  4828. sink.write("123", 3);
  4829. sink.write("456", 3);
  4830. sink.write("789", 3);
  4831. return true;
  4832. },
  4833. "text/plain",
  4834. [&body](const char *data, size_t data_length) {
  4835. body.append(data, data_length);
  4836. return true;
  4837. });
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. EXPECT_EQ("123456789", body);
  4841. }
  4842. TEST_F(ServerTest, PatchLoopBack) {
  4843. std::string body;
  4844. auto res = cli_.Patch(
  4845. "/patch-loopback", 9,
  4846. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4847. EXPECT_EQ(9u, length);
  4848. sink.write("123", 3);
  4849. sink.write("456", 3);
  4850. sink.write("789", 3);
  4851. return true;
  4852. },
  4853. "text/plain",
  4854. [&body](const char *data, size_t data_length) {
  4855. body.append(data, data_length);
  4856. return true;
  4857. });
  4858. ASSERT_TRUE(res);
  4859. EXPECT_EQ(StatusCode::OK_200, res->status);
  4860. EXPECT_EQ("123456789", body);
  4861. }
  4862. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4863. std::string body;
  4864. auto res = cli_.Post(
  4865. "/post-loopback",
  4866. [](size_t /*offset*/, DataSink &sink) {
  4867. sink.write("123", 3);
  4868. sink.write("456", 3);
  4869. sink.write("789", 3);
  4870. sink.done();
  4871. return true;
  4872. },
  4873. "text/plain",
  4874. [&body](const char *data, size_t data_length) {
  4875. body.append(data, data_length);
  4876. return true;
  4877. });
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::OK_200, res->status);
  4880. EXPECT_EQ("123456789", body);
  4881. }
  4882. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4883. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4884. cli_.set_compress(true);
  4885. auto res = cli_.Put(
  4886. "/put", 3,
  4887. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4888. sink.os << "PUT";
  4889. return true;
  4890. },
  4891. "text/plain");
  4892. ASSERT_TRUE(res);
  4893. EXPECT_EQ(StatusCode::OK_200, res->status);
  4894. EXPECT_EQ("PUT", res->body);
  4895. }
  4896. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4897. cli_.set_compress(true);
  4898. auto res = cli_.Post(
  4899. "/post", 42,
  4900. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4901. return false;
  4902. },
  4903. "text/plain");
  4904. ASSERT_TRUE(!res);
  4905. EXPECT_EQ(Error::Canceled, res.error());
  4906. }
  4907. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4908. cli_.set_compress(true);
  4909. auto res = cli_.Put(
  4910. "/put",
  4911. [](size_t /*offset*/, DataSink &sink) {
  4912. sink.os << "PUT";
  4913. sink.done();
  4914. return true;
  4915. },
  4916. "text/plain");
  4917. ASSERT_TRUE(res);
  4918. EXPECT_EQ(StatusCode::OK_200, res->status);
  4919. EXPECT_EQ("PUT", res->body);
  4920. }
  4921. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4922. cli_.set_compress(true);
  4923. auto res = cli_.Post(
  4924. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4925. "text/plain");
  4926. ASSERT_TRUE(!res);
  4927. EXPECT_EQ(Error::Canceled, res.error());
  4928. }
  4929. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4930. cli_.set_compress(true);
  4931. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4932. ASSERT_TRUE(res);
  4933. EXPECT_EQ(StatusCode::OK_200, res->status);
  4934. EXPECT_EQ(LARGE_DATA, res->body);
  4935. }
  4936. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4937. #ifdef CPPHTTPLIB_SSL_ENABLED
  4938. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4939. Client cli(s.c_str());
  4940. cli.enable_server_certificate_verification(false);
  4941. #else
  4942. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4943. Client cli(s.c_str());
  4944. #endif
  4945. cli.set_compress(true);
  4946. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4947. ASSERT_TRUE(res);
  4948. EXPECT_EQ(StatusCode::OK_200, res->status);
  4949. EXPECT_EQ(LARGE_DATA, res->body);
  4950. // The compressed size should be less than a 10th of the original. May vary
  4951. // depending on the zlib library.
  4952. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4953. static_cast<uint64_t>(10 * 1024 * 1024));
  4954. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4955. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4956. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4957. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4958. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4959. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4960. #endif
  4961. }
  4962. TEST_F(ServerTest, PutContentWithDeflate) {
  4963. cli_.set_compress(false);
  4964. Headers headers;
  4965. headers.emplace("Content-Encoding", "deflate");
  4966. // PUT in deflate format:
  4967. auto res = cli_.Put("/put", headers,
  4968. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4969. ASSERT_TRUE(res);
  4970. EXPECT_EQ(StatusCode::OK_200, res->status);
  4971. EXPECT_EQ("PUT", res->body);
  4972. }
  4973. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4974. Headers headers;
  4975. headers.emplace("Accept-Encoding", "gzip, deflate");
  4976. auto res = cli_.Get("/streamed-chunked", headers);
  4977. ASSERT_TRUE(res);
  4978. EXPECT_EQ(StatusCode::OK_200, res->status);
  4979. EXPECT_EQ(std::string("123456789"), res->body);
  4980. }
  4981. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4982. Headers headers;
  4983. headers.emplace("Accept-Encoding", "gzip, deflate");
  4984. auto res = cli_.Get("/streamed-chunked2", headers);
  4985. ASSERT_TRUE(res);
  4986. EXPECT_EQ(StatusCode::OK_200, res->status);
  4987. EXPECT_EQ(std::string("123456789"), res->body);
  4988. }
  4989. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4990. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4991. ASSERT_TRUE(res);
  4992. EXPECT_EQ(StatusCode::OK_200, res->status);
  4993. }
  4994. TEST(GzipDecompressor, ChunkedDecompression) {
  4995. std::string data;
  4996. for (size_t i = 0; i < 32 * 1024; ++i) {
  4997. data.push_back(static_cast<char>('a' + i % 26));
  4998. }
  4999. std::string compressed_data;
  5000. {
  5001. httplib::detail::gzip_compressor compressor;
  5002. bool result = compressor.compress(
  5003. data.data(), data.size(),
  5004. /*last=*/true,
  5005. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5006. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5007. compressed_data_size);
  5008. return true;
  5009. });
  5010. ASSERT_TRUE(result);
  5011. }
  5012. std::string decompressed_data;
  5013. {
  5014. httplib::detail::gzip_decompressor decompressor;
  5015. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5016. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5017. size_t chunk_size = 130;
  5018. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5019. chunk_begin += chunk_size) {
  5020. size_t current_chunk_size =
  5021. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5022. bool result = decompressor.decompress(
  5023. compressed_data.data() + chunk_begin, current_chunk_size,
  5024. [&](const char *decompressed_data_chunk,
  5025. size_t decompressed_data_chunk_size) {
  5026. decompressed_data.insert(decompressed_data.size(),
  5027. decompressed_data_chunk,
  5028. decompressed_data_chunk_size);
  5029. return true;
  5030. });
  5031. ASSERT_TRUE(result);
  5032. }
  5033. }
  5034. ASSERT_EQ(data, decompressed_data);
  5035. }
  5036. TEST(GzipDecompressor, DeflateDecompression) {
  5037. std::string original_text = "Raw deflate without gzip";
  5038. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5039. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5040. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5041. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  5042. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5043. std::string decompressed_data;
  5044. {
  5045. httplib::detail::gzip_decompressor decompressor;
  5046. bool result = decompressor.decompress(
  5047. compressed_data.data(), compressed_data.size(),
  5048. [&](const char *decompressed_data_chunk,
  5049. size_t decompressed_data_chunk_size) {
  5050. decompressed_data.insert(decompressed_data.size(),
  5051. decompressed_data_chunk,
  5052. decompressed_data_chunk_size);
  5053. return true;
  5054. });
  5055. ASSERT_TRUE(result);
  5056. }
  5057. ASSERT_EQ(original_text, decompressed_data);
  5058. }
  5059. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  5060. std::string original_text = "Raw deflate without gzip";
  5061. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  5062. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  5063. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  5064. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  5065. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  5066. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5067. std::string decompressed_data;
  5068. {
  5069. httplib::detail::gzip_decompressor decompressor;
  5070. bool result = decompressor.decompress(
  5071. compressed_data.data(), compressed_data.size(),
  5072. [&](const char *decompressed_data_chunk,
  5073. size_t decompressed_data_chunk_size) {
  5074. decompressed_data.insert(decompressed_data.size(),
  5075. decompressed_data_chunk,
  5076. decompressed_data_chunk_size);
  5077. return true;
  5078. });
  5079. ASSERT_TRUE(result);
  5080. }
  5081. ASSERT_EQ(original_text, decompressed_data);
  5082. }
  5083. #endif
  5084. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5085. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  5086. Headers headers;
  5087. headers.emplace("Accept-Encoding", "br");
  5088. auto res = cli_.Get("/streamed-chunked", headers);
  5089. ASSERT_TRUE(res);
  5090. EXPECT_EQ(StatusCode::OK_200, res->status);
  5091. EXPECT_EQ(std::string("123456789"), res->body);
  5092. }
  5093. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  5094. Headers headers;
  5095. headers.emplace("Accept-Encoding", "br");
  5096. auto res = cli_.Get("/streamed-chunked2", headers);
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. EXPECT_EQ(std::string("123456789"), res->body);
  5100. }
  5101. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  5102. cli_.set_compress(true);
  5103. auto res = cli_.Put(
  5104. "/put", 3,
  5105. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5106. sink.os << "PUT";
  5107. return true;
  5108. },
  5109. "text/plain");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("PUT", res->body);
  5113. }
  5114. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  5115. cli_.set_compress(true);
  5116. auto res = cli_.Put(
  5117. "/put",
  5118. [](size_t /*offset*/, DataSink &sink) {
  5119. sink.os << "PUT";
  5120. sink.done();
  5121. return true;
  5122. },
  5123. "text/plain");
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ("PUT", res->body);
  5127. }
  5128. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5129. cli_.set_compress(true);
  5130. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5131. ASSERT_TRUE(res);
  5132. EXPECT_EQ(StatusCode::OK_200, res->status);
  5133. EXPECT_EQ(LARGE_DATA, res->body);
  5134. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5135. }
  5136. #endif
  5137. TEST_F(ServerTest, Patch) {
  5138. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5139. ASSERT_TRUE(res);
  5140. EXPECT_EQ(StatusCode::OK_200, res->status);
  5141. EXPECT_EQ("PATCH", res->body);
  5142. }
  5143. TEST_F(ServerTest, Delete) {
  5144. auto res = cli_.Delete("/delete");
  5145. ASSERT_TRUE(res);
  5146. EXPECT_EQ(StatusCode::OK_200, res->status);
  5147. EXPECT_EQ("DELETE", res->body);
  5148. }
  5149. TEST_F(ServerTest, DeleteContentReceiver) {
  5150. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("content", res->body);
  5154. }
  5155. TEST_F(ServerTest, Options) {
  5156. auto res = cli_.Options("*");
  5157. ASSERT_TRUE(res);
  5158. EXPECT_EQ(StatusCode::OK_200, res->status);
  5159. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5160. EXPECT_TRUE(res->body.empty());
  5161. }
  5162. TEST_F(ServerTest, URL) {
  5163. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5164. ASSERT_TRUE(res);
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. }
  5167. TEST_F(ServerTest, ArrayParam) {
  5168. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ(StatusCode::OK_200, res->status);
  5171. }
  5172. TEST_F(ServerTest, ArrayParamValues) {
  5173. auto res =
  5174. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5175. ASSERT_TRUE(res);
  5176. EXPECT_EQ(StatusCode::OK_200, res->status);
  5177. }
  5178. TEST_F(ServerTest, NoMultipleHeaders) {
  5179. Headers headers = {{"Content-Length", "5"}};
  5180. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5181. "text/plain");
  5182. ASSERT_TRUE(res);
  5183. EXPECT_EQ(StatusCode::OK_200, res->status);
  5184. }
  5185. TEST_F(ServerTest, PostContentReceiver) {
  5186. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5187. ASSERT_TRUE(res);
  5188. ASSERT_EQ(StatusCode::OK_200, res->status);
  5189. ASSERT_EQ("content", res->body);
  5190. }
  5191. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5192. UploadFormDataItems items = {
  5193. {"text1", "text default", "", ""},
  5194. {"text2", "aωb", "", ""},
  5195. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5196. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5197. {"file3", "", "", "application/octet-stream"},
  5198. };
  5199. auto res = cli_.Post("/content_receiver", items);
  5200. ASSERT_TRUE(res);
  5201. EXPECT_EQ(StatusCode::OK_200, res->status);
  5202. }
  5203. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5204. UploadFormDataItems items = {
  5205. {"text1", "text default", "", ""},
  5206. {"text2", "aωb", "", ""},
  5207. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5208. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5209. {"file3", "", "", "application/octet-stream"},
  5210. };
  5211. auto boundary = std::string("+++++");
  5212. std::string body;
  5213. for (const auto &item : items) {
  5214. body += "--" + boundary + "\r\n";
  5215. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5216. if (!item.filename.empty()) {
  5217. body += "; filename=\"" + item.filename + "\"";
  5218. }
  5219. body += "\r\n";
  5220. if (!item.content_type.empty()) {
  5221. body += "Content-Type: " + item.content_type + "\r\n";
  5222. }
  5223. body += "\r\n";
  5224. body += item.content + "\r\n";
  5225. }
  5226. body += "--" + boundary + "--\r\n";
  5227. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5228. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5229. ASSERT_TRUE(res);
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. }
  5232. TEST_F(ServerTest, PostContentReceiverGzip) {
  5233. cli_.set_compress(true);
  5234. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5235. ASSERT_TRUE(res);
  5236. ASSERT_EQ(StatusCode::OK_200, res->status);
  5237. ASSERT_EQ("content", res->body);
  5238. }
  5239. TEST_F(ServerTest, PutContentReceiver) {
  5240. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5241. ASSERT_TRUE(res);
  5242. ASSERT_EQ(StatusCode::OK_200, res->status);
  5243. ASSERT_EQ("content", res->body);
  5244. }
  5245. TEST_F(ServerTest, PatchContentReceiver) {
  5246. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5247. ASSERT_TRUE(res);
  5248. ASSERT_EQ(StatusCode::OK_200, res->status);
  5249. ASSERT_EQ("content", res->body);
  5250. }
  5251. template <typename ClientType>
  5252. void TestWithHeadersAndContentReceiver(
  5253. ClientType &cli,
  5254. std::function<Result(ClientType &, const std::string &, const Headers &,
  5255. const std::string &, const std::string &,
  5256. ContentReceiver, DownloadProgress)>
  5257. request_func) {
  5258. Headers headers;
  5259. headers.emplace("X-Custom-Header", "test-value");
  5260. std::string received_body;
  5261. auto res = request_func(
  5262. cli, "/content_receiver", headers, "content", "application/json",
  5263. [&](const char *data, size_t data_length) {
  5264. received_body.append(data, data_length);
  5265. return true;
  5266. },
  5267. nullptr);
  5268. ASSERT_TRUE(res);
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. EXPECT_EQ("content", received_body);
  5271. }
  5272. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5273. #ifdef CPPHTTPLIB_SSL_ENABLED
  5274. using ClientT = SSLClient;
  5275. #else
  5276. using ClientT = Client;
  5277. #endif
  5278. TestWithHeadersAndContentReceiver<ClientT>(
  5279. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5280. const std::string &body, const std::string &content_type,
  5281. ContentReceiver receiver, DownloadProgress progress) {
  5282. return cli.Post(path, headers, body, content_type, receiver, progress);
  5283. });
  5284. }
  5285. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5286. #ifdef CPPHTTPLIB_SSL_ENABLED
  5287. using ClientT = SSLClient;
  5288. #else
  5289. using ClientT = Client;
  5290. #endif
  5291. TestWithHeadersAndContentReceiver<ClientT>(
  5292. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5293. const std::string &body, const std::string &content_type,
  5294. ContentReceiver receiver, DownloadProgress progress) {
  5295. return cli.Put(path, headers, body, content_type, receiver, progress);
  5296. });
  5297. }
  5298. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5299. #ifdef CPPHTTPLIB_SSL_ENABLED
  5300. using ClientT = SSLClient;
  5301. #else
  5302. using ClientT = Client;
  5303. #endif
  5304. TestWithHeadersAndContentReceiver<ClientT>(
  5305. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5306. const std::string &body, const std::string &content_type,
  5307. ContentReceiver receiver, DownloadProgress progress) {
  5308. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5309. });
  5310. }
  5311. template <typename ClientType>
  5312. void TestWithHeadersAndContentReceiverWithProgress(
  5313. ClientType &cli,
  5314. std::function<Result(ClientType &, const std::string &, const Headers &,
  5315. const std::string &, const std::string &,
  5316. ContentReceiver, DownloadProgress)>
  5317. request_func) {
  5318. Headers headers;
  5319. headers.emplace("X-Test-Header", "progress-test");
  5320. std::string received_body;
  5321. auto progress_called = false;
  5322. auto res = request_func(
  5323. cli, "/content_receiver", headers, "content", "text/plain",
  5324. [&](const char *data, size_t data_length) {
  5325. received_body.append(data, data_length);
  5326. return true;
  5327. },
  5328. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5329. progress_called = true;
  5330. return true;
  5331. });
  5332. ASSERT_TRUE(res);
  5333. EXPECT_EQ(StatusCode::OK_200, res->status);
  5334. EXPECT_EQ("content", received_body);
  5335. EXPECT_TRUE(progress_called);
  5336. }
  5337. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5338. #ifdef CPPHTTPLIB_SSL_ENABLED
  5339. using ClientT = SSLClient;
  5340. #else
  5341. using ClientT = Client;
  5342. #endif
  5343. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5344. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5345. const std::string &body, const std::string &content_type,
  5346. ContentReceiver receiver, DownloadProgress progress) {
  5347. return cli.Post(path, headers, body, content_type, receiver, progress);
  5348. });
  5349. }
  5350. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5351. #ifdef CPPHTTPLIB_SSL_ENABLED
  5352. using ClientT = SSLClient;
  5353. #else
  5354. using ClientT = Client;
  5355. #endif
  5356. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5357. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5358. const std::string &body, const std::string &content_type,
  5359. ContentReceiver receiver, DownloadProgress progress) {
  5360. return cli.Put(path, headers, body, content_type, receiver, progress);
  5361. });
  5362. }
  5363. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5364. #ifdef CPPHTTPLIB_SSL_ENABLED
  5365. using ClientT = SSLClient;
  5366. #else
  5367. using ClientT = Client;
  5368. #endif
  5369. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5370. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5371. const std::string &body, const std::string &content_type,
  5372. ContentReceiver receiver, DownloadProgress progress) {
  5373. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5374. });
  5375. }
  5376. template <typename ClientType>
  5377. void TestWithHeadersAndContentReceiverError(
  5378. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5379. const Headers &, const std::string &,
  5380. const std::string &, ContentReceiver)>
  5381. request_func) {
  5382. Headers headers;
  5383. headers.emplace("X-Error-Test", "true");
  5384. std::string received_body;
  5385. auto receiver_failed = false;
  5386. auto res =
  5387. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5388. [&](const char *data, size_t data_length) {
  5389. received_body.append(data, data_length);
  5390. receiver_failed = true;
  5391. return false;
  5392. });
  5393. ASSERT_FALSE(res);
  5394. EXPECT_TRUE(receiver_failed);
  5395. }
  5396. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5397. #ifdef CPPHTTPLIB_SSL_ENABLED
  5398. using ClientT = SSLClient;
  5399. #else
  5400. using ClientT = Client;
  5401. #endif
  5402. TestWithHeadersAndContentReceiverError<ClientT>(
  5403. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5404. const std::string &body, const std::string &content_type,
  5405. ContentReceiver receiver) {
  5406. return cli.Post(path, headers, body, content_type, receiver);
  5407. });
  5408. }
  5409. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5410. #ifdef CPPHTTPLIB_SSL_ENABLED
  5411. using ClientT = SSLClient;
  5412. #else
  5413. using ClientT = Client;
  5414. #endif
  5415. TestWithHeadersAndContentReceiverError<ClientT>(
  5416. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5417. const std::string &body, const std::string &content_type,
  5418. ContentReceiver receiver) {
  5419. return cli.Put(path, headers, body, content_type, receiver);
  5420. });
  5421. }
  5422. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5423. #ifdef CPPHTTPLIB_SSL_ENABLED
  5424. using ClientT = SSLClient;
  5425. #else
  5426. using ClientT = Client;
  5427. #endif
  5428. TestWithHeadersAndContentReceiverError<ClientT>(
  5429. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5430. const std::string &body, const std::string &content_type,
  5431. ContentReceiver receiver) {
  5432. return cli.Patch(path, headers, body, content_type, receiver);
  5433. });
  5434. }
  5435. TEST_F(ServerTest, PostQueryStringAndBody) {
  5436. auto res =
  5437. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5438. ASSERT_TRUE(res);
  5439. ASSERT_EQ(StatusCode::OK_200, res->status);
  5440. }
  5441. TEST_F(ServerTest, HTTP2Magic) {
  5442. Request req;
  5443. req.method = "PRI";
  5444. req.path = "*";
  5445. req.body = "SM";
  5446. auto res = std::make_shared<Response>();
  5447. auto error = Error::Success;
  5448. auto ret = cli_.send(req, *res, error);
  5449. ASSERT_TRUE(ret);
  5450. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5451. }
  5452. TEST_F(ServerTest, KeepAlive) {
  5453. auto res = cli_.Get("/hi");
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ(StatusCode::OK_200, res->status);
  5456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5457. EXPECT_EQ("Hello World!", res->body);
  5458. res = cli_.Get("/hi");
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(StatusCode::OK_200, res->status);
  5461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5462. EXPECT_EQ("Hello World!", res->body);
  5463. res = cli_.Get("/hi");
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5467. EXPECT_EQ("Hello World!", res->body);
  5468. res = cli_.Get("/not-exist");
  5469. ASSERT_TRUE(res);
  5470. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5471. res = cli_.Post("/empty", "", "text/plain");
  5472. ASSERT_TRUE(res);
  5473. EXPECT_EQ(StatusCode::OK_200, res->status);
  5474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5475. EXPECT_EQ("empty", res->body);
  5476. EXPECT_EQ("close", res->get_header_value("Connection"));
  5477. res = cli_.Post(
  5478. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5479. "text/plain");
  5480. ASSERT_TRUE(res);
  5481. EXPECT_EQ(StatusCode::OK_200, res->status);
  5482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5483. EXPECT_EQ("empty", res->body);
  5484. cli_.set_keep_alive(false);
  5485. res = cli_.Get("/last-request");
  5486. ASSERT_TRUE(res);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ("close", res->get_header_value("Connection"));
  5489. }
  5490. TEST_F(ServerTest, TooManyRedirect) {
  5491. cli_.set_follow_location(true);
  5492. auto res = cli_.Get("/redirect/0");
  5493. ASSERT_TRUE(!res);
  5494. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5495. }
  5496. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5497. Request req;
  5498. req.method = "FOOBAR";
  5499. req.path = "/hi";
  5500. cli_.set_keep_alive(true);
  5501. auto res = cli_.send(req);
  5502. ASSERT_TRUE(res);
  5503. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5504. EXPECT_EQ("close", res->get_header_value("Connection"));
  5505. EXPECT_FALSE(cli_.is_socket_open());
  5506. }
  5507. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5508. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5509. TEST_F(ServerTest, Gzip) {
  5510. Headers headers;
  5511. headers.emplace("Accept-Encoding", "gzip, deflate");
  5512. auto res = cli_.Get("/compress", headers);
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5515. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5516. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5517. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5518. "7890123456789012345678901234567890",
  5519. res->body);
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. }
  5522. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5523. Headers headers;
  5524. headers.emplace("Accept-Encoding", "gzip, deflate");
  5525. auto res = cli_.Get("/compress-with-charset", headers);
  5526. ASSERT_TRUE(res);
  5527. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5528. EXPECT_EQ("application/json; charset=utf-8",
  5529. res->get_header_value("Content-Type"));
  5530. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5531. "7890123456789012345678901234567890",
  5532. res->body);
  5533. EXPECT_EQ(StatusCode::OK_200, res->status);
  5534. }
  5535. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5536. Headers headers;
  5537. headers.emplace("Accept-Encoding", "");
  5538. auto res = cli_.Get("/compress", headers);
  5539. ASSERT_TRUE(res);
  5540. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5542. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5543. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5544. "7890123456789012345678901234567890",
  5545. res->body);
  5546. EXPECT_EQ(StatusCode::OK_200, res->status);
  5547. }
  5548. TEST_F(ServerTest, GzipWithContentReceiver) {
  5549. Headers headers;
  5550. headers.emplace("Accept-Encoding", "gzip, deflate");
  5551. std::string body;
  5552. auto res = cli_.Get("/compress", headers,
  5553. [&](const char *data, uint64_t data_length) {
  5554. EXPECT_EQ(100U, data_length);
  5555. body.append(data, data_length);
  5556. return true;
  5557. });
  5558. ASSERT_TRUE(res);
  5559. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5561. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5562. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5563. "7890123456789012345678901234567890",
  5564. body);
  5565. EXPECT_EQ(StatusCode::OK_200, res->status);
  5566. }
  5567. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5568. Headers headers;
  5569. headers.emplace("Accept-Encoding", "gzip, deflate");
  5570. cli_.set_decompress(false);
  5571. auto res = cli_.Get("/compress", headers);
  5572. ASSERT_TRUE(res);
  5573. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5575. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5576. EXPECT_EQ(33U, res->body.size());
  5577. EXPECT_EQ(StatusCode::OK_200, res->status);
  5578. }
  5579. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5580. Headers headers;
  5581. headers.emplace("Accept-Encoding", "");
  5582. std::string body;
  5583. auto res = cli_.Get("/compress", headers,
  5584. [&](const char *data, uint64_t data_length) {
  5585. EXPECT_EQ(100U, data_length);
  5586. body.append(data, data_length);
  5587. return true;
  5588. });
  5589. ASSERT_TRUE(res);
  5590. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5592. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5593. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5594. "7890123456789012345678901234567890",
  5595. body);
  5596. EXPECT_EQ(StatusCode::OK_200, res->status);
  5597. }
  5598. TEST_F(ServerTest, NoGzip) {
  5599. Headers headers;
  5600. headers.emplace("Accept-Encoding", "gzip, deflate");
  5601. auto res = cli_.Get("/nocompress", headers);
  5602. ASSERT_TRUE(res);
  5603. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5604. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5605. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5606. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5607. "7890123456789012345678901234567890",
  5608. res->body);
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. }
  5611. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5612. Headers headers;
  5613. headers.emplace("Accept-Encoding", "gzip, deflate");
  5614. std::string body;
  5615. auto res = cli_.Get("/nocompress", headers,
  5616. [&](const char *data, uint64_t data_length) {
  5617. EXPECT_EQ(100U, data_length);
  5618. body.append(data, data_length);
  5619. return true;
  5620. });
  5621. ASSERT_TRUE(res);
  5622. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5623. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5625. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5626. "7890123456789012345678901234567890",
  5627. body);
  5628. EXPECT_EQ(StatusCode::OK_200, res->status);
  5629. }
  5630. TEST_F(ServerTest, MultipartFormDataGzip) {
  5631. UploadFormDataItems items = {
  5632. {"key1", "test", "", ""},
  5633. {"key2", "--abcdefg123", "", ""},
  5634. };
  5635. cli_.set_compress(true);
  5636. auto res = cli_.Post("/compress-multipart", items);
  5637. ASSERT_TRUE(res);
  5638. EXPECT_EQ(StatusCode::OK_200, res->status);
  5639. }
  5640. #endif
  5641. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5642. TEST_F(ServerTest, Brotli) {
  5643. Headers headers;
  5644. headers.emplace("Accept-Encoding", "br");
  5645. auto res = cli_.Get("/compress", headers);
  5646. ASSERT_TRUE(res);
  5647. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5649. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5650. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5651. "7890123456789012345678901234567890",
  5652. res->body);
  5653. EXPECT_EQ(StatusCode::OK_200, res->status);
  5654. }
  5655. #endif
  5656. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5657. TEST_F(ServerTest, Zstd) {
  5658. Headers headers;
  5659. headers.emplace("Accept-Encoding", "zstd");
  5660. auto res = cli_.Get("/compress", headers);
  5661. ASSERT_TRUE(res);
  5662. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5663. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5664. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5665. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5666. "7890123456789012345678901234567890",
  5667. res->body);
  5668. EXPECT_EQ(StatusCode::OK_200, res->status);
  5669. }
  5670. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5671. Headers headers;
  5672. headers.emplace("Accept-Encoding", "");
  5673. auto res = cli_.Get("/compress", headers);
  5674. ASSERT_TRUE(res);
  5675. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5676. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5677. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5678. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5679. "7890123456789012345678901234567890",
  5680. res->body);
  5681. EXPECT_EQ(StatusCode::OK_200, res->status);
  5682. }
  5683. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5684. Headers headers;
  5685. headers.emplace("Accept-Encoding", "zstd");
  5686. std::string body;
  5687. auto res = cli_.Get("/compress", headers,
  5688. [&](const char *data, uint64_t data_length) {
  5689. EXPECT_EQ(100U, data_length);
  5690. body.append(data, data_length);
  5691. return true;
  5692. });
  5693. ASSERT_TRUE(res);
  5694. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5695. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5696. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5697. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5698. "7890123456789012345678901234567890",
  5699. body);
  5700. EXPECT_EQ(StatusCode::OK_200, res->status);
  5701. }
  5702. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5703. Headers headers;
  5704. headers.emplace("Accept-Encoding", "zstd");
  5705. cli_.set_decompress(false);
  5706. auto res = cli_.Get("/compress", headers);
  5707. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5708. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5709. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5710. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5711. ASSERT_TRUE(res);
  5712. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5714. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5715. EXPECT_EQ(StatusCode::OK_200, res->status);
  5716. ASSERT_EQ(26U, res->body.size());
  5717. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5718. 0);
  5719. }
  5720. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5721. Headers headers;
  5722. headers.emplace("Accept-Encoding", "");
  5723. std::string body;
  5724. auto res = cli_.Get("/compress", headers,
  5725. [&](const char *data, uint64_t data_length) {
  5726. EXPECT_EQ(100U, data_length);
  5727. body.append(data, data_length);
  5728. return true;
  5729. });
  5730. ASSERT_TRUE(res);
  5731. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5733. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5734. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5735. "7890123456789012345678901234567890",
  5736. body);
  5737. EXPECT_EQ(StatusCode::OK_200, res->status);
  5738. }
  5739. TEST_F(ServerTest, NoZstd) {
  5740. Headers headers;
  5741. headers.emplace("Accept-Encoding", "zstd");
  5742. auto res = cli_.Get("/nocompress", headers);
  5743. ASSERT_TRUE(res);
  5744. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5745. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5746. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5747. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5748. "7890123456789012345678901234567890",
  5749. res->body);
  5750. EXPECT_EQ(StatusCode::OK_200, res->status);
  5751. }
  5752. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5753. Headers headers;
  5754. headers.emplace("Accept-Encoding", "zstd");
  5755. std::string body;
  5756. auto res = cli_.Get("/nocompress", headers,
  5757. [&](const char *data, uint64_t data_length) {
  5758. EXPECT_EQ(100U, data_length);
  5759. body.append(data, data_length);
  5760. return true;
  5761. });
  5762. ASSERT_TRUE(res);
  5763. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5764. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5765. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5766. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5767. "7890123456789012345678901234567890",
  5768. body);
  5769. EXPECT_EQ(StatusCode::OK_200, res->status);
  5770. }
  5771. // TODO: How to enable zstd ??
  5772. TEST_F(ServerTest, MultipartFormDataZstd) {
  5773. UploadFormDataItems items = {
  5774. {"key1", "test", "", ""},
  5775. {"key2", "--abcdefg123", "", ""},
  5776. };
  5777. Headers headers;
  5778. headers.emplace("Accept-Encoding", "zstd");
  5779. cli_.set_compress(true);
  5780. auto res = cli_.Post("/compress-multipart", headers, items);
  5781. ASSERT_TRUE(res);
  5782. EXPECT_EQ(StatusCode::OK_200, res->status);
  5783. }
  5784. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5785. Headers headers;
  5786. headers.emplace("Accept-Encoding", "zstd");
  5787. cli_.set_compress(true);
  5788. auto res = cli_.Put(
  5789. "/put", headers, 3,
  5790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5791. sink.os << "PUT";
  5792. return true;
  5793. },
  5794. "text/plain");
  5795. ASSERT_TRUE(res);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. EXPECT_EQ("PUT", res->body);
  5798. }
  5799. // Pre-compression logging tests
  5800. TEST_F(ServerTest, PreCompressionLogging) {
  5801. // Test data for compression (matches the actual /compress endpoint content)
  5802. const std::string test_content =
  5803. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5804. "3456789012345678901234567890";
  5805. // Variables to capture logging data
  5806. std::string pre_compression_body;
  5807. std::string pre_compression_content_type;
  5808. std::string pre_compression_content_encoding;
  5809. std::string post_compression_body;
  5810. std::string post_compression_content_type;
  5811. std::string post_compression_content_encoding;
  5812. // Set up pre-compression logger
  5813. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5814. const Response &res) {
  5815. pre_compression_body = res.body;
  5816. pre_compression_content_type = res.get_header_value("Content-Type");
  5817. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5818. });
  5819. // Set up post-compression logger
  5820. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5821. post_compression_body = res.body;
  5822. post_compression_content_type = res.get_header_value("Content-Type");
  5823. post_compression_content_encoding =
  5824. res.get_header_value("Content-Encoding");
  5825. });
  5826. // Test with gzip compression
  5827. Headers headers;
  5828. headers.emplace("Accept-Encoding", "gzip");
  5829. auto res = cli_.Get("/compress", headers);
  5830. // Verify response was compressed
  5831. ASSERT_TRUE(res);
  5832. EXPECT_EQ(StatusCode::OK_200, res->status);
  5833. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5834. // Verify pre-compression logger captured uncompressed content
  5835. EXPECT_EQ(test_content, pre_compression_body);
  5836. EXPECT_EQ("text/plain", pre_compression_content_type);
  5837. EXPECT_TRUE(pre_compression_content_encoding
  5838. .empty()); // No encoding header before compression
  5839. // Verify post-compression logger captured compressed content
  5840. EXPECT_NE(test_content,
  5841. post_compression_body); // Should be different after compression
  5842. EXPECT_EQ("text/plain", post_compression_content_type);
  5843. EXPECT_EQ("gzip", post_compression_content_encoding);
  5844. // Verify compressed content is smaller
  5845. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5846. }
  5847. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5848. const std::string test_content =
  5849. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5850. "3456789012345678901234567890";
  5851. std::string pre_compression_body;
  5852. std::string post_compression_body;
  5853. svr_.set_pre_compression_logger(
  5854. [&](const Request & /*req*/, const Response &res) {
  5855. pre_compression_body = res.body;
  5856. });
  5857. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5858. post_compression_body = res.body;
  5859. });
  5860. Headers headers;
  5861. headers.emplace("Accept-Encoding", "br");
  5862. auto res = cli_.Get("/compress", headers);
  5863. ASSERT_TRUE(res);
  5864. EXPECT_EQ(StatusCode::OK_200, res->status);
  5865. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5866. // Verify pre-compression content is uncompressed
  5867. EXPECT_EQ(test_content, pre_compression_body);
  5868. // Verify post-compression content is compressed
  5869. EXPECT_NE(test_content, post_compression_body);
  5870. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5871. }
  5872. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5873. const std::string test_content =
  5874. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5875. "3456789012345678901234567890";
  5876. std::string pre_compression_body;
  5877. std::string post_compression_body;
  5878. svr_.set_pre_compression_logger(
  5879. [&](const Request & /*req*/, const Response &res) {
  5880. pre_compression_body = res.body;
  5881. });
  5882. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5883. post_compression_body = res.body;
  5884. });
  5885. // Request without compression (use /nocompress endpoint)
  5886. Headers headers;
  5887. auto res = cli_.Get("/nocompress", headers);
  5888. ASSERT_TRUE(res);
  5889. EXPECT_EQ(StatusCode::OK_200, res->status);
  5890. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5891. // Pre-compression logger should not be called when no compression is applied
  5892. EXPECT_TRUE(
  5893. pre_compression_body.empty()); // Pre-compression logger not called
  5894. EXPECT_EQ(
  5895. test_content,
  5896. post_compression_body); // Post-compression logger captures final content
  5897. }
  5898. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5899. const std::string test_content =
  5900. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5901. "3456789012345678901234567890";
  5902. std::string pre_compression_body;
  5903. bool pre_logger_called = false;
  5904. // Set only pre-compression logger
  5905. svr_.set_pre_compression_logger(
  5906. [&](const Request & /*req*/, const Response &res) {
  5907. pre_compression_body = res.body;
  5908. pre_logger_called = true;
  5909. });
  5910. Headers headers;
  5911. headers.emplace("Accept-Encoding", "gzip");
  5912. auto res = cli_.Get("/compress", headers);
  5913. ASSERT_TRUE(res);
  5914. EXPECT_EQ(StatusCode::OK_200, res->status);
  5915. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5916. // Verify pre-compression logger was called
  5917. EXPECT_TRUE(pre_logger_called);
  5918. EXPECT_EQ(test_content, pre_compression_body);
  5919. }
  5920. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5921. {
  5922. // Test with Expect: 100-continue header - success case
  5923. // Server returns 100 Continue, client sends body, server returns 200 OK
  5924. Request req;
  5925. req.method = "POST";
  5926. req.path = "/post-large";
  5927. req.set_header("Expect", "100-continue");
  5928. req.body = LARGE_DATA;
  5929. Response res;
  5930. auto error = Error::Success;
  5931. cli_.set_keep_alive(true);
  5932. auto ret = cli_.send(req, res, error);
  5933. EXPECT_TRUE(ret);
  5934. EXPECT_EQ(StatusCode::OK_200, res.status);
  5935. EXPECT_EQ(LARGE_DATA, res.body);
  5936. }
  5937. {
  5938. // Test with Expect: 100-continue header - error case
  5939. // Client should not send the body when server returns an error
  5940. Request req;
  5941. req.method = "POST";
  5942. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5943. req.set_header("Expect", "100-continue");
  5944. req.body = LARGE_DATA;
  5945. Response res;
  5946. auto error = Error::Success;
  5947. auto start = std::chrono::high_resolution_clock::now();
  5948. cli_.set_keep_alive(true);
  5949. auto ret = cli_.send(req, res, error);
  5950. auto end = std::chrono::high_resolution_clock::now();
  5951. auto elapsed =
  5952. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5953. .count();
  5954. // With Expect: 100-continue, request completes successfully but with error
  5955. EXPECT_TRUE(ret);
  5956. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5957. EXPECT_EQ("close", res.get_header_value("Connection"));
  5958. EXPECT_FALSE(cli_.is_socket_open());
  5959. EXPECT_LE(elapsed, 2000);
  5960. }
  5961. {
  5962. // Send an extra GET request to ensure error recovery without hanging
  5963. Request req;
  5964. req.method = "GET";
  5965. req.path = "/hi";
  5966. auto start = std::chrono::high_resolution_clock::now();
  5967. auto res = cli_.send(req);
  5968. auto end = std::chrono::high_resolution_clock::now();
  5969. auto elapsed =
  5970. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5971. .count();
  5972. ASSERT_TRUE(res);
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. EXPECT_EQ("Hello World!", res->body);
  5975. EXPECT_LE(elapsed, 500);
  5976. }
  5977. }
  5978. TEST(ZstdDecompressor, ChunkedDecompression) {
  5979. std::string data;
  5980. for (size_t i = 0; i < 32 * 1024; ++i) {
  5981. data.push_back(static_cast<char>('a' + i % 26));
  5982. }
  5983. std::string compressed_data;
  5984. {
  5985. httplib::detail::zstd_compressor compressor;
  5986. bool result = compressor.compress(
  5987. data.data(), data.size(),
  5988. /*last=*/true,
  5989. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5990. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5991. compressed_data_size);
  5992. return true;
  5993. });
  5994. ASSERT_TRUE(result);
  5995. }
  5996. std::string decompressed_data;
  5997. {
  5998. httplib::detail::zstd_decompressor decompressor;
  5999. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6000. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6001. size_t chunk_size = 130;
  6002. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6003. chunk_begin += chunk_size) {
  6004. size_t current_chunk_size =
  6005. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6006. bool result = decompressor.decompress(
  6007. compressed_data.data() + chunk_begin, current_chunk_size,
  6008. [&](const char *decompressed_data_chunk,
  6009. size_t decompressed_data_chunk_size) {
  6010. decompressed_data.insert(decompressed_data.size(),
  6011. decompressed_data_chunk,
  6012. decompressed_data_chunk_size);
  6013. return true;
  6014. });
  6015. ASSERT_TRUE(result);
  6016. }
  6017. }
  6018. ASSERT_EQ(data, decompressed_data);
  6019. }
  6020. TEST(ZstdDecompressor, Decompress) {
  6021. std::string original_text = "Compressed with ZSTD";
  6022. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  6023. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  6024. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  6025. 0x20, 0x5a, 0x53, 0x54, 0x44};
  6026. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6027. std::string decompressed_data;
  6028. {
  6029. httplib::detail::zstd_decompressor decompressor;
  6030. bool result = decompressor.decompress(
  6031. compressed_data.data(), compressed_data.size(),
  6032. [&](const char *decompressed_data_chunk,
  6033. size_t decompressed_data_chunk_size) {
  6034. decompressed_data.insert(decompressed_data.size(),
  6035. decompressed_data_chunk,
  6036. decompressed_data_chunk_size);
  6037. return true;
  6038. });
  6039. ASSERT_TRUE(result);
  6040. }
  6041. ASSERT_EQ(original_text, decompressed_data);
  6042. }
  6043. #endif
  6044. // Sends a raw request to a server listening at HOST:PORT.
  6045. static bool send_request(time_t read_timeout_sec, const std::string &req,
  6046. std::string *resp = nullptr) {
  6047. auto error = Error::Success;
  6048. auto client_sock = detail::create_client_socket(
  6049. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  6050. /*connection_timeout_sec=*/5, 0,
  6051. /*read_timeout_sec=*/5, 0,
  6052. /*write_timeout_sec=*/5, 0, std::string(), error);
  6053. if (client_sock == INVALID_SOCKET) { return false; }
  6054. auto ret = detail::process_client_socket(
  6055. client_sock, read_timeout_sec, 0, 0, 0, 0,
  6056. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  6057. if (req.size() !=
  6058. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  6059. return false;
  6060. }
  6061. char buf[512];
  6062. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  6063. while (line_reader.getline()) {
  6064. if (resp) { *resp += line_reader.ptr(); }
  6065. }
  6066. return true;
  6067. });
  6068. detail::close_socket(client_sock);
  6069. return ret;
  6070. }
  6071. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  6072. Server svr;
  6073. std::string header_value;
  6074. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  6075. header_value = req.get_header_value("foo");
  6076. res.set_content("ok", "text/plain");
  6077. });
  6078. thread t = thread([&] { svr.listen(HOST, PORT); });
  6079. auto se = detail::scope_exit([&] {
  6080. svr.stop();
  6081. t.join();
  6082. ASSERT_FALSE(svr.is_running());
  6083. });
  6084. svr.wait_until_ready();
  6085. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  6086. // like characters are not treated the same - use vertical tab and escape.
  6087. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  6088. "foo: \t \v bar \x1B\t \r\n"
  6089. "Connection: close\r\n"
  6090. "\r\n";
  6091. std::string res;
  6092. ASSERT_TRUE(send_request(5, req, &res));
  6093. EXPECT_EQ(header_value, "");
  6094. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  6095. }
  6096. // Sends a raw request and verifies that there isn't a crash or exception.
  6097. static void test_raw_request(const std::string &req,
  6098. std::string *out = nullptr) {
  6099. Server svr;
  6100. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6101. res.set_content("ok", "text/plain");
  6102. });
  6103. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  6104. res.set_content("ok", "text/plain");
  6105. });
  6106. svr.Get("/header_field_value_check",
  6107. [&](const Request & /*req*/, Response &res) {
  6108. res.set_content("ok", "text/plain");
  6109. });
  6110. // Server read timeout must be longer than the client read timeout for the
  6111. // bug to reproduce, probably to force the server to process a request
  6112. // without a trailing blank line.
  6113. const time_t client_read_timeout_sec = 1;
  6114. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  6115. bool listen_thread_ok = false;
  6116. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  6117. auto se = detail::scope_exit([&] {
  6118. svr.stop();
  6119. t.join();
  6120. ASSERT_FALSE(svr.is_running());
  6121. EXPECT_TRUE(listen_thread_ok);
  6122. });
  6123. svr.wait_until_ready();
  6124. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6125. }
  6126. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6127. // A certain header line causes an exception if the header property is parsed
  6128. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6129. test_raw_request(
  6130. "GET /hi HTTP/1.1\r\n"
  6131. " : "
  6132. " "
  6133. " ");
  6134. }
  6135. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6136. // A certain header line causes an exception if the header property *name* is
  6137. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6138. // greedy matcher and requires backtracking when there are a lot of ":"
  6139. // characters.
  6140. // This occurs with libc++ but not libstdc++.
  6141. test_raw_request(
  6142. "GET /hi HTTP/1.1\r\n"
  6143. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6144. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6145. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6146. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6147. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6148. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6149. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6150. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6151. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6152. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6153. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6154. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6155. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6156. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6157. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6158. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6159. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6160. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6161. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6162. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6163. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6164. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6165. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6166. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6167. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6168. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6169. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6170. "&&&%%%");
  6171. }
  6172. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6173. // Make sure this doesn't crash the server.
  6174. // In a previous version of the header line regex, the "\r" rendered the line
  6175. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6176. // a new position where the leading white space ended and the field value
  6177. // began.
  6178. // The crash occurs with libc++ but not libstdc++.
  6179. test_raw_request("GET /hi HTTP/1.1\r\n"
  6180. "a:" +
  6181. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6182. "\r\n"
  6183. "\r\n");
  6184. }
  6185. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6186. std::string out;
  6187. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6188. "Content-Type: text/plain\r\n"
  6189. "Transfer-Encoding: chunked\r\n"
  6190. "\r\n"
  6191. "nothex\r\n",
  6192. &out);
  6193. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6194. }
  6195. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6196. std::string out;
  6197. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6198. "Content-Type: text/plain\r\n"
  6199. "Transfer-Encoding: chunked\r\n"
  6200. "\r\n"
  6201. "3\r\n"
  6202. "xyz\r\n"
  6203. "NaN\r\n",
  6204. &out);
  6205. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6206. }
  6207. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6208. std::string out;
  6209. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6210. "Content-Type: text/plain\r\n"
  6211. "Transfer-Encoding: chunked\r\n"
  6212. "\r\n"
  6213. // Length is too large for 64 bits.
  6214. "1ffffffffffffffff\r\n"
  6215. "xyz\r\n",
  6216. &out);
  6217. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6218. }
  6219. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6220. test_raw_request("GET /hi HTTP/1.1\r\n"
  6221. "Content-Type: text/plain\r\n\r");
  6222. }
  6223. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6224. std::string out;
  6225. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6226. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6227. }
  6228. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6229. Server svr;
  6230. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6231. EXPECT_TRUE(!req.remote_addr.empty());
  6232. });
  6233. thread t = thread([&] { svr.listen(HOST, PORT); });
  6234. auto se = detail::scope_exit([&] {
  6235. svr.stop();
  6236. t.join();
  6237. ASSERT_FALSE(svr.is_running());
  6238. });
  6239. svr.wait_until_ready();
  6240. // Send an invalid request line to trigger Bad Request
  6241. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6242. std::string out;
  6243. ASSERT_TRUE(send_request(5, bad_req, &out));
  6244. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6245. }
  6246. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6247. std::string out;
  6248. std::string request(
  6249. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6250. test_raw_request(request, &out);
  6251. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6252. }
  6253. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6254. std::string out;
  6255. std::string request(
  6256. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6257. test_raw_request(request, &out);
  6258. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6259. }
  6260. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6261. std::string out;
  6262. std::string request(
  6263. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6264. test_raw_request(request, &out);
  6265. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6266. }
  6267. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6268. std::string out;
  6269. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6270. "Test: \r\n\r\n",
  6271. &out);
  6272. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6273. }
  6274. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6275. Server svr;
  6276. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6277. res.set_header("Cache-Control", "no-cache");
  6278. res.set_chunked_content_provider(
  6279. "text/event-stream", [](size_t offset, DataSink &sink) {
  6280. std::string s = "data:";
  6281. s += std::to_string(offset);
  6282. s += "\n\n";
  6283. auto ret = sink.write(s.data(), s.size());
  6284. EXPECT_TRUE(ret);
  6285. std::this_thread::sleep_for(std::chrono::seconds(1));
  6286. return true;
  6287. });
  6288. });
  6289. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6290. svr.wait_until_ready();
  6291. Client client(HOST, PORT);
  6292. const Headers headers = {{"Accept", "text/event-stream"}};
  6293. auto get_thread = std::thread([&client, &headers]() {
  6294. auto res = client.Get(
  6295. "/events", headers,
  6296. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6297. });
  6298. auto se = detail::scope_exit([&] {
  6299. svr.stop();
  6300. get_thread.join();
  6301. listen_thread.join();
  6302. ASSERT_FALSE(svr.is_running());
  6303. });
  6304. // Give GET time to get a few messages.
  6305. std::this_thread::sleep_for(std::chrono::seconds(2));
  6306. }
  6307. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6308. httplib::Server svr;
  6309. svr.Post("/hi",
  6310. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6311. res.status = StatusCode::OK_200;
  6312. });
  6313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6314. svr.wait_until_ready();
  6315. Client cli(HOST, PORT);
  6316. auto res = cli.Post("/hi", "data", "text/plain");
  6317. ASSERT_TRUE(res);
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. svr.stop();
  6320. thread.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. res = cli.Post("/hi", "data", "text/plain");
  6323. ASSERT_FALSE(res);
  6324. }
  6325. TEST(ServerStopTest, ListenFailure) {
  6326. Server svr;
  6327. auto t = thread([&]() {
  6328. auto ret = svr.listen("????", PORT);
  6329. EXPECT_FALSE(ret);
  6330. });
  6331. svr.wait_until_ready();
  6332. svr.stop();
  6333. t.join();
  6334. }
  6335. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6336. TEST(ServerStopTest, Decommision) {
  6337. Server svr;
  6338. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6339. for (int i = 0; i < 4; i++) {
  6340. auto is_even = !(i % 2);
  6341. std::thread t{[&] {
  6342. try {
  6343. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6344. if (is_even) {
  6345. throw std::runtime_error("Some thing that happens to go wrong.");
  6346. }
  6347. svr.listen(HOST, PORT);
  6348. } catch (...) { svr.decommission(); }
  6349. }};
  6350. svr.wait_until_ready();
  6351. // Server is up
  6352. {
  6353. Client cli(HOST, PORT);
  6354. auto res = cli.Get("/hi");
  6355. if (is_even) {
  6356. EXPECT_FALSE(res);
  6357. } else {
  6358. EXPECT_TRUE(res);
  6359. EXPECT_EQ("hi...", res->body);
  6360. }
  6361. }
  6362. svr.stop();
  6363. t.join();
  6364. // Server is down...
  6365. {
  6366. Client cli(HOST, PORT);
  6367. auto res = cli.Get("/hi");
  6368. EXPECT_FALSE(res);
  6369. }
  6370. }
  6371. }
  6372. #endif
  6373. // Helper function for string body upload progress tests
  6374. template <typename SetupHandler, typename ClientCall>
  6375. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6376. ClientCall &&client_call,
  6377. const string &body) {
  6378. Server svr;
  6379. setup_handler(svr);
  6380. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6381. auto se = detail::scope_exit([&] {
  6382. svr.stop();
  6383. t.join();
  6384. });
  6385. svr.wait_until_ready();
  6386. Client cli(HOST, PORT);
  6387. vector<uint64_t> progress_values;
  6388. bool progress_called = false;
  6389. auto res =
  6390. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6391. progress_values.push_back(current);
  6392. progress_called = true;
  6393. return true;
  6394. });
  6395. ASSERT_TRUE(res);
  6396. EXPECT_EQ(200, res->status);
  6397. EXPECT_TRUE(progress_called);
  6398. }
  6399. TEST(UploadProgressTest, PostStringBodyBasic) {
  6400. TestStringBodyUploadProgress(
  6401. [](Server &svr) {
  6402. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6403. res.set_content("received", "text/plain");
  6404. });
  6405. },
  6406. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6407. return cli.Post("/test", body, "text/plain", progress_callback);
  6408. },
  6409. "test data for upload progress");
  6410. }
  6411. TEST(UploadProgressTest, PutStringBodyBasic) {
  6412. TestStringBodyUploadProgress(
  6413. [](Server &svr) {
  6414. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6415. res.set_content("put received", "text/plain");
  6416. });
  6417. },
  6418. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6419. return cli.Put("/test", body, "text/plain", progress_callback);
  6420. },
  6421. "put test data for upload progress");
  6422. }
  6423. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6424. TestStringBodyUploadProgress(
  6425. [](Server &svr) {
  6426. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6427. res.set_content("patch received", "text/plain");
  6428. });
  6429. },
  6430. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6431. return cli.Patch("/test", body, "text/plain", progress_callback);
  6432. },
  6433. "patch test data for upload progress");
  6434. }
  6435. // Helper function for content provider upload progress tests
  6436. template <typename SetupHandler, typename ClientCall>
  6437. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6438. ClientCall &&client_call) {
  6439. Server svr;
  6440. setup_handler(svr);
  6441. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6442. auto se = detail::scope_exit([&] {
  6443. svr.stop();
  6444. t.join();
  6445. });
  6446. svr.wait_until_ready();
  6447. Client cli(HOST, PORT);
  6448. vector<uint64_t> progress_values;
  6449. auto res =
  6450. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6451. progress_values.push_back(current);
  6452. return true;
  6453. });
  6454. ASSERT_TRUE(res);
  6455. EXPECT_EQ(200, res->status);
  6456. EXPECT_FALSE(progress_values.empty());
  6457. }
  6458. TEST(UploadProgressTest, PostContentProviderProgress) {
  6459. TestContentProviderUploadProgress(
  6460. [](Server &svr) {
  6461. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6462. res.set_content("provider received", "text/plain");
  6463. });
  6464. },
  6465. [](Client &cli, UploadProgress progress_callback) {
  6466. return cli.Post(
  6467. "/test", 10,
  6468. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6469. sink.os << "test data";
  6470. return true;
  6471. },
  6472. "text/plain", progress_callback);
  6473. });
  6474. }
  6475. // Helper function for multipart upload progress tests
  6476. template <typename SetupHandler, typename ClientCall>
  6477. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6478. ClientCall &&client_call,
  6479. const string &endpoint) {
  6480. Server svr;
  6481. setup_handler(svr);
  6482. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6483. auto se = detail::scope_exit([&] {
  6484. svr.stop();
  6485. t.join();
  6486. });
  6487. svr.wait_until_ready();
  6488. Client cli(HOST, PORT);
  6489. vector<uint64_t> progress_values;
  6490. UploadFormDataItems items = {
  6491. {"field1", "value1", "", ""},
  6492. {"field2", "longer value for progress tracking test", "", ""},
  6493. {"file1", "file content data for upload progress", "test.txt",
  6494. "text/plain"}};
  6495. auto res = client_call(cli, endpoint, items,
  6496. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6497. progress_values.push_back(current);
  6498. return true;
  6499. });
  6500. ASSERT_TRUE(res);
  6501. EXPECT_EQ(200, res->status);
  6502. EXPECT_FALSE(progress_values.empty());
  6503. }
  6504. TEST(UploadProgressTest, PostMultipartProgress) {
  6505. TestMultipartUploadProgress(
  6506. [](Server &svr) {
  6507. svr.Post("/multipart", [](const Request &req, Response &res) {
  6508. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6509. res.set_content("multipart received", "text/plain");
  6510. });
  6511. },
  6512. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6513. UploadProgress progress_callback) {
  6514. return cli.Post(endpoint, items, progress_callback);
  6515. },
  6516. "/multipart");
  6517. }
  6518. // Helper function for basic download progress tests
  6519. template <typename SetupHandler, typename ClientCall>
  6520. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6521. ClientCall &&client_call, const string &endpoint,
  6522. size_t expected_content_size) {
  6523. Server svr;
  6524. setup_handler(svr);
  6525. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6526. auto se = detail::scope_exit([&] {
  6527. svr.stop();
  6528. t.join();
  6529. });
  6530. svr.wait_until_ready();
  6531. Client cli(HOST, PORT);
  6532. vector<uint64_t> progress_values;
  6533. auto res = client_call(cli, endpoint,
  6534. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6535. progress_values.push_back(current);
  6536. return true;
  6537. });
  6538. ASSERT_TRUE(res);
  6539. EXPECT_EQ(200, res->status);
  6540. EXPECT_FALSE(progress_values.empty());
  6541. EXPECT_EQ(expected_content_size, res->body.size());
  6542. }
  6543. TEST(DownloadProgressTest, GetBasic) {
  6544. TestBasicDownloadProgress(
  6545. [](Server &svr) {
  6546. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6547. string content(1000, 'D');
  6548. res.set_content(content, "text/plain");
  6549. });
  6550. },
  6551. [](Client &cli, const string &endpoint,
  6552. DownloadProgress progress_callback) {
  6553. return cli.Get(endpoint, progress_callback);
  6554. },
  6555. "/download", 1000u);
  6556. }
  6557. // Helper function for content receiver download progress tests
  6558. template <typename SetupHandler, typename ClientCall>
  6559. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6560. ClientCall &&client_call,
  6561. const string &endpoint,
  6562. size_t expected_content_size) {
  6563. Server svr;
  6564. setup_handler(svr);
  6565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6566. auto se = detail::scope_exit([&] {
  6567. svr.stop();
  6568. t.join();
  6569. });
  6570. svr.wait_until_ready();
  6571. Client cli(HOST, PORT);
  6572. vector<uint64_t> progress_values;
  6573. string received_body;
  6574. auto res = client_call(
  6575. cli, endpoint,
  6576. [&](const char *data, size_t data_length) -> bool {
  6577. received_body.append(data, data_length);
  6578. return true;
  6579. },
  6580. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6581. progress_values.push_back(current);
  6582. return true;
  6583. });
  6584. ASSERT_TRUE(res);
  6585. EXPECT_EQ(200, res->status);
  6586. EXPECT_FALSE(progress_values.empty());
  6587. EXPECT_EQ(expected_content_size, received_body.size());
  6588. EXPECT_TRUE(res->body.empty());
  6589. }
  6590. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6591. TestContentReceiverDownloadProgress(
  6592. [](Server &svr) {
  6593. svr.Get("/download-receiver",
  6594. [](const Request & /*req*/, Response &res) {
  6595. string content(2000, 'R');
  6596. res.set_content(content, "text/plain");
  6597. });
  6598. },
  6599. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6600. DownloadProgress progress_callback) {
  6601. return cli.Get(endpoint, content_receiver, progress_callback);
  6602. },
  6603. "/download-receiver", 2000u);
  6604. }
  6605. TEST(StreamingTest, NoContentLengthStreaming) {
  6606. Server svr;
  6607. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6608. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6609. if (offset < 6) {
  6610. sink.os << (offset < 3 ? "a" : "b");
  6611. } else {
  6612. sink.done();
  6613. }
  6614. return true;
  6615. });
  6616. });
  6617. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6618. auto listen_se = detail::scope_exit([&] {
  6619. svr.stop();
  6620. listen_thread.join();
  6621. ASSERT_FALSE(svr.is_running());
  6622. });
  6623. svr.wait_until_ready();
  6624. Client client(HOST, PORT);
  6625. auto get_thread = std::thread([&client]() {
  6626. std::string s;
  6627. auto res =
  6628. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6629. s += std::string(data, len);
  6630. return true;
  6631. });
  6632. ASSERT_TRUE(res);
  6633. EXPECT_EQ(StatusCode::OK_200, res->status);
  6634. EXPECT_EQ("aaabbb", s);
  6635. });
  6636. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6637. // Give GET time to get a few messages.
  6638. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6639. }
  6640. TEST(MountTest, Unmount) {
  6641. Server svr;
  6642. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6643. auto se = detail::scope_exit([&] {
  6644. svr.stop();
  6645. listen_thread.join();
  6646. ASSERT_FALSE(svr.is_running());
  6647. });
  6648. svr.wait_until_ready();
  6649. Client cli("localhost", PORT);
  6650. svr.set_mount_point("/mount2", "./www2");
  6651. auto res = cli.Get("/");
  6652. ASSERT_TRUE(res);
  6653. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6654. res = cli.Get("/mount2/dir/test.html");
  6655. ASSERT_TRUE(res);
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. svr.set_mount_point("/", "./www");
  6658. res = cli.Get("/dir/");
  6659. ASSERT_TRUE(res);
  6660. EXPECT_EQ(StatusCode::OK_200, res->status);
  6661. svr.remove_mount_point("/");
  6662. res = cli.Get("/dir/");
  6663. ASSERT_TRUE(res);
  6664. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6665. svr.remove_mount_point("/mount2");
  6666. res = cli.Get("/mount2/dir/test.html");
  6667. ASSERT_TRUE(res);
  6668. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6669. }
  6670. TEST(MountTest, Redicect) {
  6671. Server svr;
  6672. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6673. auto se = detail::scope_exit([&] {
  6674. svr.stop();
  6675. listen_thread.join();
  6676. ASSERT_FALSE(svr.is_running());
  6677. });
  6678. svr.set_mount_point("/", "./www");
  6679. svr.wait_until_ready();
  6680. Client cli("localhost", PORT);
  6681. auto res = cli.Get("/dir/");
  6682. ASSERT_TRUE(res);
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. res = cli.Get("/dir");
  6685. ASSERT_TRUE(res);
  6686. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6687. res = cli.Get("/file");
  6688. ASSERT_TRUE(res);
  6689. EXPECT_EQ(StatusCode::OK_200, res->status);
  6690. res = cli.Get("/file/");
  6691. ASSERT_TRUE(res);
  6692. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6693. cli.set_follow_location(true);
  6694. res = cli.Get("/dir");
  6695. ASSERT_TRUE(res);
  6696. EXPECT_EQ(StatusCode::OK_200, res->status);
  6697. }
  6698. TEST(MountTest, MultibytesPathName) {
  6699. Server svr;
  6700. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6701. auto se = detail::scope_exit([&] {
  6702. svr.stop();
  6703. listen_thread.join();
  6704. ASSERT_FALSE(svr.is_running());
  6705. });
  6706. svr.set_mount_point("/", "./www");
  6707. svr.wait_until_ready();
  6708. Client cli("localhost", PORT);
  6709. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6710. ASSERT_TRUE(res);
  6711. EXPECT_EQ(StatusCode::OK_200, res->status);
  6712. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6713. }
  6714. #ifdef _WIN32
  6715. // Issue #2435: mmap::open() must succeed even when another handle holds
  6716. // the file open for writing (e.g. an active log file).
  6717. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  6718. const char *path = "mmap_concurrent_writer_test.txt";
  6719. const char *content = "hello";
  6720. {
  6721. std::ofstream f(path, std::ios::binary);
  6722. f.write(content, static_cast<std::streamsize>(strlen(content)));
  6723. }
  6724. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  6725. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  6726. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  6727. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  6728. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  6729. detail::mmap m(path);
  6730. ASSERT_TRUE(m.is_open());
  6731. EXPECT_EQ(strlen(content), m.size());
  6732. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  6733. }
  6734. #endif
  6735. TEST(KeepAliveTest, ReadTimeout) {
  6736. Server svr;
  6737. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6738. std::this_thread::sleep_for(std::chrono::seconds(2));
  6739. res.set_content("a", "text/plain");
  6740. });
  6741. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6742. res.set_content("b", "text/plain");
  6743. });
  6744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6745. auto se = detail::scope_exit([&] {
  6746. svr.stop();
  6747. listen_thread.join();
  6748. ASSERT_FALSE(svr.is_running());
  6749. });
  6750. svr.wait_until_ready();
  6751. Client cli("localhost", PORT);
  6752. cli.set_keep_alive(true);
  6753. cli.set_read_timeout(std::chrono::seconds(1));
  6754. auto resa = cli.Get("/a");
  6755. ASSERT_FALSE(resa);
  6756. EXPECT_EQ(Error::Read, resa.error());
  6757. auto resb = cli.Get("/b");
  6758. ASSERT_TRUE(resb);
  6759. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6760. EXPECT_EQ("b", resb->body);
  6761. }
  6762. TEST(KeepAliveTest, MaxCount) {
  6763. size_t keep_alive_max_count = 3;
  6764. Server svr;
  6765. svr.set_keep_alive_max_count(keep_alive_max_count);
  6766. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6767. res.set_content("Hello World!", "text/plain");
  6768. });
  6769. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6770. auto se = detail::scope_exit([&] {
  6771. svr.stop();
  6772. listen_thread.join();
  6773. ASSERT_FALSE(svr.is_running());
  6774. });
  6775. svr.wait_until_ready();
  6776. Client cli(HOST, PORT);
  6777. cli.set_keep_alive(true);
  6778. for (size_t i = 0; i < 5; i++) {
  6779. auto result = cli.Get("/hi");
  6780. ASSERT_TRUE(result);
  6781. EXPECT_EQ(StatusCode::OK_200, result->status);
  6782. if (i == keep_alive_max_count - 1) {
  6783. EXPECT_EQ("close", result->get_header_value("Connection"));
  6784. } else {
  6785. EXPECT_FALSE(result->has_header("Connection"));
  6786. }
  6787. }
  6788. }
  6789. TEST(KeepAliveTest, Issue1041) {
  6790. Server svr;
  6791. svr.set_keep_alive_timeout(3);
  6792. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6793. res.set_content("Hello World!", "text/plain");
  6794. });
  6795. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6796. auto se = detail::scope_exit([&] {
  6797. svr.stop();
  6798. listen_thread.join();
  6799. ASSERT_FALSE(svr.is_running());
  6800. });
  6801. svr.wait_until_ready();
  6802. Client cli(HOST, PORT);
  6803. cli.set_keep_alive(true);
  6804. auto result = cli.Get("/hi");
  6805. ASSERT_TRUE(result);
  6806. EXPECT_EQ(StatusCode::OK_200, result->status);
  6807. std::this_thread::sleep_for(std::chrono::seconds(5));
  6808. result = cli.Get("/hi");
  6809. ASSERT_TRUE(result);
  6810. EXPECT_EQ(StatusCode::OK_200, result->status);
  6811. }
  6812. TEST(KeepAliveTest, Issue1959) {
  6813. Server svr;
  6814. svr.set_keep_alive_timeout(5);
  6815. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6816. res.set_content("a", "text/plain");
  6817. });
  6818. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6819. auto se = detail::scope_exit([&] {
  6820. if (!svr.is_running()) return;
  6821. svr.stop();
  6822. listen_thread.join();
  6823. ASSERT_FALSE(svr.is_running());
  6824. });
  6825. svr.wait_until_ready();
  6826. Client cli("localhost", PORT);
  6827. cli.set_keep_alive(true);
  6828. using namespace std::chrono;
  6829. auto start = steady_clock::now();
  6830. cli.Get("/a");
  6831. svr.stop();
  6832. listen_thread.join();
  6833. auto end = steady_clock::now();
  6834. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6835. EXPECT_LT(elapsed, 5000);
  6836. }
  6837. #ifdef CPPHTTPLIB_SSL_ENABLED
  6838. TEST(KeepAliveTest, SSLClientReconnection) {
  6839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6840. ASSERT_TRUE(svr.is_valid());
  6841. svr.set_keep_alive_timeout(1);
  6842. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6843. res.set_content("Hello World!", "text/plain");
  6844. });
  6845. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6846. auto se = detail::scope_exit([&] {
  6847. svr.stop();
  6848. listen_thread.join();
  6849. ASSERT_FALSE(svr.is_running());
  6850. });
  6851. svr.wait_until_ready();
  6852. SSLClient cli(HOST, PORT);
  6853. cli.enable_server_certificate_verification(false);
  6854. cli.set_keep_alive(true);
  6855. auto result = cli.Get("/hi");
  6856. ASSERT_TRUE(result);
  6857. EXPECT_EQ(StatusCode::OK_200, result->status);
  6858. result = cli.Get("/hi");
  6859. ASSERT_TRUE(result);
  6860. EXPECT_EQ(StatusCode::OK_200, result->status);
  6861. std::this_thread::sleep_for(std::chrono::seconds(2));
  6862. // Recoonect
  6863. result = cli.Get("/hi");
  6864. ASSERT_TRUE(result);
  6865. EXPECT_EQ(StatusCode::OK_200, result->status);
  6866. result = cli.Get("/hi");
  6867. ASSERT_TRUE(result);
  6868. EXPECT_EQ(StatusCode::OK_200, result->status);
  6869. }
  6870. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6872. ASSERT_TRUE(svr.is_valid());
  6873. svr.set_keep_alive_timeout(1);
  6874. std::string content = "reconnect";
  6875. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6876. res.set_content("Hello World!", "text/plain");
  6877. });
  6878. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6879. auto se = detail::scope_exit([&] {
  6880. svr.stop();
  6881. listen_thread.join();
  6882. ASSERT_FALSE(svr.is_running());
  6883. });
  6884. svr.wait_until_ready();
  6885. SSLClient cli(HOST, PORT);
  6886. cli.enable_server_certificate_verification(false);
  6887. cli.set_keep_alive(true);
  6888. auto result = cli.Post(
  6889. "/hi", content.size(),
  6890. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6891. sink.write(content.c_str(), content.size());
  6892. return true;
  6893. },
  6894. "text/plain");
  6895. ASSERT_TRUE(result);
  6896. EXPECT_EQ(200, result->status);
  6897. std::this_thread::sleep_for(std::chrono::seconds(2));
  6898. // Recoonect
  6899. result = cli.Post(
  6900. "/hi", content.size(),
  6901. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6902. sink.write(content.c_str(), content.size());
  6903. return true;
  6904. },
  6905. "text/plain");
  6906. ASSERT_TRUE(result);
  6907. EXPECT_EQ(200, result->status);
  6908. result = cli.Post(
  6909. "/hi", content.size(),
  6910. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6911. sink.write(content.c_str(), content.size());
  6912. return true;
  6913. },
  6914. "text/plain");
  6915. ASSERT_TRUE(result);
  6916. EXPECT_EQ(200, result->status);
  6917. }
  6918. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6919. using namespace httplib::tls;
  6920. {
  6921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6922. ASSERT_TRUE(svr.is_valid());
  6923. svr.Get("/sni", [&](const Request &req, Response &res) {
  6924. std::string expected = req.sni();
  6925. EXPECT_EQ(expected, req.get_param_value("expected"));
  6926. res.set_content("ok", "text/plain");
  6927. });
  6928. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6929. auto se = detail::scope_exit([&] {
  6930. svr.stop();
  6931. listen_thread.join();
  6932. ASSERT_FALSE(svr.is_running());
  6933. });
  6934. svr.wait_until_ready();
  6935. {
  6936. SSLClient cli("localhost", PORT);
  6937. cli.enable_server_certificate_verification(false);
  6938. auto res = cli.Get("/sni?expected=localhost");
  6939. ASSERT_TRUE(res);
  6940. }
  6941. {
  6942. SSLClient cli("::1", PORT);
  6943. cli.enable_server_certificate_verification(false);
  6944. auto res = cli.Get("/sni?expected=");
  6945. // NOTE: This may fail if the server is listening on IPv4 only
  6946. // (e.g., when localhost resolves to 127.0.0.1 only)
  6947. if (res) {
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. } else {
  6950. EXPECT_EQ(Error::Connection, res.error());
  6951. }
  6952. }
  6953. }
  6954. }
  6955. #endif
  6956. TEST(ClientProblemDetectionTest, ContentProvider) {
  6957. Server svr;
  6958. size_t content_length = 1024 * 1024;
  6959. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6960. res.set_content_provider(
  6961. content_length, "text/plain",
  6962. [&](size_t offset, size_t length, DataSink &sink) {
  6963. auto out_len = std::min(length, static_cast<size_t>(1024));
  6964. std::string out(out_len, '@');
  6965. sink.write(out.data(), out_len);
  6966. return offset < 4096;
  6967. },
  6968. [](bool success) { ASSERT_FALSE(success); });
  6969. });
  6970. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6971. res.set_content_provider(
  6972. 0, "text/plain",
  6973. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6974. EXPECT_TRUE(false);
  6975. return true;
  6976. },
  6977. [](bool success) { ASSERT_FALSE(success); });
  6978. });
  6979. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6980. auto se = detail::scope_exit([&] {
  6981. svr.stop();
  6982. listen_thread.join();
  6983. ASSERT_FALSE(svr.is_running());
  6984. });
  6985. svr.wait_until_ready();
  6986. Client cli("localhost", PORT);
  6987. {
  6988. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6989. size_t /*data_length*/) { return false; });
  6990. ASSERT_FALSE(res);
  6991. }
  6992. {
  6993. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6994. size_t /*data_length*/) { return false; });
  6995. ASSERT_TRUE(res);
  6996. }
  6997. }
  6998. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6999. Server svr;
  7000. svr.set_error_handler([](Request const &, Response &res) -> void {
  7001. res.set_chunked_content_provider(
  7002. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7003. sink.os << "hello";
  7004. sink.os << "world";
  7005. sink.done();
  7006. return true;
  7007. });
  7008. });
  7009. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7010. auto se = detail::scope_exit([&] {
  7011. svr.stop();
  7012. listen_thread.join();
  7013. ASSERT_FALSE(svr.is_running());
  7014. });
  7015. svr.wait_until_ready();
  7016. Client cli("localhost", PORT);
  7017. auto res = cli.Get("/");
  7018. ASSERT_TRUE(res);
  7019. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7020. EXPECT_EQ("helloworld", res->body);
  7021. }
  7022. TEST(LongPollingTest, ClientCloseDetection) {
  7023. Server svr;
  7024. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7025. res.set_chunked_content_provider(
  7026. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7027. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7028. sink.os << "hello";
  7029. auto count = 10;
  7030. while (count > 0 && sink.is_writable()) {
  7031. this_thread::sleep_for(chrono::milliseconds(10));
  7032. count--;
  7033. }
  7034. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  7035. return true;
  7036. });
  7037. });
  7038. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7039. auto se = detail::scope_exit([&] {
  7040. svr.stop();
  7041. listen_thread.join();
  7042. ASSERT_FALSE(svr.is_running());
  7043. });
  7044. svr.wait_until_ready();
  7045. Client cli("localhost", PORT);
  7046. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7047. EXPECT_EQ("hello", string(data, data_length));
  7048. return false; // close the socket immediately.
  7049. });
  7050. ASSERT_FALSE(res);
  7051. }
  7052. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  7053. Server svr;
  7054. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  7055. res.set_chunked_content_provider(
  7056. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  7057. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  7058. sink.os << "hello";
  7059. EXPECT_TRUE(sink.os.good());
  7060. // Wait for the client to close the connection
  7061. auto count = 10;
  7062. while (count > 0 && sink.is_writable()) {
  7063. this_thread::sleep_for(chrono::milliseconds(10));
  7064. count--;
  7065. }
  7066. // After client disconnect, write repeatedly until the socket
  7067. // write actually fails (small writes may be absorbed by the
  7068. // kernel buffer)
  7069. std::string chunk(1024, 'x');
  7070. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  7071. sink.os << chunk;
  7072. }
  7073. EXPECT_TRUE(sink.os.fail());
  7074. return true;
  7075. });
  7076. });
  7077. auto port = svr.bind_to_any_port("localhost");
  7078. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  7079. auto se = detail::scope_exit([&] {
  7080. svr.stop();
  7081. listen_thread.join();
  7082. ASSERT_FALSE(svr.is_running());
  7083. });
  7084. svr.wait_until_ready();
  7085. Client cli("localhost", port);
  7086. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  7087. EXPECT_EQ("hello", string(data, data_length));
  7088. return false; // close the socket immediately.
  7089. });
  7090. ASSERT_FALSE(res);
  7091. }
  7092. TEST(GetWithParametersTest, GetWithParameters) {
  7093. Server svr;
  7094. svr.Get("/", [&](const Request &req, Response &) {
  7095. EXPECT_EQ("world", req.get_param_value("hello"));
  7096. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7097. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7098. });
  7099. svr.Get("/params", [&](const Request &req, Response &) {
  7100. EXPECT_EQ("world", req.get_param_value("hello"));
  7101. EXPECT_EQ("world2", req.get_param_value("hello2"));
  7102. EXPECT_EQ("world3", req.get_param_value("hello3"));
  7103. });
  7104. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  7105. EXPECT_EQ("resource-id", req.matches[1]);
  7106. EXPECT_EQ("foo", req.get_param_value("param1"));
  7107. EXPECT_EQ("bar", req.get_param_value("param2"));
  7108. });
  7109. svr.Get("/users/:id", [&](const Request &req, Response &) {
  7110. EXPECT_EQ("user-id", req.path_params.at("id"));
  7111. EXPECT_EQ("foo", req.get_param_value("param1"));
  7112. EXPECT_EQ("bar", req.get_param_value("param2"));
  7113. });
  7114. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7115. auto se = detail::scope_exit([&] {
  7116. svr.stop();
  7117. listen_thread.join();
  7118. ASSERT_FALSE(svr.is_running());
  7119. });
  7120. svr.wait_until_ready();
  7121. {
  7122. Client cli(HOST, PORT);
  7123. Params params;
  7124. params.emplace("hello", "world");
  7125. params.emplace("hello2", "world2");
  7126. params.emplace("hello3", "world3");
  7127. auto res = cli.Get("/", params, Headers{});
  7128. ASSERT_TRUE(res);
  7129. EXPECT_EQ(StatusCode::OK_200, res->status);
  7130. }
  7131. {
  7132. Client cli(HOST, PORT);
  7133. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  7134. ASSERT_TRUE(res);
  7135. EXPECT_EQ(StatusCode::OK_200, res->status);
  7136. }
  7137. {
  7138. Client cli(HOST, PORT);
  7139. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7140. ASSERT_TRUE(res);
  7141. EXPECT_EQ(StatusCode::OK_200, res->status);
  7142. }
  7143. {
  7144. Client cli(HOST, PORT);
  7145. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7146. ASSERT_TRUE(res);
  7147. EXPECT_EQ(StatusCode::OK_200, res->status);
  7148. }
  7149. }
  7150. TEST(GetWithParametersTest, GetWithParameters2) {
  7151. Server svr;
  7152. svr.Get("/", [&](const Request &req, Response &res) {
  7153. auto text = req.get_param_value("hello");
  7154. res.set_content(text, "text/plain");
  7155. });
  7156. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7157. auto se = detail::scope_exit([&] {
  7158. svr.stop();
  7159. listen_thread.join();
  7160. ASSERT_FALSE(svr.is_running());
  7161. });
  7162. svr.wait_until_ready();
  7163. Client cli("localhost", PORT);
  7164. Params params;
  7165. params.emplace("hello", "world");
  7166. std::string body;
  7167. auto res = cli.Get("/", params, Headers{},
  7168. [&](const char *data, size_t data_length) {
  7169. body.append(data, data_length);
  7170. return true;
  7171. });
  7172. ASSERT_TRUE(res);
  7173. EXPECT_EQ(StatusCode::OK_200, res->status);
  7174. EXPECT_EQ("world", body);
  7175. }
  7176. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7177. auto host = "httpbingo.org";
  7178. auto path = std::string{"/range/32"};
  7179. #ifdef CPPHTTPLIB_SSL_ENABLED
  7180. SSLClient cli(host);
  7181. #else
  7182. Client cli(host);
  7183. #endif
  7184. cli.set_default_headers({make_range_header({{1, 10}})});
  7185. cli.set_connection_timeout(5);
  7186. {
  7187. auto res = cli.Get(path);
  7188. ASSERT_TRUE(res);
  7189. EXPECT_EQ("bcdefghijk", res->body);
  7190. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7191. }
  7192. {
  7193. auto res = cli.Get(path);
  7194. ASSERT_TRUE(res);
  7195. EXPECT_EQ("bcdefghijk", res->body);
  7196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7197. }
  7198. }
  7199. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7200. Server svr;
  7201. svr.set_default_headers({{"Hello", "World"}});
  7202. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7203. res.set_content("ok", "text/plain");
  7204. });
  7205. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7206. auto se = detail::scope_exit([&] {
  7207. svr.stop();
  7208. listen_thread.join();
  7209. ASSERT_FALSE(svr.is_running());
  7210. });
  7211. svr.wait_until_ready();
  7212. Client cli("localhost", PORT);
  7213. auto res = cli.Get("/");
  7214. ASSERT_TRUE(res);
  7215. EXPECT_EQ(StatusCode::OK_200, res->status);
  7216. EXPECT_EQ("ok", res->body);
  7217. EXPECT_EQ("World", res->get_header_value("Hello"));
  7218. }
  7219. #ifdef CPPHTTPLIB_SSL_ENABLED
  7220. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7222. ASSERT_TRUE(svr.is_valid());
  7223. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7224. std::this_thread::sleep_for(std::chrono::seconds(2));
  7225. res.set_content("a", "text/plain");
  7226. });
  7227. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7228. res.set_content("b", "text/plain");
  7229. });
  7230. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7231. auto se = detail::scope_exit([&] {
  7232. svr.stop();
  7233. listen_thread.join();
  7234. ASSERT_FALSE(svr.is_running());
  7235. });
  7236. svr.wait_until_ready();
  7237. SSLClient cli("localhost", PORT);
  7238. cli.enable_server_certificate_verification(false);
  7239. cli.set_keep_alive(true);
  7240. cli.set_read_timeout(std::chrono::seconds(1));
  7241. auto resa = cli.Get("/a");
  7242. ASSERT_TRUE(!resa);
  7243. EXPECT_EQ(Error::Read, resa.error());
  7244. auto resb = cli.Get("/b");
  7245. ASSERT_TRUE(resb);
  7246. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7247. EXPECT_EQ("b", resb->body);
  7248. }
  7249. #endif
  7250. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7251. protected:
  7252. ServerTestWithAI_PASSIVE()
  7253. : cli_(HOST, PORT)
  7254. #ifdef CPPHTTPLIB_SSL_ENABLED
  7255. ,
  7256. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7257. #endif
  7258. {
  7259. #ifdef CPPHTTPLIB_SSL_ENABLED
  7260. cli_.enable_server_certificate_verification(false);
  7261. #endif
  7262. }
  7263. virtual void SetUp() {
  7264. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7265. res.set_content("Hello World!", "text/plain");
  7266. });
  7267. t_ = thread(
  7268. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7269. svr_.wait_until_ready();
  7270. }
  7271. virtual void TearDown() {
  7272. svr_.stop();
  7273. t_.join();
  7274. }
  7275. #ifdef CPPHTTPLIB_SSL_ENABLED
  7276. SSLClient cli_;
  7277. SSLServer svr_;
  7278. #else
  7279. Client cli_;
  7280. Server svr_;
  7281. #endif
  7282. thread t_;
  7283. };
  7284. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7285. auto res = cli_.Get("/hi");
  7286. ASSERT_TRUE(res);
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7289. EXPECT_EQ("Hello World!", res->body);
  7290. }
  7291. class ServerUpDownTest : public ::testing::Test {
  7292. protected:
  7293. ServerUpDownTest() : cli_(HOST, PORT) {}
  7294. virtual void SetUp() {
  7295. t_ = thread([&]() {
  7296. svr_.bind_to_any_port(HOST);
  7297. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7298. ASSERT_TRUE(svr_.listen_after_bind());
  7299. });
  7300. svr_.wait_until_ready();
  7301. }
  7302. virtual void TearDown() {
  7303. svr_.stop();
  7304. t_.join();
  7305. }
  7306. Client cli_;
  7307. Server svr_;
  7308. thread t_;
  7309. };
  7310. TEST_F(ServerUpDownTest, QuickStartStop) {
  7311. // Should not crash, especially when run with
  7312. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7313. }
  7314. class PayloadMaxLengthTest : public ::testing::Test {
  7315. protected:
  7316. PayloadMaxLengthTest()
  7317. : cli_(HOST, PORT)
  7318. #ifdef CPPHTTPLIB_SSL_ENABLED
  7319. ,
  7320. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7321. #endif
  7322. {
  7323. #ifdef CPPHTTPLIB_SSL_ENABLED
  7324. cli_.enable_server_certificate_verification(false);
  7325. #endif
  7326. }
  7327. virtual void SetUp() {
  7328. svr_.set_payload_max_length(8);
  7329. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7330. res.set_content("test", "text/plain");
  7331. });
  7332. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7333. svr_.wait_until_ready();
  7334. }
  7335. virtual void TearDown() {
  7336. svr_.stop();
  7337. t_.join();
  7338. }
  7339. #ifdef CPPHTTPLIB_SSL_ENABLED
  7340. SSLClient cli_;
  7341. SSLServer svr_;
  7342. #else
  7343. Client cli_;
  7344. Server svr_;
  7345. #endif
  7346. thread t_;
  7347. };
  7348. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7349. auto res = cli_.Post("/test", "123456789", "text/plain");
  7350. ASSERT_TRUE(res);
  7351. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7352. res = cli_.Post("/test", "12345678", "text/plain");
  7353. ASSERT_TRUE(res);
  7354. EXPECT_EQ(StatusCode::OK_200, res->status);
  7355. }
  7356. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7357. // Test chunked encoding with payload exceeding the 8-byte limit
  7358. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7359. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7360. ASSERT_TRUE(res);
  7361. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7362. }
  7363. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7364. // Test chunked encoding with payload within the 8-byte limit
  7365. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7366. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7367. ASSERT_TRUE(res);
  7368. EXPECT_EQ(StatusCode::OK_200, res->status);
  7369. }
  7370. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7371. // Test using send_request to send chunked data exceeding payload limit
  7372. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7373. "Host: " +
  7374. std::string(HOST) + ":" + std::to_string(PORT) +
  7375. "\r\n"
  7376. "Transfer-Encoding: chunked\r\n"
  7377. "Connection: close\r\n"
  7378. "\r\n"
  7379. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7380. "0123456789\r\n"
  7381. "0\r\n" // End chunk
  7382. "\r\n";
  7383. std::string response;
  7384. bool result = send_request(1, chunked_request, &response);
  7385. if (!result) {
  7386. // If send_request fails, it might be because the server closed the
  7387. // connection due to payload limit enforcement, which is acceptable
  7388. SUCCEED()
  7389. << "Server rejected oversized chunked request (connection closed)";
  7390. } else {
  7391. // If we got a response, check if it's an error response or connection was
  7392. // closed early Short response length indicates connection was closed due to
  7393. // payload limit
  7394. if (response.length() <= 10) {
  7395. SUCCEED() << "Server closed connection for oversized chunked request";
  7396. } else {
  7397. // Check for error status codes
  7398. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7399. response.find("Payload Too Large") != std::string::npos ||
  7400. response.find("400") != std::string::npos);
  7401. }
  7402. }
  7403. }
  7404. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7405. // Test request without Content-Length header exceeding payload limit
  7406. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7407. "Host: " +
  7408. std::string(HOST) + ":" +
  7409. std::to_string(PORT) +
  7410. "\r\n"
  7411. "Connection: close\r\n"
  7412. "\r\n";
  7413. // Add payload exceeding the 8-byte limit
  7414. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7415. request_without_content_length += large_payload;
  7416. std::string response;
  7417. bool result = send_request(1, request_without_content_length, &response);
  7418. if (!result) {
  7419. // If send_request fails, server likely closed connection due to payload
  7420. // limit
  7421. SUCCEED() << "Server rejected oversized request without Content-Length "
  7422. "(connection closed)";
  7423. } else {
  7424. // Check if server responded with error or closed connection early
  7425. if (response.length() <= 10) {
  7426. SUCCEED() << "Server closed connection for oversized request without "
  7427. "Content-Length";
  7428. } else {
  7429. // Check for error status codes
  7430. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7431. response.find("Payload Too Large") != std::string::npos ||
  7432. response.find("400") != std::string::npos);
  7433. }
  7434. }
  7435. }
  7436. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7437. // Test request without Content-Length header within payload limit
  7438. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7439. "Host: " +
  7440. std::string(HOST) + ":" +
  7441. std::to_string(PORT) +
  7442. "\r\n"
  7443. "Connection: close\r\n"
  7444. "\r\n";
  7445. // Add payload within the 8-byte limit
  7446. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7447. request_without_content_length += small_payload;
  7448. std::string response;
  7449. bool result = send_request(1, request_without_content_length, &response);
  7450. // For requests without Content-Length, the server may have different behavior
  7451. // The key is that it should not reject due to payload limit for small
  7452. // payloads
  7453. if (result) {
  7454. // Check for any HTTP response (success or error, but not connection closed)
  7455. if (response.length() > 10) {
  7456. SUCCEED()
  7457. << "Server processed request without Content-Length within limit";
  7458. } else {
  7459. // Short response might indicate connection closed, which is acceptable
  7460. SUCCEED() << "Server closed connection for request without "
  7461. "Content-Length (acceptable behavior)";
  7462. }
  7463. } else {
  7464. // Connection failure might be due to protocol requirements
  7465. SUCCEED() << "Connection issue with request without Content-Length "
  7466. "(environment-specific)";
  7467. }
  7468. }
  7469. class LargePayloadMaxLengthTest : public ::testing::Test {
  7470. protected:
  7471. LargePayloadMaxLengthTest()
  7472. : cli_(HOST, PORT)
  7473. #ifdef CPPHTTPLIB_SSL_ENABLED
  7474. ,
  7475. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7476. #endif
  7477. {
  7478. #ifdef CPPHTTPLIB_SSL_ENABLED
  7479. cli_.enable_server_certificate_verification(false);
  7480. #endif
  7481. }
  7482. virtual void SetUp() {
  7483. // Set 10MB payload limit
  7484. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7485. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7486. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7487. res.set_content("Large payload test", "text/plain");
  7488. });
  7489. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7490. svr_.wait_until_ready();
  7491. }
  7492. virtual void TearDown() {
  7493. svr_.stop();
  7494. t_.join();
  7495. }
  7496. #ifdef CPPHTTPLIB_SSL_ENABLED
  7497. SSLClient cli_;
  7498. SSLServer svr_;
  7499. #else
  7500. Client cli_;
  7501. Server svr_;
  7502. #endif
  7503. thread t_;
  7504. };
  7505. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7506. // Test chunked encoding with payload within 10MB limit
  7507. std::string medium_payload(5 * 1024 * 1024,
  7508. 'A'); // 5MB payload, within 10MB limit
  7509. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7510. ASSERT_TRUE(res);
  7511. EXPECT_EQ(StatusCode::OK_200, res->status);
  7512. }
  7513. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7514. // Test chunked encoding with payload exceeding 10MB limit
  7515. std::string large_payload(12 * 1024 * 1024,
  7516. 'B'); // 12MB payload, exceeds 10MB limit
  7517. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7518. // Server may either return 413 or close the connection
  7519. if (res) {
  7520. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7521. } else {
  7522. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7523. }
  7524. }
  7525. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7526. // Test request without Content-Length header within 10MB limit
  7527. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7528. "Host: " +
  7529. std::string(HOST) + ":" +
  7530. std::to_string(PORT) +
  7531. "\r\n"
  7532. "Connection: close\r\n"
  7533. "\r\n";
  7534. // Add 1MB payload (within 10MB limit)
  7535. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7536. request_without_content_length += medium_payload;
  7537. std::string response;
  7538. bool result = send_request(5, request_without_content_length, &response);
  7539. if (result) {
  7540. // Should get a proper HTTP response for payloads within limit
  7541. if (response.length() > 10) {
  7542. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7543. "10MB limit";
  7544. } else {
  7545. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7546. "Content-Length)";
  7547. }
  7548. } else {
  7549. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7550. }
  7551. }
  7552. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7553. // Test request without Content-Length header exceeding 10MB limit
  7554. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7555. "Host: " +
  7556. std::string(HOST) + ":" +
  7557. std::to_string(PORT) +
  7558. "\r\n"
  7559. "Connection: close\r\n"
  7560. "\r\n";
  7561. // Add 12MB payload (exceeds 10MB limit)
  7562. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7563. request_without_content_length += large_payload;
  7564. std::string response;
  7565. bool result = send_request(10, request_without_content_length, &response);
  7566. if (!result) {
  7567. // Server should close connection due to payload limit
  7568. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7569. "(connection closed)";
  7570. } else {
  7571. // Check for error response
  7572. if (response.length() <= 10) {
  7573. SUCCEED()
  7574. << "Server closed connection for 12MB request exceeding 10MB limit";
  7575. } else {
  7576. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7577. response.find("Payload Too Large") != std::string::npos ||
  7578. response.find("400") != std::string::npos);
  7579. }
  7580. }
  7581. }
  7582. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7583. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7584. // path.
  7585. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7586. Server svr;
  7587. const size_t LIMIT = 64 * 1024; // 64KB
  7588. svr.set_payload_max_length(LIMIT);
  7589. size_t total = 0;
  7590. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7591. const ContentReader &content_reader) {
  7592. content_reader([&](const char * /*data*/, size_t len) {
  7593. total += len;
  7594. return true;
  7595. });
  7596. res.status = 200;
  7597. res.set_content("stream_ok", "text/plain");
  7598. });
  7599. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7600. auto se = detail::scope_exit([&] {
  7601. svr.stop();
  7602. thread.join();
  7603. ASSERT_FALSE(svr.is_running());
  7604. });
  7605. svr.wait_until_ready();
  7606. // Prepare 256KB raw data and gzip-compress it
  7607. std::string raw(256 * 1024, 'A');
  7608. std::string gz;
  7609. {
  7610. z_stream zs{};
  7611. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7612. Z_DEFAULT_STRATEGY);
  7613. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7614. zs.avail_in = static_cast<uInt>(raw.size());
  7615. char outbuf[4096];
  7616. int ret;
  7617. do {
  7618. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7619. zs.avail_out = sizeof(outbuf);
  7620. ret = deflate(&zs, Z_FINISH);
  7621. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7622. } while (ret != Z_STREAM_END);
  7623. deflateEnd(&zs);
  7624. }
  7625. Client cli(HOST, PORT);
  7626. cli.set_connection_timeout(std::chrono::seconds(5));
  7627. Headers headers = {{"Content-Encoding", "gzip"}};
  7628. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7629. "application/octet-stream");
  7630. ASSERT_TRUE(res);
  7631. // Server must reject oversized decompressed payloads with 413.
  7632. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7633. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7634. EXPECT_LE(total, LIMIT);
  7635. }
  7636. #endif
  7637. // Regression test for DoS vulnerability: a malicious server sending a response
  7638. // without Content-Length header must not cause unbounded memory consumption on
  7639. // the client side. The client should stop reading after a reasonable limit,
  7640. // similar to the server-side set_payload_max_length protection.
  7641. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7642. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7643. #ifndef _WIN32
  7644. signal(SIGPIPE, SIG_IGN);
  7645. #endif
  7646. auto server_thread = std::thread([] {
  7647. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7648. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7649. default_socket_options(srv);
  7650. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7651. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7652. sockaddr_in addr{};
  7653. addr.sin_family = AF_INET;
  7654. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7655. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7656. int opt = 1;
  7657. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7658. #ifdef _WIN32
  7659. reinterpret_cast<const char *>(&opt),
  7660. #else
  7661. &opt,
  7662. #endif
  7663. sizeof(opt));
  7664. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7665. ::listen(srv, 1);
  7666. sockaddr_in cli_addr{};
  7667. socklen_t cli_len = sizeof(cli_addr);
  7668. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7669. if (cli != INVALID_SOCKET) {
  7670. char buf[4096];
  7671. ::recv(cli, buf, sizeof(buf), 0);
  7672. // Malicious response: no Content-Length, no chunked encoding
  7673. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7674. "Connection: close\r\n"
  7675. "\r\n";
  7676. ::send(cli,
  7677. #ifdef _WIN32
  7678. static_cast<const char *>(response_header.c_str()),
  7679. static_cast<int>(response_header.size()),
  7680. #else
  7681. response_header.c_str(), response_header.size(),
  7682. #endif
  7683. 0);
  7684. // Send 10MB of data
  7685. std::string chunk(64 * 1024, 'A');
  7686. size_t total_sent = 0;
  7687. while (total_sent < MALICIOUS_DATA_SIZE) {
  7688. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7689. auto sent = ::send(cli,
  7690. #ifdef _WIN32
  7691. static_cast<const char *>(chunk.c_str()),
  7692. static_cast<int>(to_send),
  7693. #else
  7694. chunk.c_str(), to_send,
  7695. #endif
  7696. 0);
  7697. if (sent <= 0) break;
  7698. total_sent += static_cast<size_t>(sent);
  7699. }
  7700. detail::close_socket(cli);
  7701. }
  7702. detail::close_socket(srv);
  7703. });
  7704. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7705. size_t total_read = 0;
  7706. {
  7707. Client cli("127.0.0.1", PORT + 2);
  7708. cli.set_read_timeout(5, 0);
  7709. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7710. auto stream = cli.open_stream("GET", "/malicious");
  7711. ASSERT_TRUE(stream.is_valid());
  7712. char buffer[64 * 1024];
  7713. ssize_t n;
  7714. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7715. total_read += static_cast<size_t>(n);
  7716. }
  7717. } // StreamHandle and Client destroyed here, closing the socket
  7718. server_thread.join();
  7719. // With set_payload_max_length, the client must stop reading before consuming
  7720. // all 10MB. The read loop should be cut off at or near the configured limit.
  7721. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7722. << "Client read " << total_read << " bytes, exceeding the configured "
  7723. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7724. }
  7725. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7726. // the entire response body without truncation.
  7727. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7728. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7729. #ifndef _WIN32
  7730. signal(SIGPIPE, SIG_IGN);
  7731. #endif
  7732. auto server_thread = std::thread([] {
  7733. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7734. default_socket_options(srv);
  7735. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7736. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7737. sockaddr_in addr{};
  7738. addr.sin_family = AF_INET;
  7739. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7740. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7741. int opt = 1;
  7742. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7743. #ifdef _WIN32
  7744. reinterpret_cast<const char *>(&opt),
  7745. #else
  7746. &opt,
  7747. #endif
  7748. sizeof(opt));
  7749. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7750. ::listen(srv, 1);
  7751. sockaddr_in cli_addr{};
  7752. socklen_t cli_len = sizeof(cli_addr);
  7753. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7754. if (cli != INVALID_SOCKET) {
  7755. char buf[4096];
  7756. ::recv(cli, buf, sizeof(buf), 0);
  7757. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7758. "Connection: close\r\n"
  7759. "\r\n";
  7760. ::send(cli,
  7761. #ifdef _WIN32
  7762. static_cast<const char *>(response_header.c_str()),
  7763. static_cast<int>(response_header.size()),
  7764. #else
  7765. response_header.c_str(), response_header.size(),
  7766. #endif
  7767. 0);
  7768. std::string chunk(64 * 1024, 'A');
  7769. size_t total_sent = 0;
  7770. while (total_sent < DATA_SIZE) {
  7771. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7772. auto sent = ::send(cli,
  7773. #ifdef _WIN32
  7774. static_cast<const char *>(chunk.c_str()),
  7775. static_cast<int>(to_send),
  7776. #else
  7777. chunk.c_str(), to_send,
  7778. #endif
  7779. 0);
  7780. if (sent <= 0) break;
  7781. total_sent += static_cast<size_t>(sent);
  7782. }
  7783. #ifdef _WIN32
  7784. ::shutdown(cli, SD_SEND);
  7785. #else
  7786. ::shutdown(cli, SHUT_WR);
  7787. #endif
  7788. // Drain until the client closes its end, ensuring all data is delivered
  7789. char drain[1024];
  7790. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7791. detail::close_socket(cli);
  7792. }
  7793. detail::close_socket(srv);
  7794. });
  7795. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7796. size_t total_read = 0;
  7797. {
  7798. Client cli("127.0.0.1", PORT + 2);
  7799. cli.set_read_timeout(5, 0);
  7800. cli.set_payload_max_length(0); // 0 means no limit
  7801. auto stream = cli.open_stream("GET", "/data");
  7802. ASSERT_TRUE(stream.is_valid());
  7803. char buffer[64 * 1024];
  7804. ssize_t n;
  7805. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7806. total_read += static_cast<size_t>(n);
  7807. }
  7808. }
  7809. server_thread.join();
  7810. EXPECT_EQ(total_read, DATA_SIZE)
  7811. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7812. << " bytes without truncation, but only read " << total_read << " bytes.";
  7813. }
  7814. // Verify that content_receiver bypasses the default payload_max_length,
  7815. // allowing streaming downloads larger than 100MB without requiring an explicit
  7816. // set_payload_max_length call.
  7817. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7818. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7819. #ifndef _WIN32
  7820. signal(SIGPIPE, SIG_IGN);
  7821. #endif
  7822. auto server_thread = std::thread([] {
  7823. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7824. default_socket_options(srv);
  7825. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7826. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7827. sockaddr_in addr{};
  7828. addr.sin_family = AF_INET;
  7829. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7830. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7831. int opt = 1;
  7832. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7833. #ifdef _WIN32
  7834. reinterpret_cast<const char *>(&opt),
  7835. #else
  7836. &opt,
  7837. #endif
  7838. sizeof(opt));
  7839. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7840. ::listen(srv, 1);
  7841. sockaddr_in cli_addr{};
  7842. socklen_t cli_len = sizeof(cli_addr);
  7843. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7844. if (cli != INVALID_SOCKET) {
  7845. char buf[4096];
  7846. ::recv(cli, buf, sizeof(buf), 0);
  7847. // Response with Content-Length larger than default 100MB limit
  7848. auto content_length = std::to_string(DATA_SIZE);
  7849. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7850. "Content-Length: " +
  7851. content_length +
  7852. "\r\n"
  7853. "Connection: close\r\n"
  7854. "\r\n";
  7855. ::send(cli,
  7856. #ifdef _WIN32
  7857. static_cast<const char *>(response_header.c_str()),
  7858. static_cast<int>(response_header.size()),
  7859. #else
  7860. response_header.c_str(), response_header.size(),
  7861. #endif
  7862. 0);
  7863. std::string chunk(64 * 1024, 'A');
  7864. size_t total_sent = 0;
  7865. while (total_sent < DATA_SIZE) {
  7866. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7867. auto sent = ::send(cli,
  7868. #ifdef _WIN32
  7869. static_cast<const char *>(chunk.c_str()),
  7870. static_cast<int>(to_send),
  7871. #else
  7872. chunk.c_str(), to_send,
  7873. #endif
  7874. 0);
  7875. if (sent <= 0) break;
  7876. total_sent += static_cast<size_t>(sent);
  7877. }
  7878. detail::close_socket(cli);
  7879. }
  7880. detail::close_socket(srv);
  7881. });
  7882. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7883. size_t total_received = 0;
  7884. {
  7885. Client cli("127.0.0.1", PORT + 2);
  7886. cli.set_read_timeout(10, 0);
  7887. // Do NOT call set_payload_max_length — use the default 100MB limit
  7888. auto res =
  7889. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7890. total_received += data_length;
  7891. return true;
  7892. });
  7893. ASSERT_TRUE(res);
  7894. EXPECT_EQ(StatusCode::OK_200, res->status);
  7895. }
  7896. server_thread.join();
  7897. EXPECT_EQ(total_received, DATA_SIZE)
  7898. << "With content_receiver, the client should read all " << DATA_SIZE
  7899. << " bytes despite the default 100MB payload_max_length, but only read "
  7900. << total_received << " bytes.";
  7901. }
  7902. // Verify that an explicit set_payload_max_length smaller than the response is
  7903. // enforced even when a content_receiver is used.
  7904. TEST(ClientVulnerabilityTest,
  7905. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7906. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7907. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7908. #ifndef _WIN32
  7909. signal(SIGPIPE, SIG_IGN);
  7910. #endif
  7911. auto server_thread = std::thread([] {
  7912. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7913. default_socket_options(srv);
  7914. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7915. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7916. sockaddr_in addr{};
  7917. addr.sin_family = AF_INET;
  7918. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7919. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7920. int opt = 1;
  7921. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7922. #ifdef _WIN32
  7923. reinterpret_cast<const char *>(&opt),
  7924. #else
  7925. &opt,
  7926. #endif
  7927. sizeof(opt));
  7928. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7929. ::listen(srv, 1);
  7930. sockaddr_in cli_addr{};
  7931. socklen_t cli_len = sizeof(cli_addr);
  7932. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7933. if (cli != INVALID_SOCKET) {
  7934. char buf[4096];
  7935. ::recv(cli, buf, sizeof(buf), 0);
  7936. auto content_length = std::to_string(DATA_SIZE);
  7937. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7938. "Content-Length: " +
  7939. content_length +
  7940. "\r\n"
  7941. "Connection: close\r\n"
  7942. "\r\n";
  7943. ::send(cli,
  7944. #ifdef _WIN32
  7945. static_cast<const char *>(response_header.c_str()),
  7946. static_cast<int>(response_header.size()),
  7947. #else
  7948. response_header.c_str(), response_header.size(),
  7949. #endif
  7950. 0);
  7951. std::string chunk(64 * 1024, 'A');
  7952. size_t total_sent = 0;
  7953. while (total_sent < DATA_SIZE) {
  7954. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7955. auto sent = ::send(cli,
  7956. #ifdef _WIN32
  7957. static_cast<const char *>(chunk.c_str()),
  7958. static_cast<int>(to_send),
  7959. #else
  7960. chunk.c_str(), to_send,
  7961. #endif
  7962. 0);
  7963. if (sent <= 0) break;
  7964. total_sent += static_cast<size_t>(sent);
  7965. }
  7966. detail::close_socket(cli);
  7967. }
  7968. detail::close_socket(srv);
  7969. });
  7970. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7971. size_t total_received = 0;
  7972. {
  7973. Client cli("127.0.0.1", PORT + 2);
  7974. cli.set_read_timeout(10, 0);
  7975. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7976. auto res =
  7977. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7978. total_received += data_length;
  7979. return true;
  7980. });
  7981. // Should fail because 200MB exceeds the explicit 150MB limit
  7982. EXPECT_FALSE(res);
  7983. }
  7984. server_thread.join();
  7985. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7986. << "Client with content_receiver should respect the explicit "
  7987. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7988. << total_received << " bytes.";
  7989. }
  7990. // Verify that an explicit set_payload_max_length larger than the response
  7991. // allows the content_receiver to read all data successfully.
  7992. TEST(ClientVulnerabilityTest,
  7993. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7994. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7995. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7996. #ifndef _WIN32
  7997. signal(SIGPIPE, SIG_IGN);
  7998. #endif
  7999. auto server_thread = std::thread([] {
  8000. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8001. default_socket_options(srv);
  8002. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8003. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8004. sockaddr_in addr{};
  8005. addr.sin_family = AF_INET;
  8006. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  8007. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8008. int opt = 1;
  8009. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8010. #ifdef _WIN32
  8011. reinterpret_cast<const char *>(&opt),
  8012. #else
  8013. &opt,
  8014. #endif
  8015. sizeof(opt));
  8016. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8017. ::listen(srv, 1);
  8018. sockaddr_in cli_addr{};
  8019. socklen_t cli_len = sizeof(cli_addr);
  8020. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8021. if (cli != INVALID_SOCKET) {
  8022. char buf[4096];
  8023. ::recv(cli, buf, sizeof(buf), 0);
  8024. auto content_length = std::to_string(DATA_SIZE);
  8025. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8026. "Content-Length: " +
  8027. content_length +
  8028. "\r\n"
  8029. "Connection: close\r\n"
  8030. "\r\n";
  8031. ::send(cli,
  8032. #ifdef _WIN32
  8033. static_cast<const char *>(response_header.c_str()),
  8034. static_cast<int>(response_header.size()),
  8035. #else
  8036. response_header.c_str(), response_header.size(),
  8037. #endif
  8038. 0);
  8039. std::string chunk(64 * 1024, 'A');
  8040. size_t total_sent = 0;
  8041. while (total_sent < DATA_SIZE) {
  8042. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  8043. auto sent = ::send(cli,
  8044. #ifdef _WIN32
  8045. static_cast<const char *>(chunk.c_str()),
  8046. static_cast<int>(to_send),
  8047. #else
  8048. chunk.c_str(), to_send,
  8049. #endif
  8050. 0);
  8051. if (sent <= 0) break;
  8052. total_sent += static_cast<size_t>(sent);
  8053. }
  8054. #ifdef _WIN32
  8055. ::shutdown(cli, SD_SEND);
  8056. #else
  8057. ::shutdown(cli, SHUT_WR);
  8058. #endif
  8059. char drain[1024];
  8060. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  8061. detail::close_socket(cli);
  8062. }
  8063. detail::close_socket(srv);
  8064. });
  8065. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8066. size_t total_received = 0;
  8067. {
  8068. Client cli("127.0.0.1", PORT + 2);
  8069. cli.set_read_timeout(10, 0);
  8070. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  8071. auto res =
  8072. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  8073. total_received += data_length;
  8074. return true;
  8075. });
  8076. ASSERT_TRUE(res);
  8077. EXPECT_EQ(StatusCode::OK_200, res->status);
  8078. }
  8079. server_thread.join();
  8080. EXPECT_EQ(total_received, DATA_SIZE)
  8081. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  8082. << " bytes (larger than " << DATA_SIZE
  8083. << " bytes response), content_receiver should read all data, but only "
  8084. "read "
  8085. << total_received << " bytes.";
  8086. }
  8087. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  8088. // Regression test for "zip bomb" attack on the client side: a malicious server
  8089. // sends a small gzip-compressed response that decompresses to a huge payload.
  8090. // The client must enforce payload_max_length on the decompressed size.
  8091. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  8092. constexpr size_t DECOMPRESSED_SIZE =
  8093. 10 * 1024 * 1024; // 10MB after decompression
  8094. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  8095. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  8096. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  8097. std::string compressed;
  8098. {
  8099. httplib::detail::gzip_compressor compressor;
  8100. bool ok =
  8101. compressor.compress(uncompressed.data(), uncompressed.size(),
  8102. /*last=*/true, [&](const char *buf, size_t len) {
  8103. compressed.append(buf, len);
  8104. return true;
  8105. });
  8106. ASSERT_TRUE(ok);
  8107. }
  8108. // Sanity: compressed data should be much smaller than the decompressed size
  8109. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  8110. #ifndef _WIN32
  8111. signal(SIGPIPE, SIG_IGN);
  8112. #endif
  8113. // Set up the listening socket in the main thread so the server is guaranteed
  8114. // to be ready before the client connects (eliminates race condition).
  8115. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8116. default_socket_options(srv);
  8117. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  8118. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  8119. sockaddr_in addr{};
  8120. addr.sin_family = AF_INET;
  8121. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  8122. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8123. int opt = 1;
  8124. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  8125. #ifdef _WIN32
  8126. reinterpret_cast<const char *>(&opt),
  8127. #else
  8128. &opt,
  8129. #endif
  8130. sizeof(opt));
  8131. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  8132. ASSERT_EQ(0, ::listen(srv, 1));
  8133. auto server_thread = std::thread([&compressed, srv] {
  8134. sockaddr_in cli_addr{};
  8135. socklen_t cli_len = sizeof(cli_addr);
  8136. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8137. if (cli != INVALID_SOCKET) {
  8138. // Read the full HTTP request (until \r\n\r\n)
  8139. char buf[4096];
  8140. size_t total = 0;
  8141. while (total < sizeof(buf)) {
  8142. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8143. if (n <= 0) break;
  8144. total += static_cast<size_t>(n);
  8145. // Check for end of headers
  8146. if (total >= 4) {
  8147. std::string req(buf, total);
  8148. if (req.find("\r\n\r\n") != std::string::npos) break;
  8149. }
  8150. }
  8151. // Malicious response: gzip-compressed body, no Content-Length
  8152. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8153. "Content-Encoding: gzip\r\n"
  8154. "Connection: close\r\n"
  8155. "\r\n";
  8156. ::send(cli,
  8157. #ifdef _WIN32
  8158. static_cast<const char *>(response_header.c_str()),
  8159. static_cast<int>(response_header.size()),
  8160. #else
  8161. response_header.c_str(), response_header.size(),
  8162. #endif
  8163. 0);
  8164. // Send the compressed payload (small on the wire, huge when decompressed)
  8165. size_t total_sent = 0;
  8166. while (total_sent < compressed.size()) {
  8167. auto to_send = std::min(compressed.size() - total_sent,
  8168. static_cast<size_t>(64 * 1024));
  8169. auto sent =
  8170. ::send(cli,
  8171. #ifdef _WIN32
  8172. static_cast<const char *>(compressed.c_str() + total_sent),
  8173. static_cast<int>(to_send),
  8174. #else
  8175. compressed.c_str() + total_sent, to_send,
  8176. #endif
  8177. 0);
  8178. if (sent <= 0) break;
  8179. total_sent += static_cast<size_t>(sent);
  8180. }
  8181. detail::close_socket(cli);
  8182. }
  8183. });
  8184. auto se = detail::scope_exit([&] {
  8185. detail::close_socket(srv);
  8186. server_thread.join();
  8187. });
  8188. size_t total_decompressed = 0;
  8189. {
  8190. Client cli("127.0.0.1", PORT + 3);
  8191. cli.set_read_timeout(5, 0);
  8192. cli.set_decompress(true);
  8193. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8194. auto stream = cli.open_stream("GET", "/zipbomb");
  8195. ASSERT_TRUE(stream.is_valid());
  8196. char buffer[64 * 1024];
  8197. ssize_t n;
  8198. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8199. total_decompressed += static_cast<size_t>(n);
  8200. }
  8201. }
  8202. // The decompressed size must be capped by payload_max_length. Without
  8203. // protection, the client would decompress the full 10MB from a tiny
  8204. // compressed payload, enabling a zip bomb DoS attack.
  8205. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8206. << "Client decompressed " << total_decompressed
  8207. << " bytes from a gzip response. The decompressed size should be "
  8208. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8209. }
  8210. #endif
  8211. TEST(HostAndPortPropertiesTest, NoSSL) {
  8212. httplib::Client cli("www.google.com", 1234);
  8213. ASSERT_EQ("www.google.com", cli.host());
  8214. ASSERT_EQ(1234, cli.port());
  8215. }
  8216. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8217. httplib::Client cli("www.google.com:1234");
  8218. ASSERT_EQ("www.google.com", cli.host());
  8219. ASSERT_EQ(1234, cli.port());
  8220. }
  8221. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8222. // Port number that overflows int — should not crash, client becomes invalid
  8223. httplib::Client cli("http://www.google.com:99999999999999999999");
  8224. ASSERT_FALSE(cli.is_valid());
  8225. }
  8226. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8227. // Port 99999 exceeds valid range (1-65535) — should not crash
  8228. httplib::Client cli("http://www.google.com:99999");
  8229. ASSERT_FALSE(cli.is_valid());
  8230. }
  8231. #ifdef CPPHTTPLIB_SSL_ENABLED
  8232. TEST(HostAndPortPropertiesTest, SSL) {
  8233. httplib::SSLClient cli("www.google.com");
  8234. ASSERT_EQ("www.google.com", cli.host());
  8235. ASSERT_EQ(443, cli.port());
  8236. }
  8237. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8238. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8239. std::string cert;
  8240. read_file(CA_CERT_FILE, cert);
  8241. httplib::SSLClient httplib_client("www.google.com");
  8242. // Load CA store first time
  8243. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8244. // Load CA store second time (update)
  8245. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8246. // Verify client is still valid and can make connections
  8247. httplib_client.enable_server_certificate_verification(true);
  8248. auto res = httplib_client.Get("/");
  8249. ASSERT_TRUE(res);
  8250. // Google may return 200 or 301 depending on various factors
  8251. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8252. res->status == StatusCode::MovedPermanently_301);
  8253. }
  8254. TEST(SSLClientTest, ServerNameIndication_Online) {
  8255. auto host = "httpbingo.org";
  8256. auto path = std::string{"/get"};
  8257. SSLClient cli(host, 443);
  8258. auto res = cli.Get(path);
  8259. ASSERT_TRUE(res);
  8260. ASSERT_EQ(StatusCode::OK_200, res->status);
  8261. }
  8262. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8263. // Use a site that will cause SSL verification failure due to self-signed cert
  8264. SSLClient cli("self-signed.badssl.com", 443);
  8265. cli.enable_server_certificate_verification(true);
  8266. auto res = cli.Get("/");
  8267. ASSERT_TRUE(!res);
  8268. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8269. // Verify backend error is captured for SSLServerVerification
  8270. // This occurs when certificate verification fails
  8271. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8272. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8273. EXPECT_NE(0UL, res.ssl_backend_error());
  8274. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8275. // For OpenSSL, ssl_error is 0 for verification errors
  8276. EXPECT_EQ(0, res.ssl_error());
  8277. #if !defined(_WIN32) || \
  8278. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8279. // On non-Windows or when Windows Schannel is disabled, the error comes
  8280. // from OpenSSL's verification
  8281. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8282. res.ssl_backend_error());
  8283. #endif
  8284. #endif
  8285. }
  8286. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8287. // Use a site where hostname doesn't match the certificate
  8288. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8289. SSLClient cli("wrong.host.badssl.com", 443);
  8290. cli.enable_server_certificate_verification(true);
  8291. cli.enable_server_hostname_verification(true);
  8292. auto res = cli.Get("/");
  8293. ASSERT_TRUE(!res);
  8294. // The error type depends on when hostname verification occurs:
  8295. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8296. // - Mbed TLS: SSLServerVerification (during handshake)
  8297. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8298. res.error() == Error::SSLServerVerification);
  8299. // Verify backend error is captured for hostname verification failure
  8300. EXPECT_NE(0UL, res.ssl_backend_error());
  8301. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8302. // For OpenSSL, ssl_error is 0 for verification errors
  8303. EXPECT_EQ(0, res.ssl_error());
  8304. #if !defined(_WIN32) || \
  8305. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8306. // On non-Windows or when Windows Schannel is disabled, the error comes
  8307. // from OpenSSL's hostname verification
  8308. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8309. res.ssl_backend_error());
  8310. #endif
  8311. #endif
  8312. }
  8313. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8314. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8315. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8316. SSLClient cli("www.google.com", 443);
  8317. cli.enable_server_certificate_verification(true);
  8318. auto res = cli.Get("/");
  8319. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8320. }
  8321. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8322. SSLClient cli("www.google.com", 443);
  8323. cli.enable_server_certificate_verification(true);
  8324. cli.enable_windows_certificate_verification(false);
  8325. auto res = cli.Get("/");
  8326. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8327. }
  8328. #endif
  8329. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8330. Client cli("https://google.com");
  8331. auto res = cli.Get("/");
  8332. ASSERT_TRUE(res);
  8333. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8334. }
  8335. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8336. SSLClient cli("google.com");
  8337. cli.set_ca_cert_path(CA_CERT_FILE);
  8338. auto res = cli.Get("/");
  8339. ASSERT_TRUE(res);
  8340. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8341. }
  8342. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8343. SSLClient cli("google.com");
  8344. cli.enable_server_certificate_verification(true);
  8345. cli.set_ca_cert_path("hello");
  8346. auto res = cli.Get("/");
  8347. ASSERT_TRUE(!res);
  8348. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8349. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8350. // should be set
  8351. EXPECT_EQ(0, res.ssl_error());
  8352. // Verify backend error is captured for SSLLoadingCerts
  8353. // This error occurs when loading CA certificates fails
  8354. EXPECT_NE(0UL, res.ssl_backend_error());
  8355. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8356. // OpenSSL specific error codes:
  8357. // > openssl errstr 0x80000002
  8358. // error:80000002:system library::No such file or directory
  8359. // > openssl errstr 0xA000126
  8360. // error:0A000126:SSL routines::unexpected eof while reading
  8361. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8362. res.ssl_backend_error() == 0xA000126);
  8363. #endif
  8364. }
  8365. TEST(SSLClientTest, ServerCertificateVerification4) {
  8366. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8367. ASSERT_TRUE(svr.is_valid());
  8368. svr.Get("/test", [&](const Request &, Response &res) {
  8369. res.set_content("test", "text/plain");
  8370. svr.stop();
  8371. ASSERT_TRUE(true);
  8372. });
  8373. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8374. auto se = detail::scope_exit([&] {
  8375. t.join();
  8376. ASSERT_FALSE(svr.is_running());
  8377. });
  8378. svr.wait_until_ready();
  8379. SSLClient cli("127.0.0.1", PORT);
  8380. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8381. cli.enable_server_certificate_verification(true);
  8382. cli.set_connection_timeout(30);
  8383. auto res = cli.Get("/test");
  8384. ASSERT_TRUE(res);
  8385. ASSERT_EQ(StatusCode::OK_200, res->status);
  8386. }
  8387. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8388. std::string cert;
  8389. read_file(CA_CERT_FILE, cert);
  8390. SSLClient cli("google.com");
  8391. cli.load_ca_cert_store(cert.data(), cert.size());
  8392. const auto res = cli.Get("/");
  8393. ASSERT_TRUE(res);
  8394. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8395. }
  8396. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8397. // clang-format off
  8398. static constexpr char cert[] =
  8399. "GlobalSign Root CA\n"
  8400. "==================\n"
  8401. "-----BEGIN CERTIFICATE-----\n"
  8402. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8403. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8404. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8405. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8406. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8407. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8408. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8409. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8410. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8411. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8412. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8413. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8414. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8415. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8416. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8417. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8418. "-----END CERTIFICATE-----\n";
  8419. // clang-format on
  8420. SSLClient cli("google.com");
  8421. cli.load_ca_cert_store(cert, sizeof(cert));
  8422. const auto res = cli.Get("/");
  8423. ASSERT_TRUE(res);
  8424. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8425. }
  8426. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8427. SSLClient cli("www.youtube.com");
  8428. cli.set_ca_cert_path(CA_CERT_FILE);
  8429. cli.enable_server_certificate_verification(true);
  8430. cli.set_follow_location(true);
  8431. auto res = cli.Get("/");
  8432. ASSERT_TRUE(res);
  8433. ASSERT_EQ(StatusCode::OK_200, res->status);
  8434. }
  8435. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8436. SSLClient cli("wWw.YouTube.Com");
  8437. cli.set_ca_cert_path(CA_CERT_FILE);
  8438. cli.enable_server_certificate_verification(true);
  8439. cli.enable_server_hostname_verification(true);
  8440. cli.set_follow_location(true);
  8441. auto res = cli.Get("/");
  8442. ASSERT_TRUE(res);
  8443. ASSERT_EQ(StatusCode::OK_200, res->status);
  8444. }
  8445. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8446. SSLClient cli("gOoGlE.COm");
  8447. cli.enable_server_certificate_verification(true);
  8448. cli.enable_server_hostname_verification(true);
  8449. cli.set_follow_location(true);
  8450. auto res = cli.Get("/");
  8451. ASSERT_TRUE(res);
  8452. ASSERT_EQ(StatusCode::OK_200, res->status);
  8453. }
  8454. TEST(SSLClientTest, Issue2004_Online) {
  8455. Client client("https://google.com");
  8456. client.set_follow_location(true);
  8457. auto res = client.Get("/");
  8458. ASSERT_TRUE(res);
  8459. ASSERT_EQ(StatusCode::OK_200, res->status);
  8460. auto body = res->body;
  8461. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8462. }
  8463. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8464. // Create SSLClient with invalid cert/key to make is_valid() return false
  8465. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8466. "nonexistent_key.pem");
  8467. // is_valid() should be false due to cert loading failure
  8468. ASSERT_FALSE(cli.is_valid());
  8469. auto res = cli.Get("/");
  8470. ASSERT_FALSE(res);
  8471. EXPECT_EQ(Error::SSLConnection, res.error());
  8472. }
  8473. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8474. // Test for Issue #2251: SSL error not properly reported when client cert
  8475. // and key paths are swapped or mismatched
  8476. // This simulates the scenario where user accidentally swaps the cert and key
  8477. // files
  8478. // Using client cert file as private key and vice versa (completely wrong)
  8479. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8480. // Should fail validation due to cert/key mismatch
  8481. ASSERT_FALSE(cli.is_valid());
  8482. // Attempt to make a request should fail with proper error
  8483. auto res = cli.Get("/");
  8484. ASSERT_FALSE(res);
  8485. EXPECT_EQ(Error::SSLConnection, res.error());
  8486. // SSL error should be recorded in the Result object (this is the key fix for
  8487. // Issue #2251)
  8488. auto backend_error = res.ssl_backend_error();
  8489. EXPECT_NE(0u, backend_error);
  8490. }
  8491. // Tests cert/key mismatch detection at the TLS context level
  8492. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8493. // Test that using mismatched cert/key causes connection failure.
  8494. // We verify this at the SSLClient level rather than through internal
  8495. // TLS API functions.
  8496. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8497. cli.enable_server_certificate_verification(false);
  8498. cli.set_connection_timeout(2);
  8499. // The mismatch should cause a connection or handshake error
  8500. auto res = cli.Get("/test");
  8501. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8502. // Either way, the request should fail
  8503. EXPECT_FALSE(res);
  8504. }
  8505. #endif
  8506. #if 0
  8507. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8508. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8509. ASSERT_TRUE(cli != nullptr);
  8510. cli->set_address_family(AF_INET6);
  8511. cli->set_interface("en0");
  8512. auto res = cli->Get("/get");
  8513. ASSERT_TRUE(res);
  8514. ASSERT_EQ(StatusCode::OK_200, res->status);
  8515. }
  8516. #endif
  8517. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8518. #ifdef CPPHTTPLIB_SSL_ENABLED
  8519. void ClientCertPresent(
  8520. const std::string &client_cert_file,
  8521. const std::string &client_private_key_file,
  8522. const std::string &client_encrypted_private_key_pass = std::string()) {
  8523. using namespace httplib::tls;
  8524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8525. CLIENT_CA_CERT_DIR);
  8526. ASSERT_TRUE(svr.is_valid());
  8527. svr.Get("/test", [&](const Request &req, Response &res) {
  8528. res.set_content("test", "text/plain");
  8529. auto cert = req.peer_cert();
  8530. ASSERT_TRUE(static_cast<bool>(cert));
  8531. std::string common_name = cert.subject_cn();
  8532. EXPECT_EQ("Common Name", common_name);
  8533. });
  8534. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8535. auto se = detail::scope_exit([&] {
  8536. svr.stop();
  8537. t.join();
  8538. ASSERT_FALSE(svr.is_running());
  8539. });
  8540. svr.wait_until_ready();
  8541. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8542. client_encrypted_private_key_pass);
  8543. cli.enable_server_certificate_verification(false);
  8544. cli.set_connection_timeout(30);
  8545. auto res = cli.Get("/test");
  8546. ASSERT_TRUE(res);
  8547. ASSERT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. TEST(SSLClientServerTest, ClientCertPresent) {
  8550. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8551. }
  8552. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8553. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8554. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8555. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8556. }
  8557. // PEM memory-based constructor tests (works with all TLS backends)
  8558. void PemMemoryClientCertPresent(
  8559. const std::string &client_cert_file,
  8560. const std::string &client_private_key_file,
  8561. const std::string &client_encrypted_private_key_pass = std::string()) {
  8562. // Read PEM files into memory
  8563. std::string server_cert_pem, server_key_pem;
  8564. std::string client_ca_pem;
  8565. std::string client_cert_pem, client_key_pem;
  8566. read_file(SERVER_CERT_FILE, server_cert_pem);
  8567. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8568. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8569. read_file(client_cert_file, client_cert_pem);
  8570. read_file(client_private_key_file, client_key_pem);
  8571. // Create server with PEM memory
  8572. SSLServer::PemMemory server_pem = {
  8573. server_cert_pem.c_str(),
  8574. server_cert_pem.size(),
  8575. server_key_pem.c_str(),
  8576. server_key_pem.size(),
  8577. client_ca_pem.c_str(),
  8578. client_ca_pem.size(),
  8579. nullptr // no password for server key
  8580. };
  8581. SSLServer svr(server_pem);
  8582. ASSERT_TRUE(svr.is_valid());
  8583. svr.Get("/test", [&](const Request &, Response &res) {
  8584. res.set_content("test", "text/plain");
  8585. });
  8586. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8587. auto se = detail::scope_exit([&] {
  8588. svr.stop();
  8589. t.join();
  8590. ASSERT_FALSE(svr.is_running());
  8591. });
  8592. svr.wait_until_ready();
  8593. // Create client with PEM memory
  8594. const char *password = client_encrypted_private_key_pass.empty()
  8595. ? nullptr
  8596. : client_encrypted_private_key_pass.c_str();
  8597. SSLClient::PemMemory client_pem = {
  8598. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8599. client_key_pem.size(), password};
  8600. SSLClient cli(HOST, PORT, client_pem);
  8601. cli.enable_server_certificate_verification(false);
  8602. cli.set_connection_timeout(30);
  8603. auto res = cli.Get("/test");
  8604. ASSERT_TRUE(res);
  8605. ASSERT_EQ(StatusCode::OK_200, res->status);
  8606. }
  8607. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8608. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8609. }
  8610. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8611. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8612. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8613. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8614. }
  8615. TEST(SSLClientServerTest, ClientCertMissing) {
  8616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8617. CLIENT_CA_CERT_DIR);
  8618. ASSERT_TRUE(svr.is_valid());
  8619. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8620. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8621. auto se = detail::scope_exit([&] {
  8622. svr.stop();
  8623. t.join();
  8624. ASSERT_FALSE(svr.is_running());
  8625. });
  8626. svr.wait_until_ready();
  8627. SSLClient cli(HOST, PORT);
  8628. cli.set_connection_timeout(30);
  8629. auto res = cli.Get("/test");
  8630. ASSERT_TRUE(!res);
  8631. // When client cert is missing and server requires it, connection fails
  8632. // Error type depends on backend implementation
  8633. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8634. res.error() == Error::SSLConnection);
  8635. // Verify backend error is captured
  8636. // Note: This test may have different error codes depending on the exact
  8637. // verification failure
  8638. EXPECT_NE(0UL, res.ssl_backend_error());
  8639. }
  8640. TEST(SSLClientServerTest, TrustDirOptional) {
  8641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8642. ASSERT_TRUE(svr.is_valid());
  8643. svr.Get("/test", [&](const Request &, Response &res) {
  8644. res.set_content("test", "text/plain");
  8645. });
  8646. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8647. auto se = detail::scope_exit([&] {
  8648. svr.stop();
  8649. t.join();
  8650. ASSERT_FALSE(svr.is_running());
  8651. });
  8652. svr.wait_until_ready();
  8653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8654. cli.enable_server_certificate_verification(false);
  8655. cli.set_connection_timeout(30);
  8656. auto res = cli.Get("/test");
  8657. ASSERT_TRUE(res);
  8658. ASSERT_EQ(StatusCode::OK_200, res->status);
  8659. }
  8660. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8661. class NoListenSSLServer : public SSLServer {
  8662. public:
  8663. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8664. const char *client_ca_cert_file_path,
  8665. const char *client_ca_cert_dir_path = nullptr)
  8666. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8667. client_ca_cert_dir_path),
  8668. stop_(false) {}
  8669. std::atomic_bool stop_;
  8670. private:
  8671. bool process_and_close_socket(socket_t /*sock*/) override {
  8672. // Don't create SSL context
  8673. while (!stop_.load()) {
  8674. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8675. }
  8676. return true;
  8677. }
  8678. };
  8679. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8680. CLIENT_CA_CERT_FILE);
  8681. ASSERT_TRUE(svr.is_valid());
  8682. svr.Get("/test", [&](const Request &, Response &res) {
  8683. res.set_content("test", "text/plain");
  8684. });
  8685. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8686. auto se = detail::scope_exit([&] {
  8687. svr.stop_ = true;
  8688. svr.stop();
  8689. t.join();
  8690. ASSERT_FALSE(svr.is_running());
  8691. });
  8692. svr.wait_until_ready();
  8693. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8694. cli.enable_server_certificate_verification(false);
  8695. cli.set_connection_timeout(1);
  8696. auto res = cli.Get("/test");
  8697. ASSERT_TRUE(!res);
  8698. EXPECT_EQ(Error::SSLConnection, res.error());
  8699. // Timeout results in WantRead error code (maps to backend-specific value)
  8700. EXPECT_NE(0, res.ssl_error());
  8701. }
  8702. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8703. // Test SSLServer with client certificate verification using the standard
  8704. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8706. CLIENT_CA_CERT_DIR);
  8707. ASSERT_TRUE(svr.is_valid());
  8708. svr.Get("/test", [&](const Request &req, Response &res) {
  8709. res.set_content("test", "text/plain");
  8710. auto cert = req.peer_cert();
  8711. ASSERT_TRUE(static_cast<bool>(cert));
  8712. auto common_name = cert.subject_cn();
  8713. EXPECT_EQ("Common Name", common_name);
  8714. });
  8715. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8716. auto se = detail::scope_exit([&] {
  8717. svr.stop();
  8718. t.join();
  8719. ASSERT_FALSE(svr.is_running());
  8720. });
  8721. svr.wait_until_ready();
  8722. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8723. cli.enable_server_certificate_verification(false);
  8724. cli.set_connection_timeout(30);
  8725. auto res = cli.Get("/test");
  8726. ASSERT_TRUE(res);
  8727. ASSERT_EQ(StatusCode::OK_200, res->status);
  8728. }
  8729. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8730. // Verifies that wildcard matching and exact matching work consistently
  8731. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8732. using namespace httplib::tls;
  8733. // We need a running server to test against
  8734. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8735. ASSERT_TRUE(svr.is_valid());
  8736. svr.Get("/test", [](const Request &, Response &res) {
  8737. res.set_content("ok", "text/plain");
  8738. });
  8739. thread t([&]() { svr.listen(HOST, PORT); });
  8740. auto se = detail::scope_exit([&] {
  8741. svr.stop();
  8742. t.join();
  8743. });
  8744. svr.wait_until_ready();
  8745. bool verify_callback_called = false;
  8746. bool verify_result_wrong = false;
  8747. SSLClient cli(HOST, PORT);
  8748. cli.enable_server_certificate_verification(true);
  8749. cli.set_ca_cert_path(CA_CERT_FILE);
  8750. cli.set_connection_timeout(5);
  8751. // Note: Test certificate has CN="Common Name", not "localhost"
  8752. bool verify_result_cn = false;
  8753. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8754. verify_callback_called = true;
  8755. if (!ctx.cert) return false;
  8756. // Test 1: "Common Name" should match (our test server cert CN)
  8757. verify_result_cn = ctx.check_hostname("Common Name");
  8758. // Test 2: wrong hostname should not match
  8759. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8760. return true; // Accept for the purpose of this test
  8761. });
  8762. auto res = cli.Get("/test");
  8763. // The request may succeed or fail depending on cert configuration
  8764. // but the callback should have been called
  8765. ASSERT_TRUE(verify_callback_called)
  8766. << "Verify callback should have been called";
  8767. // CN="Common Name" should match our test certificate
  8768. EXPECT_TRUE(verify_result_cn)
  8769. << "verify_hostname should match 'Common Name' (certificate CN)";
  8770. // Wrong hostname should not match
  8771. EXPECT_FALSE(verify_result_wrong)
  8772. << "verify_hostname should not match 'wronghost.example.com'";
  8773. }
  8774. #endif
  8775. // mbedTLS-specific callback constructor test
  8776. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8777. #ifdef CPPHTTPLIB_SSL_ENABLED
  8778. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8780. ASSERT_TRUE(svr.is_valid());
  8781. // Set up a handler to verify client certificate is present
  8782. bool client_cert_verified = false;
  8783. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8784. // Verify that client certificate was provided
  8785. client_cert_verified = true;
  8786. res.set_content("success", "text/plain");
  8787. });
  8788. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8789. auto se = detail::scope_exit([&] {
  8790. svr.stop();
  8791. t.join();
  8792. ASSERT_FALSE(svr.is_running());
  8793. });
  8794. svr.wait_until_ready();
  8795. // Client with certificate
  8796. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8797. cli.enable_server_certificate_verification(false);
  8798. cli.set_connection_timeout(30);
  8799. auto res = cli.Get("/test");
  8800. ASSERT_TRUE(res);
  8801. ASSERT_EQ(StatusCode::OK_200, res->status);
  8802. ASSERT_TRUE(client_cert_verified);
  8803. EXPECT_EQ("success", res->body);
  8804. }
  8805. #endif
  8806. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8807. // backends
  8808. #ifdef CPPHTTPLIB_SSL_ENABLED
  8809. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8810. using namespace httplib::tls;
  8811. // Test that when client CA cert file is provided,
  8812. // the server properly requests and validates client certificates
  8813. // Create a server with client authentication
  8814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8815. ASSERT_TRUE(svr.is_valid());
  8816. bool handler_called = false;
  8817. svr.Get("/test", [&](const Request &req, Response &res) {
  8818. handler_called = true;
  8819. // Verify that a client certificate was provided
  8820. auto cert = req.peer_cert();
  8821. ASSERT_TRUE(static_cast<bool>(cert));
  8822. // Get the issuer name
  8823. std::string issuer_str = cert.issuer_name();
  8824. ASSERT_FALSE(issuer_str.empty());
  8825. // The client certificate should be issued by our test CA
  8826. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8827. res.set_content("authenticated", "text/plain");
  8828. });
  8829. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8830. auto se = detail::scope_exit([&] {
  8831. svr.stop();
  8832. t.join();
  8833. ASSERT_FALSE(svr.is_running());
  8834. });
  8835. svr.wait_until_ready();
  8836. // Connect with a client certificate issued by the CA
  8837. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8838. cli.enable_server_certificate_verification(false);
  8839. cli.set_connection_timeout(30);
  8840. auto res = cli.Get("/test");
  8841. ASSERT_TRUE(res);
  8842. ASSERT_EQ(StatusCode::OK_200, res->status);
  8843. ASSERT_TRUE(handler_called);
  8844. EXPECT_EQ("authenticated", res->body);
  8845. }
  8846. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8847. using namespace httplib::tls;
  8848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8849. ASSERT_TRUE(svr.is_valid());
  8850. svr.Get("/test", [](const Request &, Response &res) {
  8851. res.set_content("ok", "text/plain");
  8852. });
  8853. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8854. auto se = detail::scope_exit([&] {
  8855. svr.stop();
  8856. t.join();
  8857. });
  8858. svr.wait_until_ready();
  8859. SSLClient cli(HOST, PORT);
  8860. cli.enable_server_certificate_verification(false);
  8861. cli.set_connection_timeout(30);
  8862. bool cert_checked = false;
  8863. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8864. if (ctx.cert) {
  8865. auto sans = ctx.sans();
  8866. // Test certificate may or may not have SANs - just verify the API
  8867. // works If SANs exist, verify the types are valid
  8868. for (const auto &san : sans) {
  8869. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8870. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8871. san.type == SanType::OTHER);
  8872. EXPECT_FALSE(san.value.empty());
  8873. }
  8874. cert_checked = true;
  8875. }
  8876. return true;
  8877. });
  8878. auto res = cli.Get("/test");
  8879. ASSERT_TRUE(res);
  8880. EXPECT_TRUE(cert_checked);
  8881. }
  8882. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8883. using namespace httplib::tls;
  8884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8885. ASSERT_TRUE(svr.is_valid());
  8886. svr.Get("/test", [](const Request &, Response &res) {
  8887. res.set_content("ok", "text/plain");
  8888. });
  8889. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8890. auto se = detail::scope_exit([&] {
  8891. svr.stop();
  8892. t.join();
  8893. });
  8894. svr.wait_until_ready();
  8895. SSLClient cli(HOST, PORT);
  8896. cli.enable_server_certificate_verification(false);
  8897. cli.set_connection_timeout(30);
  8898. bool validity_checked = false;
  8899. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8900. if (ctx.cert) {
  8901. time_t not_before = 0, not_after = 0;
  8902. bool result = ctx.validity(not_before, not_after);
  8903. EXPECT_TRUE(result);
  8904. // Verify that not_before < now < not_after for a valid cert
  8905. time_t now = time(nullptr);
  8906. EXPECT_LT(not_before, now);
  8907. EXPECT_GT(not_after, now);
  8908. validity_checked = true;
  8909. }
  8910. return true;
  8911. });
  8912. auto res = cli.Get("/test");
  8913. ASSERT_TRUE(res);
  8914. EXPECT_TRUE(validity_checked);
  8915. }
  8916. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8917. using namespace httplib::tls;
  8918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8919. ASSERT_TRUE(svr.is_valid());
  8920. svr.Get("/test", [](const Request &, Response &res) {
  8921. res.set_content("ok", "text/plain");
  8922. });
  8923. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8924. auto se = detail::scope_exit([&] {
  8925. svr.stop();
  8926. t.join();
  8927. });
  8928. svr.wait_until_ready();
  8929. SSLClient cli(HOST, PORT);
  8930. cli.enable_server_certificate_verification(false);
  8931. cli.set_connection_timeout(30);
  8932. bool serial_checked = false;
  8933. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8934. if (ctx.cert) {
  8935. std::string serial = ctx.serial();
  8936. EXPECT_FALSE(serial.empty());
  8937. // Serial should be a hex string
  8938. for (char c : serial) {
  8939. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8940. (c >= 'a' && c <= 'f'));
  8941. }
  8942. serial_checked = true;
  8943. }
  8944. return true;
  8945. });
  8946. auto res = cli.Get("/test");
  8947. ASSERT_TRUE(res);
  8948. EXPECT_TRUE(serial_checked);
  8949. }
  8950. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8951. // Test 1: Valid CA file - no error should be recorded
  8952. {
  8953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8954. CLIENT_CA_CERT_FILE);
  8955. ASSERT_TRUE(svr.is_valid());
  8956. // With valid setup, last_ssl_error should be 0
  8957. EXPECT_EQ(0, svr.ssl_last_error());
  8958. }
  8959. // Test 2: Invalid CA file content
  8960. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8961. {
  8962. // Create a temporary file with completely invalid content
  8963. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8964. {
  8965. std::ofstream ofs(temp_invalid_ca);
  8966. ofs << "This is not a certificate file at all\n";
  8967. ofs << "Just plain text content\n";
  8968. }
  8969. // Create server with invalid CA file
  8970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8971. // Clean up temporary file
  8972. std::remove(temp_invalid_ca);
  8973. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8974. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8975. // Note: SSL_CTX_load_verify_locations typically fails first,
  8976. // but our error handling code path is still exercised
  8977. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8978. }
  8979. }
  8980. TEST(VerifyCallbackTest, VerifyContextFields) {
  8981. using namespace httplib::tls;
  8982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8983. ASSERT_TRUE(svr.is_valid());
  8984. svr.Get("/test", [](const Request &, Response &res) {
  8985. res.set_content("ok", "text/plain");
  8986. });
  8987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8988. auto se = detail::scope_exit([&] {
  8989. svr.stop();
  8990. t.join();
  8991. });
  8992. svr.wait_until_ready();
  8993. SSLClient cli(HOST, PORT);
  8994. cli.enable_server_certificate_verification(false);
  8995. cli.set_connection_timeout(30);
  8996. int callback_count = 0;
  8997. bool saw_leaf_cert = false;
  8998. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8999. if (ctx.cert) {
  9000. callback_count++;
  9001. // We should see at least one certificate (the leaf)
  9002. std::string cn = ctx.subject_cn();
  9003. if (!cn.empty()) { saw_leaf_cert = true; }
  9004. // Verify context fields are populated
  9005. EXPECT_NE(ctx.session, nullptr);
  9006. EXPECT_GE(ctx.depth, 0);
  9007. }
  9008. return true;
  9009. });
  9010. auto res = cli.Get("/test");
  9011. ASSERT_TRUE(res);
  9012. EXPECT_GT(callback_count, 0);
  9013. EXPECT_TRUE(saw_leaf_cert);
  9014. }
  9015. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  9016. using httplib::tls::TlsError;
  9017. // Test that verify_error_to_string returns empty for success
  9018. std::string success_str = TlsError::verify_error_to_string(0);
  9019. EXPECT_TRUE(success_str.empty());
  9020. // Test that verify_error_to_string returns non-empty for error codes
  9021. // Using a common error code (certificate expired)
  9022. std::string error_str =
  9023. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  9024. EXPECT_FALSE(error_str.empty());
  9025. }
  9026. TEST(SessionVerifierTest, CertificateAccepted) {
  9027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9028. ASSERT_TRUE(svr.is_valid());
  9029. svr.Get("/test", [](const Request &, Response &res) {
  9030. res.set_content("ok", "text/plain");
  9031. });
  9032. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9033. auto se = detail::scope_exit([&] {
  9034. svr.stop();
  9035. t.join();
  9036. });
  9037. svr.wait_until_ready();
  9038. SSLClient cli(HOST, PORT);
  9039. cli.enable_server_certificate_verification(false);
  9040. cli.set_connection_timeout(30);
  9041. bool callback_called = false;
  9042. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9043. EXPECT_NE(session, nullptr);
  9044. callback_called = true;
  9045. return SSLVerifierResponse::CertificateAccepted;
  9046. });
  9047. auto res = cli.Get("/test");
  9048. ASSERT_TRUE(res);
  9049. EXPECT_EQ(200, res->status);
  9050. EXPECT_TRUE(callback_called);
  9051. }
  9052. TEST(SessionVerifierTest, CertificateRejected) {
  9053. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9054. ASSERT_TRUE(svr.is_valid());
  9055. svr.Get("/test", [](const Request &, Response &res) {
  9056. res.set_content("ok", "text/plain");
  9057. });
  9058. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9059. auto se = detail::scope_exit([&] {
  9060. svr.stop();
  9061. t.join();
  9062. });
  9063. svr.wait_until_ready();
  9064. SSLClient cli(HOST, PORT);
  9065. cli.enable_server_certificate_verification(false);
  9066. cli.set_connection_timeout(30);
  9067. bool callback_called = false;
  9068. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9069. EXPECT_NE(session, nullptr);
  9070. callback_called = true;
  9071. return SSLVerifierResponse::CertificateRejected;
  9072. });
  9073. auto res = cli.Get("/test");
  9074. EXPECT_FALSE(res);
  9075. EXPECT_TRUE(callback_called);
  9076. }
  9077. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  9078. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9079. ASSERT_TRUE(svr.is_valid());
  9080. svr.Get("/test", [](const Request &, Response &res) {
  9081. res.set_content("ok", "text/plain");
  9082. });
  9083. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9084. auto se = detail::scope_exit([&] {
  9085. svr.stop();
  9086. t.join();
  9087. });
  9088. svr.wait_until_ready();
  9089. // NoDecisionMade with verification disabled should succeed (no default check)
  9090. SSLClient cli(HOST, PORT);
  9091. cli.enable_server_certificate_verification(false);
  9092. cli.set_connection_timeout(30);
  9093. bool callback_called = false;
  9094. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9095. EXPECT_NE(session, nullptr);
  9096. callback_called = true;
  9097. return SSLVerifierResponse::NoDecisionMade;
  9098. });
  9099. auto res = cli.Get("/test");
  9100. ASSERT_TRUE(res);
  9101. EXPECT_EQ(200, res->status);
  9102. EXPECT_TRUE(callback_called);
  9103. }
  9104. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  9105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9106. ASSERT_TRUE(svr.is_valid());
  9107. svr.Get("/test", [](const Request &, Response &res) {
  9108. res.set_content("ok", "text/plain");
  9109. });
  9110. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9111. auto se = detail::scope_exit([&] {
  9112. svr.stop();
  9113. t.join();
  9114. });
  9115. svr.wait_until_ready();
  9116. // NoDecisionMade with verification enabled should fail (self-signed cert).
  9117. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  9118. // so we only check that the request fails, not whether the callback was
  9119. // called.
  9120. SSLClient cli(HOST, PORT);
  9121. cli.enable_server_certificate_verification(true);
  9122. cli.set_connection_timeout(30);
  9123. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  9124. EXPECT_NE(session, nullptr);
  9125. return SSLVerifierResponse::NoDecisionMade;
  9126. });
  9127. auto res = cli.Get("/test");
  9128. EXPECT_FALSE(res);
  9129. }
  9130. TEST(SSLClientServerTest, ClientCAListFromPem) {
  9131. // Test SSL server using PemMemory constructor with client CA certificates
  9132. // Read PEM files
  9133. std::string server_cert_pem, server_key_pem, client_ca_pem;
  9134. read_file(SERVER_CERT_FILE, server_cert_pem);
  9135. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  9136. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  9137. // Create SSLServer with PemMemory constructor including client CA
  9138. SSLServer::PemMemory server_pem = {
  9139. server_cert_pem.c_str(),
  9140. server_cert_pem.size(),
  9141. server_key_pem.c_str(),
  9142. server_key_pem.size(),
  9143. client_ca_pem.c_str(),
  9144. client_ca_pem.size(),
  9145. nullptr // no password for server key
  9146. };
  9147. SSLServer svr(server_pem);
  9148. ASSERT_TRUE(svr.is_valid());
  9149. // No SSL error should be recorded for valid setup
  9150. EXPECT_EQ(0, svr.ssl_last_error());
  9151. // Set up server endpoints
  9152. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9153. res.set_content("ok", "text/plain");
  9154. });
  9155. // Start server in a thread
  9156. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9157. svr.wait_until_ready();
  9158. // Connect with client certificate (using constructor with paths)
  9159. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9160. cli.enable_server_certificate_verification(false);
  9161. auto res = cli.Get("/test-pem-ca");
  9162. ASSERT_TRUE(res);
  9163. EXPECT_EQ(200, res->status);
  9164. EXPECT_EQ("ok", res->body);
  9165. svr.stop();
  9166. server_thread.join();
  9167. }
  9168. #endif
  9169. #ifdef _WIN32
  9170. TEST(CleanupTest, WSACleanup) {
  9171. int ret = WSACleanup();
  9172. ASSERT_EQ(0, ret);
  9173. }
  9174. #endif
  9175. #ifndef CPPHTTPLIB_SSL_ENABLED
  9176. TEST(NoSSLSupport, SimpleInterface) {
  9177. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9178. }
  9179. #endif
  9180. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9181. TEST(InvalidScheme, SimpleInterface) {
  9182. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9183. }
  9184. #endif
  9185. TEST(NoScheme, SimpleInterface) {
  9186. Client cli("yahoo.com:80");
  9187. ASSERT_TRUE(cli.is_valid());
  9188. }
  9189. TEST(SendAPI, SimpleInterface_Online) {
  9190. Client cli("http://yahoo.com");
  9191. Request req;
  9192. req.method = "GET";
  9193. req.path = "/";
  9194. auto res = cli.send(req);
  9195. ASSERT_TRUE(res);
  9196. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9197. }
  9198. TEST(SendAPI, WithParamsInRequest) {
  9199. Server svr;
  9200. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9201. EXPECT_TRUE(req.has_param("test"));
  9202. EXPECT_EQ("test_value", req.get_param_value("test"));
  9203. });
  9204. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9205. auto se = detail::scope_exit([&] {
  9206. svr.stop();
  9207. t.join();
  9208. ASSERT_FALSE(svr.is_running());
  9209. });
  9210. svr.wait_until_ready();
  9211. Client cli(HOST, PORT);
  9212. {
  9213. Request req;
  9214. req.method = "GET";
  9215. req.path = "/";
  9216. req.params.emplace("test", "test_value");
  9217. auto res = cli.send(req);
  9218. ASSERT_TRUE(res);
  9219. }
  9220. {
  9221. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9222. ASSERT_TRUE(res);
  9223. }
  9224. }
  9225. TEST(ClientImplMethods, GetSocketTest) {
  9226. httplib::Server svr;
  9227. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9228. res.status = StatusCode::OK_200;
  9229. });
  9230. auto port = svr.bind_to_any_port("127.0.0.1");
  9231. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9232. auto se = detail::scope_exit([&] {
  9233. svr.stop();
  9234. thread.join();
  9235. ASSERT_FALSE(svr.is_running());
  9236. });
  9237. svr.wait_until_ready();
  9238. {
  9239. httplib::Client cli("127.0.0.1", port);
  9240. cli.set_keep_alive(true);
  9241. // Use the behavior of cpp-httplib of opening the connection
  9242. // only when the first request happens. If that changes,
  9243. // this test would be obsolete.
  9244. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9245. // This also implicitly tests the server. But other tests would fail much
  9246. // earlier than this one to be considered.
  9247. auto res = cli.Get("/");
  9248. ASSERT_TRUE(res);
  9249. EXPECT_EQ(StatusCode::OK_200, res->status);
  9250. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9251. }
  9252. }
  9253. #ifdef CPPHTTPLIB_SSL_ENABLED
  9254. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9255. Client cli("http://yahoo.com");
  9256. auto res = cli.Get("/");
  9257. ASSERT_TRUE(res);
  9258. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9259. cli.set_follow_location(true);
  9260. res = cli.Get("/");
  9261. ASSERT_TRUE(res);
  9262. EXPECT_EQ(StatusCode::OK_200, res->status);
  9263. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9264. }
  9265. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9266. Client cli("https://yahoo.com");
  9267. auto res = cli.Get("/");
  9268. ASSERT_TRUE(res);
  9269. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9270. cli.set_follow_location(true);
  9271. res = cli.Get("/");
  9272. ASSERT_TRUE(res);
  9273. EXPECT_EQ(StatusCode::OK_200, res->status);
  9274. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9275. }
  9276. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9277. Client cli("https://yahoo.com");
  9278. auto res = cli.Get("/");
  9279. ASSERT_TRUE(res);
  9280. ASSERT_FALSE(!res);
  9281. ASSERT_TRUE(res);
  9282. ASSERT_FALSE(res == nullptr);
  9283. ASSERT_TRUE(res != nullptr);
  9284. EXPECT_EQ(Error::Success, res.error());
  9285. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9286. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9287. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9288. cli.set_follow_location(true);
  9289. res = cli.Get("/");
  9290. ASSERT_TRUE(res);
  9291. EXPECT_EQ(Error::Success, res.error());
  9292. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9293. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9294. EXPECT_EQ(StatusCode::OK_200, res->status);
  9295. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9296. }
  9297. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9298. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9299. Client cli("https://cdnjs.cloudflare.com");
  9300. auto res =
  9301. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9302. ASSERT_TRUE(res);
  9303. EXPECT_EQ(StatusCode::OK_200, res->status);
  9304. EXPECT_EQ(287630U, res->body.size());
  9305. EXPECT_EQ("application/javascript; charset=utf-8",
  9306. res->get_header_value("Content-Type"));
  9307. }
  9308. #endif
  9309. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9310. #undef REDIR_HOST // Silence compiler warning
  9311. #define REDIR_HOST "https://httpbingo.org"
  9312. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9313. Client cli(REDIR_HOST);
  9314. cli.set_follow_location(true);
  9315. auto res =
  9316. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9317. ASSERT_TRUE(res);
  9318. EXPECT_EQ(StatusCode::OK_200, res->status);
  9319. }
  9320. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9321. Client cli(REDIR_HOST);
  9322. cli.set_follow_location(true);
  9323. Params params;
  9324. params.emplace("url", "http://example.com");
  9325. params.emplace("status_code", "302");
  9326. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9327. ASSERT_TRUE(res);
  9328. EXPECT_EQ(StatusCode::OK_200, res->status);
  9329. }
  9330. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9331. Client cli(REDIR_HOST);
  9332. cli.set_follow_location(true);
  9333. Params params;
  9334. params.emplace("url", "http://example.com");
  9335. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9336. ASSERT_TRUE(res);
  9337. EXPECT_EQ(StatusCode::OK_200, res->status);
  9338. }
  9339. TEST(HttpToHttpsRedirectTest, CertFile) {
  9340. auto ssl_port = PORT + 1;
  9341. Server svr;
  9342. ASSERT_TRUE(svr.is_valid());
  9343. svr.Get("/index", [&](const Request &, Response &res) {
  9344. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9345. "/index");
  9346. svr.stop();
  9347. });
  9348. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9349. ASSERT_TRUE(ssl_svr.is_valid());
  9350. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9351. res.set_content("test", "text/plain");
  9352. ssl_svr.stop();
  9353. });
  9354. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9355. thread t2 =
  9356. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9357. auto se = detail::scope_exit([&] {
  9358. t2.join();
  9359. t.join();
  9360. ASSERT_FALSE(svr.is_running());
  9361. });
  9362. svr.wait_until_ready();
  9363. ssl_svr.wait_until_ready();
  9364. Client cli("127.0.0.1", PORT);
  9365. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9366. cli.enable_server_certificate_verification(true);
  9367. cli.set_follow_location(true);
  9368. cli.set_connection_timeout(30);
  9369. auto res = cli.Get("/index");
  9370. ASSERT_TRUE(res);
  9371. ASSERT_EQ(StatusCode::OK_200, res->status);
  9372. }
  9373. TEST(SSLClientRedirectTest, CertFile) {
  9374. auto ssl_port = PORT + 1;
  9375. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9376. ASSERT_TRUE(ssl_svr1.is_valid());
  9377. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9378. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9379. "/index");
  9380. ssl_svr1.stop();
  9381. });
  9382. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9383. ASSERT_TRUE(ssl_svr2.is_valid());
  9384. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9385. res.set_content("test", "text/plain");
  9386. ssl_svr2.stop();
  9387. });
  9388. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9389. thread t2 =
  9390. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9391. auto se = detail::scope_exit([&] {
  9392. t2.join();
  9393. t.join();
  9394. ASSERT_FALSE(ssl_svr1.is_running());
  9395. });
  9396. ssl_svr1.wait_until_ready();
  9397. ssl_svr2.wait_until_ready();
  9398. SSLClient cli("127.0.0.1", PORT);
  9399. std::string cert;
  9400. read_file(SERVER_CERT2_FILE, cert);
  9401. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9402. cli.enable_server_certificate_verification(true);
  9403. cli.set_follow_location(true);
  9404. cli.set_connection_timeout(30);
  9405. auto res = cli.Get("/index");
  9406. ASSERT_TRUE(res);
  9407. ASSERT_EQ(StatusCode::OK_200, res->status);
  9408. }
  9409. #endif
  9410. #ifdef CPPHTTPLIB_SSL_ENABLED
  9411. // Test that set_ca_cert_store() skips system certs (consistent with
  9412. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9413. // should be trusted - system certs should NOT be loaded.
  9414. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9415. // Load a specific cert that is NOT a system CA cert
  9416. std::string cert;
  9417. read_file(SERVER_CERT2_FILE, cert);
  9418. SSLClient cli("google.com");
  9419. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9420. cli.enable_server_certificate_verification(true);
  9421. // This should FAIL because:
  9422. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9423. // 2. System certs should NOT be loaded when custom store is set
  9424. // If system certs WERE loaded, this would succeed
  9425. auto res = cli.Get("/");
  9426. ASSERT_FALSE(res);
  9427. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9428. }
  9429. TEST(MultipartFormDataTest, LargeData) {
  9430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9431. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9432. const ContentReader &content_reader) {
  9433. if (req.is_multipart_form_data()) {
  9434. std::vector<FormData> items;
  9435. content_reader(
  9436. [&](const FormData &file) {
  9437. items.push_back(file);
  9438. return true;
  9439. },
  9440. [&](const char *data, size_t data_length) {
  9441. items.back().content.append(data, data_length);
  9442. return true;
  9443. });
  9444. EXPECT_TRUE(std::string(items[0].name) == "document");
  9445. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9446. EXPECT_TRUE(items[0].filename == "2MB_data");
  9447. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9448. EXPECT_TRUE(items[1].name == "hello");
  9449. EXPECT_TRUE(items[1].content == "world");
  9450. EXPECT_TRUE(items[1].filename == "");
  9451. EXPECT_TRUE(items[1].content_type == "");
  9452. } else {
  9453. std::string body;
  9454. content_reader([&](const char *data, size_t data_length) {
  9455. body.append(data, data_length);
  9456. return true;
  9457. });
  9458. }
  9459. });
  9460. auto port = svr.bind_to_any_port(HOST);
  9461. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. t.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. {
  9469. std::string data(1024 * 1024 * 2, '.');
  9470. std::stringstream buffer;
  9471. buffer << data;
  9472. SSLClient cli(HOST, port);
  9473. cli.enable_server_certificate_verification(false);
  9474. UploadFormDataItems items{
  9475. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9476. {"hello", "world", "", ""},
  9477. };
  9478. auto res = cli.Post("/post", items);
  9479. ASSERT_TRUE(res);
  9480. ASSERT_EQ(StatusCode::OK_200, res->status);
  9481. }
  9482. }
  9483. TEST(MultipartFormDataTest, DataProviderItems) {
  9484. std::random_device seed_gen;
  9485. std::mt19937 random(seed_gen());
  9486. std::string rand1;
  9487. rand1.resize(1000);
  9488. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9489. std::string rand2;
  9490. rand2.resize(3000);
  9491. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9493. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9494. const ContentReader &content_reader) {
  9495. ASSERT_FALSE(req.is_multipart_form_data());
  9496. std::string body;
  9497. content_reader([&](const char *data, size_t data_length) {
  9498. body.append(data, data_length);
  9499. return true;
  9500. });
  9501. EXPECT_EQ(body, "");
  9502. });
  9503. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9504. const ContentReader &content_reader) {
  9505. ASSERT_TRUE(req.is_multipart_form_data());
  9506. std::vector<FormData> items;
  9507. content_reader(
  9508. [&](const FormData &file) {
  9509. items.push_back(file);
  9510. return true;
  9511. },
  9512. [&](const char *data, size_t data_length) {
  9513. items.back().content.append(data, data_length);
  9514. return true;
  9515. });
  9516. ASSERT_TRUE(items.size() == 2);
  9517. EXPECT_EQ(std::string(items[0].name), "name1");
  9518. EXPECT_EQ(items[0].content, "Testing123");
  9519. EXPECT_EQ(items[0].filename, "filename1");
  9520. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9521. EXPECT_EQ(items[1].name, "name2");
  9522. EXPECT_EQ(items[1].content, "Testing456");
  9523. EXPECT_EQ(items[1].filename, "");
  9524. EXPECT_EQ(items[1].content_type, "");
  9525. });
  9526. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9527. const ContentReader &content_reader) {
  9528. ASSERT_TRUE(req.is_multipart_form_data());
  9529. std::vector<FormData> items;
  9530. content_reader(
  9531. [&](const FormData &file) {
  9532. items.push_back(file);
  9533. return true;
  9534. },
  9535. [&](const char *data, size_t data_length) {
  9536. items.back().content.append(data, data_length);
  9537. return true;
  9538. });
  9539. ASSERT_TRUE(items.size() == 2);
  9540. EXPECT_EQ(items[0].name, "name3");
  9541. EXPECT_EQ(items[0].content, rand1);
  9542. EXPECT_EQ(items[0].filename, "filename3");
  9543. EXPECT_EQ(items[0].content_type, "");
  9544. EXPECT_EQ(items[1].name, "name4");
  9545. EXPECT_EQ(items[1].content, rand2);
  9546. EXPECT_EQ(items[1].filename, "filename4");
  9547. EXPECT_EQ(items[1].content_type, "");
  9548. });
  9549. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9550. const ContentReader &content_reader) {
  9551. ASSERT_TRUE(req.is_multipart_form_data());
  9552. std::vector<FormData> items;
  9553. content_reader(
  9554. [&](const FormData &file) {
  9555. items.push_back(file);
  9556. return true;
  9557. },
  9558. [&](const char *data, size_t data_length) {
  9559. items.back().content.append(data, data_length);
  9560. return true;
  9561. });
  9562. ASSERT_TRUE(items.size() == 4);
  9563. EXPECT_EQ(std::string(items[0].name), "name1");
  9564. EXPECT_EQ(items[0].content, "Testing123");
  9565. EXPECT_EQ(items[0].filename, "filename1");
  9566. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9567. EXPECT_EQ(items[1].name, "name2");
  9568. EXPECT_EQ(items[1].content, "Testing456");
  9569. EXPECT_EQ(items[1].filename, "");
  9570. EXPECT_EQ(items[1].content_type, "");
  9571. EXPECT_EQ(items[2].name, "name3");
  9572. EXPECT_EQ(items[2].content, rand1);
  9573. EXPECT_EQ(items[2].filename, "filename3");
  9574. EXPECT_EQ(items[2].content_type, "");
  9575. EXPECT_EQ(items[3].name, "name4");
  9576. EXPECT_EQ(items[3].content, rand2);
  9577. EXPECT_EQ(items[3].filename, "filename4");
  9578. EXPECT_EQ(items[3].content_type, "");
  9579. });
  9580. auto port = svr.bind_to_any_port("localhost");
  9581. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9582. auto se = detail::scope_exit([&] {
  9583. svr.stop();
  9584. t.join();
  9585. ASSERT_FALSE(svr.is_running());
  9586. });
  9587. svr.wait_until_ready();
  9588. {
  9589. SSLClient cli("localhost", port);
  9590. cli.enable_server_certificate_verification(false);
  9591. UploadFormDataItems items{
  9592. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9593. {"name2", "Testing456", "", ""}, // not a file
  9594. };
  9595. {
  9596. auto res = cli.Post("/post-none", {}, {}, {});
  9597. ASSERT_TRUE(res);
  9598. ASSERT_EQ(StatusCode::OK_200, res->status);
  9599. }
  9600. FormDataProviderItems providers;
  9601. {
  9602. auto res =
  9603. cli.Post("/post-items", {}, items, providers); // empty providers
  9604. ASSERT_TRUE(res);
  9605. ASSERT_EQ(StatusCode::OK_200, res->status);
  9606. }
  9607. providers.push_back({"name3",
  9608. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9609. // test the offset is given correctly at each step
  9610. if (!offset)
  9611. sink.os.write(rand1.data(), 30);
  9612. else if (offset == 30)
  9613. sink.os.write(rand1.data() + 30, 300);
  9614. else if (offset == 330)
  9615. sink.os.write(rand1.data() + 330, 670);
  9616. else if (offset == rand1.size())
  9617. sink.done();
  9618. return true;
  9619. },
  9620. "filename3",
  9621. {}});
  9622. providers.push_back({"name4",
  9623. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9624. // test the offset is given correctly at each step
  9625. if (!offset)
  9626. sink.os.write(rand2.data(), 2000);
  9627. else if (offset == 2000)
  9628. sink.os.write(rand2.data() + 2000, 1);
  9629. else if (offset == 2001)
  9630. sink.os.write(rand2.data() + 2001, 999);
  9631. else if (offset == rand2.size())
  9632. sink.done();
  9633. return true;
  9634. },
  9635. "filename4",
  9636. {}});
  9637. {
  9638. auto res = cli.Post("/post-providers", {}, {}, providers);
  9639. ASSERT_TRUE(res);
  9640. ASSERT_EQ(StatusCode::OK_200, res->status);
  9641. }
  9642. {
  9643. auto res = cli.Post("/post-both", {}, items, providers);
  9644. ASSERT_TRUE(res);
  9645. ASSERT_EQ(StatusCode::OK_200, res->status);
  9646. }
  9647. }
  9648. }
  9649. TEST(MultipartFormDataTest, BadHeader) {
  9650. Server svr;
  9651. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9652. res.set_content("ok", "text/plain");
  9653. });
  9654. thread t = thread([&] { svr.listen(HOST, PORT); });
  9655. auto se = detail::scope_exit([&] {
  9656. svr.stop();
  9657. t.join();
  9658. ASSERT_FALSE(svr.is_running());
  9659. });
  9660. svr.wait_until_ready();
  9661. const std::string body =
  9662. "This is the preamble. It is to be ignored, though it\r\n"
  9663. "is a handy place for composition agents to include an\r\n"
  9664. "explanatory note to non-MIME conformant readers.\r\n"
  9665. "\r\n"
  9666. "\r\n"
  9667. "--simple boundary\r\n"
  9668. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9669. ": BAD...\r\n"
  9670. "\r\n"
  9671. "value1\r\n"
  9672. "--simple boundary\r\n"
  9673. "Content-Disposition: form-data; name=\"field2\"; "
  9674. "filename=\"example.txt\"\r\n"
  9675. "\r\n"
  9676. "value2\r\n"
  9677. "--simple boundary--\r\n"
  9678. "This is the epilogue. It is also to be ignored.\r\n";
  9679. std::string content_type =
  9680. R"(multipart/form-data; boundary="simple boundary")";
  9681. Client cli(HOST, PORT);
  9682. auto res = cli.Post("/post", body, content_type.c_str());
  9683. ASSERT_TRUE(res);
  9684. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9685. }
  9686. TEST(MultipartFormDataTest, WithPreamble) {
  9687. Server svr;
  9688. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9689. res.set_content("ok", "text/plain");
  9690. });
  9691. thread t = thread([&] { svr.listen(HOST, PORT); });
  9692. auto se = detail::scope_exit([&] {
  9693. svr.stop();
  9694. t.join();
  9695. ASSERT_FALSE(svr.is_running());
  9696. });
  9697. svr.wait_until_ready();
  9698. const std::string body =
  9699. "This is the preamble. It is to be ignored, though it\r\n"
  9700. "is a handy place for composition agents to include an\r\n"
  9701. "explanatory note to non-MIME conformant readers.\r\n"
  9702. "\r\n"
  9703. "\r\n"
  9704. "--simple boundary\r\n"
  9705. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9706. "\r\n"
  9707. "value1\r\n"
  9708. "--simple boundary\r\n"
  9709. "Content-Disposition: form-data; name=\"field2\"; "
  9710. "filename=\"example.txt\"\r\n"
  9711. "\r\n"
  9712. "value2\r\n"
  9713. "--simple boundary--\r\n"
  9714. "This is the epilogue. It is also to be ignored.\r\n";
  9715. std::string content_type =
  9716. R"(multipart/form-data; boundary="simple boundary")";
  9717. Client cli(HOST, PORT);
  9718. auto res = cli.Post("/post", body, content_type.c_str());
  9719. ASSERT_TRUE(res);
  9720. EXPECT_EQ(StatusCode::OK_200, res->status);
  9721. }
  9722. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9724. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9725. const ContentReader &content_reader) {
  9726. if (req.is_multipart_form_data()) {
  9727. std::vector<FormData> items;
  9728. content_reader(
  9729. [&](const FormData &file) {
  9730. items.push_back(file);
  9731. return true;
  9732. },
  9733. [&](const char *data, size_t data_length) {
  9734. items.back().content.append(data, data_length);
  9735. return true;
  9736. });
  9737. EXPECT_TRUE(std::string(items[0].name) == "document");
  9738. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9739. EXPECT_TRUE(items[0].filename == "2MB_data");
  9740. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9741. EXPECT_TRUE(items[1].name == "hello");
  9742. EXPECT_TRUE(items[1].content == "world");
  9743. EXPECT_TRUE(items[1].filename == "");
  9744. EXPECT_TRUE(items[1].content_type == "");
  9745. } else {
  9746. std::string body;
  9747. content_reader([&](const char *data, size_t data_length) {
  9748. body.append(data, data_length);
  9749. return true;
  9750. });
  9751. }
  9752. });
  9753. auto port = svr.bind_to_any_port("localhost");
  9754. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9755. auto se = detail::scope_exit([&] {
  9756. svr.stop();
  9757. t.join();
  9758. ASSERT_FALSE(svr.is_running());
  9759. });
  9760. svr.wait_until_ready();
  9761. {
  9762. std::string data(1024 * 1024 * 2, '.');
  9763. std::stringstream buffer;
  9764. buffer << data;
  9765. SSLClient cli("localhost", port);
  9766. cli.enable_server_certificate_verification(false);
  9767. UploadFormDataItems items{
  9768. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9769. {"hello", "world", "", ""},
  9770. };
  9771. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9772. ASSERT_TRUE(res);
  9773. ASSERT_EQ(StatusCode::OK_200, res->status);
  9774. }
  9775. }
  9776. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9777. std::string data(1024 * 1024 * 2, '&');
  9778. std::stringstream buffer;
  9779. buffer << data;
  9780. Client cli("https://localhost:8080");
  9781. UploadFormDataItems items{
  9782. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9783. {"hello", "world", "", ""},
  9784. };
  9785. for (const char &c : " \t\r\n") {
  9786. auto res =
  9787. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9788. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9789. ASSERT_FALSE(res);
  9790. }
  9791. }
  9792. TEST(MultipartFormDataTest, PutFormData) {
  9793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9794. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9795. const ContentReader &content_reader) {
  9796. if (req.is_multipart_form_data()) {
  9797. std::vector<FormData> items;
  9798. content_reader(
  9799. [&](const FormData &file) {
  9800. items.push_back(file);
  9801. return true;
  9802. },
  9803. [&](const char *data, size_t data_length) {
  9804. items.back().content.append(data, data_length);
  9805. return true;
  9806. });
  9807. EXPECT_TRUE(std::string(items[0].name) == "document");
  9808. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9809. EXPECT_TRUE(items[0].filename == "2MB_data");
  9810. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9811. EXPECT_TRUE(items[1].name == "hello");
  9812. EXPECT_TRUE(items[1].content == "world");
  9813. EXPECT_TRUE(items[1].filename == "");
  9814. EXPECT_TRUE(items[1].content_type == "");
  9815. } else {
  9816. std::string body;
  9817. content_reader([&](const char *data, size_t data_length) {
  9818. body.append(data, data_length);
  9819. return true;
  9820. });
  9821. }
  9822. });
  9823. auto port = svr.bind_to_any_port("localhost");
  9824. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9825. auto se = detail::scope_exit([&] {
  9826. svr.stop();
  9827. t.join();
  9828. ASSERT_FALSE(svr.is_running());
  9829. });
  9830. svr.wait_until_ready();
  9831. {
  9832. std::string data(1024 * 1024 * 2, '&');
  9833. std::stringstream buffer;
  9834. buffer << data;
  9835. SSLClient cli("localhost", port);
  9836. cli.enable_server_certificate_verification(false);
  9837. UploadFormDataItems items{
  9838. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9839. {"hello", "world", "", ""},
  9840. };
  9841. auto res = cli.Put("/put", items);
  9842. ASSERT_TRUE(res);
  9843. ASSERT_EQ(StatusCode::OK_200, res->status);
  9844. }
  9845. }
  9846. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9848. svr.Put("/put_customboundary",
  9849. [&](const Request &req, const Response & /*res*/,
  9850. const ContentReader &content_reader) {
  9851. if (req.is_multipart_form_data()) {
  9852. std::vector<FormData> items;
  9853. content_reader(
  9854. [&](const FormData &file) {
  9855. items.push_back(file);
  9856. return true;
  9857. },
  9858. [&](const char *data, size_t data_length) {
  9859. items.back().content.append(data, data_length);
  9860. return true;
  9861. });
  9862. EXPECT_TRUE(std::string(items[0].name) == "document");
  9863. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9864. EXPECT_TRUE(items[0].filename == "2MB_data");
  9865. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9866. EXPECT_TRUE(items[1].name == "hello");
  9867. EXPECT_TRUE(items[1].content == "world");
  9868. EXPECT_TRUE(items[1].filename == "");
  9869. EXPECT_TRUE(items[1].content_type == "");
  9870. } else {
  9871. std::string body;
  9872. content_reader([&](const char *data, size_t data_length) {
  9873. body.append(data, data_length);
  9874. return true;
  9875. });
  9876. }
  9877. });
  9878. auto port = svr.bind_to_any_port("localhost");
  9879. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9880. auto se = detail::scope_exit([&] {
  9881. svr.stop();
  9882. t.join();
  9883. ASSERT_FALSE(svr.is_running());
  9884. });
  9885. svr.wait_until_ready();
  9886. {
  9887. std::string data(1024 * 1024 * 2, '&');
  9888. std::stringstream buffer;
  9889. buffer << data;
  9890. SSLClient cli("localhost", port);
  9891. cli.enable_server_certificate_verification(false);
  9892. UploadFormDataItems items{
  9893. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9894. {"hello", "world", "", ""},
  9895. };
  9896. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9897. ASSERT_TRUE(res);
  9898. ASSERT_EQ(StatusCode::OK_200, res->status);
  9899. }
  9900. }
  9901. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9902. std::string data(1024 * 1024 * 2, '&');
  9903. std::stringstream buffer;
  9904. buffer << data;
  9905. Client cli("https://localhost:8080");
  9906. cli.enable_server_certificate_verification(false);
  9907. UploadFormDataItems items{
  9908. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9909. {"hello", "world", "", ""},
  9910. };
  9911. for (const char &c : " \t\r\n") {
  9912. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9913. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9914. ASSERT_FALSE(res);
  9915. }
  9916. }
  9917. TEST(MultipartFormDataTest, AlternateFilename) {
  9918. auto handled = false;
  9919. Server svr;
  9920. svr.Post("/test", [&](const Request &req, Response &res) {
  9921. ASSERT_EQ(2u, req.form.files.size());
  9922. ASSERT_EQ(1u, req.form.fields.size());
  9923. // Test files
  9924. const auto &file1 = req.form.get_file("file1");
  9925. ASSERT_EQ("file1", file1.name);
  9926. ASSERT_EQ("A.txt", file1.filename);
  9927. ASSERT_EQ("text/plain", file1.content_type);
  9928. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9929. const auto &file2 = req.form.get_file("file2");
  9930. ASSERT_EQ("file2", file2.name);
  9931. ASSERT_EQ("a.html", file2.filename);
  9932. ASSERT_EQ("text/html", file2.content_type);
  9933. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9934. file2.content);
  9935. // Test text field
  9936. const auto &text = req.form.get_field("text");
  9937. ASSERT_EQ("text default", text);
  9938. res.set_content("ok", "text/plain");
  9939. handled = true;
  9940. });
  9941. thread t = thread([&] { svr.listen(HOST, PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. t.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. ASSERT_TRUE(handled);
  9947. });
  9948. svr.wait_until_ready();
  9949. auto req = "POST /test HTTP/1.1\r\n"
  9950. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9951. "Content-Length: 399\r\n"
  9952. "\r\n"
  9953. "----------\r\n"
  9954. "Content-Disposition: form-data; name=\"text\"\r\n"
  9955. "\r\n"
  9956. "text default\r\n"
  9957. "----------\r\n"
  9958. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9959. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9960. "Content-Type: text/plain\r\n"
  9961. "\r\n"
  9962. "Content of a.txt.\r\n"
  9963. "\r\n"
  9964. "----------\r\n"
  9965. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9966. "\"a.html\"\r\n"
  9967. "Content-Type: text/html\r\n"
  9968. "\r\n"
  9969. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9970. "\r\n"
  9971. "------------\r\n";
  9972. ASSERT_TRUE(send_request(1, req));
  9973. }
  9974. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9975. auto handled = false;
  9976. Server svr;
  9977. svr.Post("/test", [&](const Request &req, Response &res) {
  9978. // Case-insensitive "utf-8''" prefix with a long value
  9979. const auto &file = req.form.get_file("file1");
  9980. ASSERT_EQ("file1", file.name);
  9981. // 8000 chars exercises both the Content-Disposition parser and the
  9982. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9983. // Prior to the fix, std::regex_match on this header would cause O(N)
  9984. // stack recursion in libstdc++, leading to SIGSEGV.
  9985. std::string expected_filename(8000, 'A');
  9986. ASSERT_EQ(expected_filename, file.filename);
  9987. res.set_content("ok", "text/plain");
  9988. handled = true;
  9989. });
  9990. thread t = thread([&] { svr.listen(HOST, PORT); });
  9991. auto se = detail::scope_exit([&] {
  9992. svr.stop();
  9993. t.join();
  9994. ASSERT_FALSE(svr.is_running());
  9995. ASSERT_TRUE(handled);
  9996. });
  9997. svr.wait_until_ready();
  9998. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9999. // Regression test for GHSA-qq6v-r583-3h69
  10000. std::string long_filename(8000, 'A');
  10001. std::string body = "----------\r\n"
  10002. "Content-Disposition: form-data; name=\"file1\"; "
  10003. "filename*=\"Utf-8''" +
  10004. long_filename +
  10005. "\"\r\n"
  10006. "\r\n"
  10007. "hello\r\n"
  10008. "------------\r\n";
  10009. auto req = "POST /test HTTP/1.1\r\n"
  10010. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10011. "Content-Length: " +
  10012. std::to_string(body.size()) + "\r\n\r\n" + body;
  10013. ASSERT_TRUE(send_request(1, req));
  10014. }
  10015. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  10016. auto handled = false;
  10017. Server svr;
  10018. svr.Post("/test", [&](const Request &req, Response &) {
  10019. ASSERT_EQ(2u, req.form.fields.size());
  10020. const auto &text1 = req.form.get_field("text1");
  10021. ASSERT_EQ("text1", text1);
  10022. const auto &text2 = req.form.get_field("text2");
  10023. ASSERT_EQ("text2", text2);
  10024. handled = true;
  10025. });
  10026. thread t = thread([&] { svr.listen(HOST, PORT); });
  10027. auto se = detail::scope_exit([&] {
  10028. svr.stop();
  10029. t.join();
  10030. ASSERT_FALSE(svr.is_running());
  10031. ASSERT_TRUE(handled);
  10032. });
  10033. svr.wait_until_ready();
  10034. auto req = "POST /test HTTP/1.1\r\n"
  10035. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10036. "Content-Length: 146\r\n"
  10037. "\r\n----------\r\n"
  10038. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10039. "\r\n"
  10040. "text1"
  10041. "\r\n----------\r\n"
  10042. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10043. "\r\n"
  10044. "text2"
  10045. "\r\n------------";
  10046. std::string response;
  10047. ASSERT_TRUE(send_request(1, req, &response));
  10048. ASSERT_EQ("200", response.substr(9, 3));
  10049. }
  10050. TEST(MultipartFormDataTest, ContentLength) {
  10051. auto handled = false;
  10052. Server svr;
  10053. svr.Post("/test", [&](const Request &req, Response &) {
  10054. ASSERT_EQ(2u, req.form.fields.size());
  10055. const auto &text1 = req.form.get_field("text1");
  10056. ASSERT_EQ("text1", text1);
  10057. const auto &text2 = req.form.get_field("text2");
  10058. ASSERT_EQ("text2", text2);
  10059. handled = true;
  10060. });
  10061. thread t = thread([&] { svr.listen(HOST, PORT); });
  10062. auto se = detail::scope_exit([&] {
  10063. svr.stop();
  10064. t.join();
  10065. ASSERT_FALSE(svr.is_running());
  10066. ASSERT_TRUE(handled);
  10067. });
  10068. svr.wait_until_ready();
  10069. auto req = "POST /test HTTP/1.1\r\n"
  10070. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10071. "Content-Length: 167\r\n"
  10072. "\r\n----------\r\n"
  10073. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10074. "Content-Length: 5\r\n"
  10075. "\r\n"
  10076. "text1"
  10077. "\r\n----------\r\n"
  10078. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10079. "\r\n"
  10080. "text2"
  10081. "\r\n------------\r\n";
  10082. std::string response;
  10083. ASSERT_TRUE(send_request(1, req, &response));
  10084. ASSERT_EQ("200", response.substr(9, 3));
  10085. }
  10086. TEST(MultipartFormDataTest, AccessPartHeaders) {
  10087. auto handled = false;
  10088. Server svr;
  10089. svr.Post("/test", [&](const Request &req, Response &) {
  10090. ASSERT_EQ(2u, req.form.fields.size());
  10091. const auto &text1 = req.form.get_field("text1");
  10092. ASSERT_EQ("text1", text1);
  10093. // TODO: Add header access for text fields if needed
  10094. const auto &text2 = req.form.get_field("text2");
  10095. ASSERT_EQ("text2", text2);
  10096. // TODO: Header access for text fields needs to be implemented
  10097. // auto &headers = it->second.headers;
  10098. // ASSERT_EQ(3U, headers.size());
  10099. // auto custom_header = headers.find("x-whatever");
  10100. // ASSERT_TRUE(custom_header != headers.end());
  10101. // ASSERT_NE("customvalue", custom_header->second);
  10102. // ASSERT_EQ("CustomValue", custom_header->second);
  10103. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  10104. handled = true;
  10105. });
  10106. thread t = thread([&] { svr.listen(HOST, PORT); });
  10107. auto se = detail::scope_exit([&] {
  10108. svr.stop();
  10109. t.join();
  10110. ASSERT_FALSE(svr.is_running());
  10111. ASSERT_TRUE(handled);
  10112. });
  10113. svr.wait_until_ready();
  10114. auto req = "POST /test HTTP/1.1\r\n"
  10115. "Content-Type: multipart/form-data;boundary=--------\r\n"
  10116. "Content-Length: 232\r\n"
  10117. "\r\n----------\r\n"
  10118. "Content-Disposition: form-data; name=\"text1\"\r\n"
  10119. "Content-Length: 5\r\n"
  10120. "X-Test: 1\r\n"
  10121. "\r\n"
  10122. "text1"
  10123. "\r\n----------\r\n"
  10124. "Content-Disposition: form-data; name=\"text2\"\r\n"
  10125. "Content-Type: text/plain\r\n"
  10126. "X-Whatever: CustomValue\r\n"
  10127. "\r\n"
  10128. "text2"
  10129. "\r\n------------\r\n"
  10130. "That should be disregarded. Not even read";
  10131. std::string response;
  10132. ASSERT_TRUE(send_request(1, req, &response));
  10133. ASSERT_EQ("200", response.substr(9, 3));
  10134. }
  10135. TEST(MultipartFormDataTest, LargeHeader) {
  10136. auto handled = false;
  10137. Server svr;
  10138. svr.Post("/test", [&](const Request &req, Response &) {
  10139. ASSERT_EQ(1u, req.form.fields.size());
  10140. const auto &text = req.form.get_field("name1");
  10141. ASSERT_EQ("text1", text);
  10142. handled = true;
  10143. });
  10144. thread t = thread([&] { svr.listen(HOST, PORT); });
  10145. auto se = detail::scope_exit([&] {
  10146. svr.stop();
  10147. t.join();
  10148. ASSERT_FALSE(svr.is_running());
  10149. ASSERT_TRUE(handled);
  10150. });
  10151. svr.wait_until_ready();
  10152. auto boundary = std::string("cpp-httplib-multipart-data");
  10153. std::string content = "--" + boundary +
  10154. "\r\n"
  10155. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10156. "\r\n"
  10157. "text1\r\n"
  10158. "--" +
  10159. boundary + "--\r\n";
  10160. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10161. "Content-Type: multipart/form-data;boundary=" +
  10162. boundary +
  10163. "\r\n"
  10164. "Content-Length: " +
  10165. std::to_string(content.size()) +
  10166. "\r\n"
  10167. "Dummy-Header: ";
  10168. std::string header_suffix = "\r\n"
  10169. "\r\n";
  10170. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10171. size_t header_dummy_size =
  10172. read_buff_size -
  10173. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10174. auto header_dummy = std::string(header_dummy_size, '@');
  10175. auto req = header_prefix + header_dummy + header_suffix + content;
  10176. std::string response;
  10177. ASSERT_TRUE(send_request(1, req, &response));
  10178. ASSERT_EQ("200", response.substr(9, 3));
  10179. }
  10180. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10181. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10182. // (not chunked Transfer-Encoding) after the streaming refactor.
  10183. auto handled = false;
  10184. Server svr;
  10185. svr.Post("/upload", [&](const Request &req, Response &res) {
  10186. auto cl_it = req.headers.find("Content-Length");
  10187. EXPECT_TRUE(cl_it != req.headers.end());
  10188. auto te_it = req.headers.find("Transfer-Encoding");
  10189. EXPECT_TRUE(te_it == req.headers.end());
  10190. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10191. res.set_content("ok", "text/plain");
  10192. handled = true;
  10193. });
  10194. auto port = svr.bind_to_any_port(HOST);
  10195. auto t = thread([&] { svr.listen_after_bind(); });
  10196. auto se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. t.join();
  10199. ASSERT_FALSE(svr.is_running());
  10200. ASSERT_TRUE(handled);
  10201. });
  10202. svr.wait_until_ready();
  10203. UploadFormDataItems items = {
  10204. {"field1", "hello", "", "text/plain"},
  10205. {"file1", "world", "test.txt", "application/octet-stream"},
  10206. };
  10207. Client cli(HOST, port);
  10208. auto res = cli.Post("/upload", {}, items);
  10209. ASSERT_TRUE(res);
  10210. EXPECT_EQ(StatusCode::OK_200, res->status);
  10211. }
  10212. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10213. // Verify that make_multipart_content_provider coalesces many small segments
  10214. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10215. constexpr size_t kItemCount = 1000;
  10216. UploadFormDataItems items;
  10217. items.reserve(kItemCount);
  10218. for (size_t i = 0; i < kItemCount; i++) {
  10219. items.push_back(
  10220. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10221. }
  10222. const std::string boundary = "----test-boundary";
  10223. auto content_length = detail::get_multipart_content_length(items, boundary);
  10224. auto provider = detail::make_multipart_content_provider(items, boundary);
  10225. // Drive the provider the same way write_content_with_progress does
  10226. size_t write_count = 0;
  10227. size_t total_bytes = 0;
  10228. DataSink sink;
  10229. size_t offset = 0;
  10230. sink.write = [&](const char *d, size_t l) -> bool {
  10231. (void)d;
  10232. write_count++;
  10233. total_bytes += l;
  10234. offset += l;
  10235. return true;
  10236. };
  10237. sink.is_writable = []() -> bool { return true; };
  10238. while (offset < content_length) {
  10239. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10240. }
  10241. EXPECT_EQ(content_length, total_bytes);
  10242. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10243. // With buffering into 64KB blocks, write_count should be much smaller.
  10244. auto segment_count = 3 * kItemCount + 1;
  10245. EXPECT_LT(write_count, segment_count / 10);
  10246. }
  10247. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10248. // Integration test: send many UploadFormDataItems and verify the server
  10249. // receives all of them correctly (#2410).
  10250. constexpr size_t kItemCount = 500;
  10251. auto handled = false;
  10252. Server svr;
  10253. svr.Post("/upload", [&](const Request &req, Response &res) {
  10254. EXPECT_EQ(kItemCount, req.form.fields.size());
  10255. for (size_t i = 0; i < kItemCount; i++) {
  10256. auto key = "field" + std::to_string(i);
  10257. auto val = "value" + std::to_string(i);
  10258. auto it = req.form.fields.find(key);
  10259. if (it != req.form.fields.end()) {
  10260. EXPECT_EQ(val, it->second.content);
  10261. } else {
  10262. ADD_FAILURE() << "Missing field: " << key;
  10263. }
  10264. }
  10265. res.set_content("ok", "text/plain");
  10266. handled = true;
  10267. });
  10268. auto port = svr.bind_to_any_port(HOST);
  10269. auto t = thread([&] { svr.listen_after_bind(); });
  10270. auto se = detail::scope_exit([&] {
  10271. svr.stop();
  10272. t.join();
  10273. ASSERT_FALSE(svr.is_running());
  10274. ASSERT_TRUE(handled);
  10275. });
  10276. svr.wait_until_ready();
  10277. UploadFormDataItems items;
  10278. items.reserve(kItemCount);
  10279. for (size_t i = 0; i < kItemCount; i++) {
  10280. items.push_back(
  10281. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10282. }
  10283. Client cli(HOST, port);
  10284. auto res = cli.Post("/upload", items);
  10285. ASSERT_TRUE(res);
  10286. EXPECT_EQ(StatusCode::OK_200, res->status);
  10287. }
  10288. TEST(MultipartFormDataTest, MakeFileProvider) {
  10289. // Verify make_file_provider sends a file's contents correctly.
  10290. const std::string file_content(4096, 'Z');
  10291. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  10292. {
  10293. std::ofstream ofs(tmp_path, std::ios::binary);
  10294. ofs.write(file_content.data(),
  10295. static_cast<std::streamsize>(file_content.size()));
  10296. }
  10297. auto handled = false;
  10298. Server svr;
  10299. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10300. const ContentReader &content_reader) {
  10301. ASSERT_TRUE(req.is_multipart_form_data());
  10302. std::vector<FormData> items;
  10303. content_reader(
  10304. [&](const FormData &file) {
  10305. items.push_back(file);
  10306. return true;
  10307. },
  10308. [&](const char *data, size_t data_length) {
  10309. items.back().content.append(data, data_length);
  10310. return true;
  10311. });
  10312. ASSERT_EQ(1u, items.size());
  10313. EXPECT_EQ("myfile", items[0].name);
  10314. EXPECT_EQ("data.bin", items[0].filename);
  10315. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10316. EXPECT_EQ(file_content, items[0].content);
  10317. handled = true;
  10318. });
  10319. auto port = svr.bind_to_any_port(HOST);
  10320. auto t = thread([&] { svr.listen_after_bind(); });
  10321. auto se = detail::scope_exit([&] {
  10322. svr.stop();
  10323. t.join();
  10324. ASSERT_FALSE(svr.is_running());
  10325. ASSERT_TRUE(handled);
  10326. std::remove(tmp_path.c_str());
  10327. });
  10328. svr.wait_until_ready();
  10329. FormDataProviderItems providers;
  10330. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10331. "application/octet-stream"));
  10332. Client cli(HOST, port);
  10333. auto res = cli.Post("/upload", {}, {}, providers);
  10334. ASSERT_TRUE(res);
  10335. EXPECT_EQ(StatusCode::OK_200, res->status);
  10336. }
  10337. TEST(MakeFileBodyTest, Basic) {
  10338. const std::string file_content(4096, 'Z');
  10339. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  10340. {
  10341. std::ofstream ofs(tmp_path, std::ios::binary);
  10342. ofs.write(file_content.data(),
  10343. static_cast<std::streamsize>(file_content.size()));
  10344. }
  10345. auto handled = false;
  10346. Server svr;
  10347. svr.Post("/upload", [&](const Request &req, Response &res) {
  10348. EXPECT_EQ(file_content, req.body);
  10349. handled = true;
  10350. res.status = StatusCode::OK_200;
  10351. });
  10352. auto port = svr.bind_to_any_port(HOST);
  10353. auto t = thread([&] { svr.listen_after_bind(); });
  10354. auto se = detail::scope_exit([&] {
  10355. svr.stop();
  10356. t.join();
  10357. ASSERT_FALSE(svr.is_running());
  10358. ASSERT_TRUE(handled);
  10359. std::remove(tmp_path.c_str());
  10360. });
  10361. svr.wait_until_ready();
  10362. auto fb = make_file_body(tmp_path);
  10363. ASSERT_GT(fb.first, 0u);
  10364. Client cli(HOST, port);
  10365. auto res =
  10366. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10367. ASSERT_TRUE(res);
  10368. EXPECT_EQ(StatusCode::OK_200, res->status);
  10369. }
  10370. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10371. static constexpr unsigned int number_of_tasks{1000000};
  10372. std::atomic_uint count{0};
  10373. std::unique_ptr<TaskQueue> task_queue{
  10374. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10375. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10376. auto queued = task_queue->enqueue(
  10377. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10378. EXPECT_TRUE(queued);
  10379. }
  10380. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10381. task_queue->shutdown();
  10382. #else
  10383. EXPECT_NO_THROW(task_queue->shutdown());
  10384. #endif
  10385. EXPECT_EQ(number_of_tasks, count.load());
  10386. }
  10387. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10388. static constexpr unsigned int number_of_tasks{1000000};
  10389. static constexpr unsigned int qlimit{2};
  10390. unsigned int queued_count{0};
  10391. std::atomic_uint count{0};
  10392. std::unique_ptr<TaskQueue> task_queue{
  10393. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10394. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10395. if (task_queue->enqueue(
  10396. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10397. queued_count++;
  10398. }
  10399. }
  10400. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10401. task_queue->shutdown();
  10402. #else
  10403. EXPECT_NO_THROW(task_queue->shutdown());
  10404. #endif
  10405. EXPECT_EQ(queued_count, count.load());
  10406. EXPECT_TRUE(queued_count <= number_of_tasks);
  10407. EXPECT_TRUE(queued_count >= qlimit);
  10408. }
  10409. TEST(TaskQueueTest, MaxQueuedRequests) {
  10410. static constexpr unsigned int qlimit{3};
  10411. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10412. std::condition_variable sem_cv;
  10413. std::mutex sem_mtx;
  10414. int credits = 0;
  10415. bool queued;
  10416. /* Fill up the queue with tasks that will block until we give them credits to
  10417. * complete. */
  10418. for (unsigned int n = 0; n <= qlimit;) {
  10419. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10420. std::unique_lock<std::mutex> lock(sem_mtx);
  10421. while (credits <= 0) {
  10422. sem_cv.wait(lock);
  10423. }
  10424. /* Consume the credit and signal the test code if they are all gone. */
  10425. if (--credits == 0) { sem_cv.notify_one(); }
  10426. });
  10427. if (n < qlimit) {
  10428. /* The first qlimit enqueues must succeed. */
  10429. EXPECT_TRUE(queued);
  10430. } else {
  10431. /* The last one will succeed only when the worker thread
  10432. * starts and dequeues the first blocking task. Although
  10433. * not necessary for the correctness of this test, we sleep for
  10434. * a short while to avoid busy waiting. */
  10435. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10436. }
  10437. if (queued) { n++; }
  10438. }
  10439. /* Further enqueues must fail since the queue is full. */
  10440. for (auto i = 0; i < 4; i++) {
  10441. queued = task_queue->enqueue([] {});
  10442. EXPECT_FALSE(queued);
  10443. }
  10444. /* Give the credits to allow the previous tasks to complete. */
  10445. {
  10446. std::unique_lock<std::mutex> lock(sem_mtx);
  10447. credits += qlimit + 1;
  10448. }
  10449. sem_cv.notify_all();
  10450. /* Wait for all the credits to be consumed. */
  10451. {
  10452. std::unique_lock<std::mutex> lock(sem_mtx);
  10453. while (credits > 0) {
  10454. sem_cv.wait(lock);
  10455. }
  10456. }
  10457. /* Check that we are able again to enqueue at least qlimit tasks. */
  10458. for (unsigned int i = 0; i < qlimit; i++) {
  10459. queued = task_queue->enqueue([] {});
  10460. EXPECT_TRUE(queued);
  10461. }
  10462. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10463. task_queue->shutdown();
  10464. #else
  10465. EXPECT_NO_THROW(task_queue->shutdown());
  10466. #endif
  10467. }
  10468. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10469. Server svr;
  10470. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10471. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10472. });
  10473. svr.Get("/hello", [](const Request &req, Response &res) {
  10474. res.set_content(req.get_param_value("key"), "text/plain");
  10475. });
  10476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10477. auto se = detail::scope_exit([&] {
  10478. svr.stop();
  10479. thread.join();
  10480. ASSERT_FALSE(svr.is_running());
  10481. });
  10482. svr.wait_until_ready();
  10483. {
  10484. Client cli(HOST, PORT);
  10485. cli.set_follow_location(true);
  10486. auto res = cli.Get("/");
  10487. ASSERT_TRUE(res);
  10488. EXPECT_EQ(StatusCode::OK_200, res->status);
  10489. EXPECT_EQ("val&key2=val2", res->body);
  10490. }
  10491. }
  10492. #endif
  10493. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10494. Server svr;
  10495. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10496. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10497. });
  10498. svr.Get("/hello", [](const Request &req, Response &res) {
  10499. res.set_content(req.get_param_value("key"), "text/plain");
  10500. });
  10501. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10502. auto se = detail::scope_exit([&] {
  10503. svr.stop();
  10504. thread.join();
  10505. ASSERT_FALSE(svr.is_running());
  10506. });
  10507. svr.wait_until_ready();
  10508. {
  10509. Client cli(HOST, PORT);
  10510. cli.set_follow_location(true);
  10511. auto res = cli.Get("/");
  10512. ASSERT_TRUE(res);
  10513. EXPECT_EQ(StatusCode::OK_200, res->status);
  10514. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10515. }
  10516. }
  10517. TEST(RedirectTest, RedirectWithPlusInPath) {
  10518. Server svr;
  10519. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10520. res.set_redirect("/a+b");
  10521. });
  10522. // Route pattern uses regex; escape + as \\+
  10523. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10524. res.set_content(req.path, "text/plain");
  10525. });
  10526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10527. auto se = detail::scope_exit([&] {
  10528. svr.stop();
  10529. thread.join();
  10530. ASSERT_FALSE(svr.is_running());
  10531. });
  10532. svr.wait_until_ready();
  10533. {
  10534. Client cli(HOST, PORT);
  10535. cli.set_follow_location(true);
  10536. auto res = cli.Get("/");
  10537. ASSERT_TRUE(res);
  10538. EXPECT_EQ(StatusCode::OK_200, res->status);
  10539. EXPECT_EQ("/a+b", res->body);
  10540. }
  10541. }
  10542. #ifdef CPPHTTPLIB_SSL_ENABLED
  10543. TEST(RedirectTest, Issue2185_Online) {
  10544. SSLClient client("github.com");
  10545. client.set_follow_location(true);
  10546. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10547. "Coollab-Windows.zip");
  10548. ASSERT_TRUE(res);
  10549. EXPECT_EQ(StatusCode::OK_200, res->status);
  10550. EXPECT_EQ(9920427U, res->body.size());
  10551. }
  10552. #endif
  10553. TEST(VulnerabilityTest, CRLFInjection) {
  10554. Server svr;
  10555. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10556. res.set_content("Hello 1", "text/plain");
  10557. });
  10558. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10559. res.set_content("Hello 2", "text/plain");
  10560. });
  10561. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10562. res.set_content("Hello 3", "text/plain");
  10563. });
  10564. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10565. res.set_content("Hello 4", "text/plain");
  10566. });
  10567. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10568. for (const auto &x : req.headers) {
  10569. auto key = x.first;
  10570. EXPECT_STRNE("evil", key.c_str());
  10571. }
  10572. });
  10573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10574. auto se = detail::scope_exit([&] {
  10575. svr.stop();
  10576. thread.join();
  10577. ASSERT_FALSE(svr.is_running());
  10578. });
  10579. svr.wait_until_ready();
  10580. {
  10581. Client cli(HOST, PORT);
  10582. cli.Post("/test1", "A=B",
  10583. "application/x-www-form-urlencoded\r\nevil: hello1");
  10584. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10585. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10586. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10587. }
  10588. }
  10589. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10590. auto server_thread = std::thread([] {
  10591. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10592. default_socket_options(srv);
  10593. sockaddr_in addr{};
  10594. addr.sin_family = AF_INET;
  10595. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10596. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10597. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10598. ::listen(srv, 1);
  10599. sockaddr_in cli_addr{};
  10600. socklen_t cli_len = sizeof(cli_addr);
  10601. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10602. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10603. std::string buf_all;
  10604. char buf[2048];
  10605. ssize_t n;
  10606. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10607. buf_all.append(buf, static_cast<size_t>(n));
  10608. size_t pos;
  10609. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10610. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10611. auto e = request_block.find("\r\n");
  10612. if (e != std::string::npos) {
  10613. auto request_line = request_block.substr(0, e);
  10614. std::string msg =
  10615. "CRLF injection detected in request line: '" + request_line + "'";
  10616. EXPECT_FALSE(true) << msg;
  10617. }
  10618. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10619. ::send(cli,
  10620. #ifdef _WIN32
  10621. static_cast<const char *>(resp.c_str()),
  10622. static_cast<int>(resp.size()),
  10623. #else
  10624. resp.c_str(), resp.size(),
  10625. #endif
  10626. 0);
  10627. buf_all.erase(0, pos + 4);
  10628. }
  10629. }
  10630. detail::close_socket(cli);
  10631. detail::close_socket(srv);
  10632. });
  10633. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10634. auto cli = Client("127.0.0.1", PORT + 1);
  10635. auto headers = Headers{
  10636. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10637. {"Connection", "keep-alive"}};
  10638. auto res = cli.Get("/hi", headers);
  10639. EXPECT_FALSE(res);
  10640. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10641. server_thread.join();
  10642. }
  10643. TEST(PathParamsTest, StaticMatch) {
  10644. const auto pattern = "/users/all";
  10645. detail::PathParamsMatcher matcher(pattern);
  10646. Request request;
  10647. request.path = "/users/all";
  10648. ASSERT_TRUE(matcher.match(request));
  10649. std::unordered_map<std::string, std::string> expected_params = {};
  10650. EXPECT_EQ(request.path_params, expected_params);
  10651. }
  10652. TEST(PathParamsTest, StaticMismatch) {
  10653. const auto pattern = "/users/all";
  10654. detail::PathParamsMatcher matcher(pattern);
  10655. Request request;
  10656. request.path = "/users/1";
  10657. ASSERT_FALSE(matcher.match(request));
  10658. }
  10659. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10660. const auto pattern = "/users/:id/subscriptions";
  10661. detail::PathParamsMatcher matcher(pattern);
  10662. Request request;
  10663. request.path = "/users/42/subscriptions";
  10664. ASSERT_TRUE(matcher.match(request));
  10665. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10666. EXPECT_EQ(request.path_params, expected_params);
  10667. }
  10668. TEST(PathParamsTest, SingleParamInTheEnd) {
  10669. const auto pattern = "/users/:id";
  10670. detail::PathParamsMatcher matcher(pattern);
  10671. Request request;
  10672. request.path = "/users/24";
  10673. ASSERT_TRUE(matcher.match(request));
  10674. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10675. EXPECT_EQ(request.path_params, expected_params);
  10676. }
  10677. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10678. const auto pattern = "/users/:id/";
  10679. detail::PathParamsMatcher matcher(pattern);
  10680. Request request;
  10681. request.path = "/users/42/";
  10682. ASSERT_TRUE(matcher.match(request));
  10683. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10684. EXPECT_EQ(request.path_params, expected_params);
  10685. }
  10686. TEST(PathParamsTest, EmptyParam) {
  10687. const auto pattern = "/users/:id/";
  10688. detail::PathParamsMatcher matcher(pattern);
  10689. Request request;
  10690. request.path = "/users//";
  10691. ASSERT_TRUE(matcher.match(request));
  10692. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10693. EXPECT_EQ(request.path_params, expected_params);
  10694. }
  10695. TEST(PathParamsTest, FragmentMismatch) {
  10696. const auto pattern = "/users/:id/";
  10697. detail::PathParamsMatcher matcher(pattern);
  10698. Request request;
  10699. request.path = "/admins/24/";
  10700. ASSERT_FALSE(matcher.match(request));
  10701. }
  10702. TEST(PathParamsTest, ExtraFragments) {
  10703. const auto pattern = "/users/:id";
  10704. detail::PathParamsMatcher matcher(pattern);
  10705. Request request;
  10706. request.path = "/users/42/subscriptions";
  10707. ASSERT_FALSE(matcher.match(request));
  10708. }
  10709. TEST(PathParamsTest, MissingTrailingParam) {
  10710. const auto pattern = "/users/:id";
  10711. detail::PathParamsMatcher matcher(pattern);
  10712. Request request;
  10713. request.path = "/users";
  10714. ASSERT_FALSE(matcher.match(request));
  10715. }
  10716. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10717. const auto pattern = "/users/:id/subscriptions";
  10718. detail::PathParamsMatcher matcher(pattern);
  10719. Request request;
  10720. request.path = "/users/subscriptions";
  10721. ASSERT_FALSE(matcher.match(request));
  10722. }
  10723. TEST(PathParamsTest, MultipleParams) {
  10724. const auto pattern = "/users/:userid/subscriptions/:subid";
  10725. detail::PathParamsMatcher matcher(pattern);
  10726. Request request;
  10727. request.path = "/users/42/subscriptions/2";
  10728. ASSERT_TRUE(matcher.match(request));
  10729. std::unordered_map<std::string, std::string> expected_params = {
  10730. {"userid", "42"}, {"subid", "2"}};
  10731. EXPECT_EQ(request.path_params, expected_params);
  10732. }
  10733. TEST(PathParamsTest, SequenceOfParams) {
  10734. const auto pattern = "/values/:x/:y/:z";
  10735. detail::PathParamsMatcher matcher(pattern);
  10736. Request request;
  10737. request.path = "/values/1/2/3";
  10738. ASSERT_TRUE(matcher.match(request));
  10739. std::unordered_map<std::string, std::string> expected_params = {
  10740. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10741. EXPECT_EQ(request.path_params, expected_params);
  10742. }
  10743. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10744. const auto pattern = "/prefix:suffix";
  10745. detail::PathParamsMatcher matcher(pattern);
  10746. Request request;
  10747. request.path = "/prefix:suffix";
  10748. ASSERT_TRUE(matcher.match(request));
  10749. const std::unordered_map<std::string, std::string> expected_params = {};
  10750. EXPECT_EQ(request.path_params, expected_params);
  10751. }
  10752. TEST(ParseUrlTest, VariousPatterns) {
  10753. {
  10754. detail::UrlComponents uc;
  10755. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10756. EXPECT_EQ("http", uc.scheme);
  10757. EXPECT_EQ("example.com", uc.host);
  10758. EXPECT_EQ("8080", uc.port);
  10759. EXPECT_EQ("/path", uc.path);
  10760. EXPECT_EQ("?q=1", uc.query);
  10761. }
  10762. {
  10763. detail::UrlComponents uc;
  10764. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10765. EXPECT_EQ("https", uc.scheme);
  10766. EXPECT_EQ("example.com", uc.host);
  10767. EXPECT_TRUE(uc.port.empty());
  10768. EXPECT_EQ("/path", uc.path);
  10769. }
  10770. {
  10771. detail::UrlComponents uc;
  10772. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10773. EXPECT_EQ("::1", uc.host);
  10774. EXPECT_EQ("8080", uc.port);
  10775. EXPECT_EQ("/path", uc.path);
  10776. }
  10777. {
  10778. detail::UrlComponents uc;
  10779. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10780. }
  10781. {
  10782. detail::UrlComponents uc;
  10783. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10784. EXPECT_TRUE(uc.scheme.empty());
  10785. EXPECT_EQ("example.com", uc.host);
  10786. EXPECT_EQ("/path", uc.path);
  10787. EXPECT_EQ("?q=1", uc.query);
  10788. }
  10789. {
  10790. detail::UrlComponents uc;
  10791. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10792. EXPECT_TRUE(uc.host.empty());
  10793. EXPECT_EQ("/path", uc.path);
  10794. EXPECT_EQ("?q=1", uc.query);
  10795. }
  10796. {
  10797. detail::UrlComponents uc;
  10798. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10799. EXPECT_EQ("example.com", uc.host);
  10800. EXPECT_EQ("8080", uc.port);
  10801. }
  10802. {
  10803. // Unix socket path — must not be parsed as host
  10804. detail::UrlComponents uc;
  10805. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  10806. EXPECT_TRUE(uc.host.empty());
  10807. }
  10808. {
  10809. detail::UrlComponents uc;
  10810. ASSERT_TRUE(detail::parse_url("", uc));
  10811. EXPECT_TRUE(uc.host.empty());
  10812. EXPECT_TRUE(uc.path.empty());
  10813. }
  10814. {
  10815. detail::UrlComponents uc;
  10816. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  10817. }
  10818. {
  10819. detail::UrlComponents uc;
  10820. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  10821. }
  10822. {
  10823. // Accepted by parse_url; callers restrict to http/https
  10824. detail::UrlComponents uc;
  10825. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  10826. EXPECT_EQ("ftp", uc.scheme);
  10827. }
  10828. {
  10829. detail::UrlComponents uc;
  10830. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  10831. }
  10832. {
  10833. detail::UrlComponents uc;
  10834. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  10835. }
  10836. }
  10837. TEST(ParseUrlTest, FragmentHandling) {
  10838. {
  10839. detail::UrlComponents uc;
  10840. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  10841. EXPECT_EQ("/path", uc.path);
  10842. EXPECT_TRUE(uc.query.empty());
  10843. }
  10844. {
  10845. detail::UrlComponents uc;
  10846. ASSERT_TRUE(detail::parse_url("#frag", uc));
  10847. EXPECT_TRUE(uc.path.empty());
  10848. EXPECT_TRUE(uc.query.empty());
  10849. }
  10850. }
  10851. TEST(ParseUrlTest, UserinfoHandling) {
  10852. // Userinfo with @ but no colon — host includes @
  10853. detail::UrlComponents uc;
  10854. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  10855. EXPECT_EQ("user@host.com", uc.host);
  10856. EXPECT_EQ("/path", uc.path);
  10857. }
  10858. TEST(ParseUrlTest, IPv6EdgeCases) {
  10859. {
  10860. detail::UrlComponents uc;
  10861. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  10862. EXPECT_TRUE(uc.scheme.empty());
  10863. EXPECT_EQ("::1", uc.host);
  10864. EXPECT_EQ("8080", uc.port);
  10865. }
  10866. {
  10867. // Zone ID '%25' is not in [a-fA-F0-9:]
  10868. detail::UrlComponents uc;
  10869. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  10870. }
  10871. }
  10872. TEST(ParseUrlTest, SchemeEdgeCases) {
  10873. {
  10874. detail::UrlComponents uc;
  10875. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  10876. }
  10877. {
  10878. detail::UrlComponents uc;
  10879. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  10880. }
  10881. {
  10882. detail::UrlComponents uc;
  10883. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  10884. }
  10885. }
  10886. TEST(ParseUrlTest, PortEdgeCases) {
  10887. {
  10888. detail::UrlComponents uc;
  10889. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  10890. EXPECT_TRUE(uc.port.empty());
  10891. EXPECT_EQ("/path", uc.path);
  10892. }
  10893. {
  10894. // parse_url accepts any port string; validation is done by parse_port
  10895. detail::UrlComponents uc;
  10896. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  10897. EXPECT_EQ("abc", uc.port);
  10898. }
  10899. }
  10900. TEST(ParseUrlTest, WebSocketPatterns) {
  10901. {
  10902. detail::UrlComponents uc;
  10903. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  10904. EXPECT_EQ("ws", uc.scheme);
  10905. EXPECT_EQ("echo.example.com", uc.host);
  10906. EXPECT_EQ("8080", uc.port);
  10907. EXPECT_EQ("/ws", uc.path);
  10908. }
  10909. {
  10910. detail::UrlComponents uc;
  10911. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  10912. EXPECT_EQ("wss", uc.scheme);
  10913. EXPECT_EQ("echo.example.com", uc.host);
  10914. EXPECT_TRUE(uc.port.empty());
  10915. EXPECT_EQ("/ws", uc.path);
  10916. }
  10917. }
  10918. TEST(ParseUrlTest, QueryOnly) {
  10919. detail::UrlComponents uc;
  10920. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  10921. EXPECT_TRUE(uc.host.empty());
  10922. EXPECT_TRUE(uc.path.empty());
  10923. EXPECT_EQ("?q=1&r=2", uc.query);
  10924. }
  10925. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  10926. detail::UrlComponents uc;
  10927. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  10928. EXPECT_TRUE(uc.scheme.empty());
  10929. EXPECT_EQ("example.com", uc.host);
  10930. EXPECT_EQ("443", uc.port);
  10931. EXPECT_EQ("/path", uc.path);
  10932. }
  10933. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10934. // If ipv6 regex working, regex match codepath is taken.
  10935. // else port will default to 80 in Client impl
  10936. int clientImplMagicPort = 80;
  10937. int port = 4321;
  10938. // above ports must be different to avoid false negative
  10939. EXPECT_NE(clientImplMagicPort, port);
  10940. std::string ipV6TestURL = "http://[ff06::c3]";
  10941. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10942. CLIENT_PRIVATE_KEY_FILE);
  10943. EXPECT_EQ(cli.port(), port);
  10944. }
  10945. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10946. auto file_path = "./www/dir/index.html";
  10947. auto dir_path = "./www/dir";
  10948. detail::FileStat stat_file(file_path);
  10949. EXPECT_TRUE(stat_file.is_file());
  10950. EXPECT_FALSE(stat_file.is_dir());
  10951. detail::FileStat stat_dir(dir_path);
  10952. EXPECT_FALSE(stat_dir.is_file());
  10953. EXPECT_TRUE(stat_dir.is_dir());
  10954. }
  10955. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10956. // IPv4 with default HTTP port (80)
  10957. EXPECT_EQ("example.com",
  10958. detail::make_host_and_port_string("example.com", 80, false));
  10959. // IPv4 with default HTTPS port (443)
  10960. EXPECT_EQ("example.com",
  10961. detail::make_host_and_port_string("example.com", 443, true));
  10962. // IPv4 with non-default HTTP port
  10963. EXPECT_EQ("example.com:8080",
  10964. detail::make_host_and_port_string("example.com", 8080, false));
  10965. // IPv4 with non-default HTTPS port
  10966. EXPECT_EQ("example.com:8443",
  10967. detail::make_host_and_port_string("example.com", 8443, true));
  10968. // IPv6 with default HTTP port (80)
  10969. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10970. // IPv6 with default HTTPS port (443)
  10971. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10972. // IPv6 with non-default HTTP port
  10973. EXPECT_EQ("[::1]:8080",
  10974. detail::make_host_and_port_string("::1", 8080, false));
  10975. // IPv6 with non-default HTTPS port
  10976. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10977. // IPv6 full address with default port
  10978. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10979. detail::make_host_and_port_string(
  10980. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10981. // IPv6 full address with non-default port
  10982. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10983. detail::make_host_and_port_string(
  10984. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10985. // IPv6 localhost with non-default port
  10986. EXPECT_EQ("[::1]:3000",
  10987. detail::make_host_and_port_string("::1", 3000, false));
  10988. // IPv6 with zone ID (link-local address) with default port
  10989. EXPECT_EQ("[fe80::1%eth0]",
  10990. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10991. // IPv6 with zone ID (link-local address) with non-default port
  10992. EXPECT_EQ("[fe80::1%eth0]:8080",
  10993. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10994. // Edge case: Port 443 with is_ssl=false (should add port)
  10995. EXPECT_EQ("example.com:443",
  10996. detail::make_host_and_port_string("example.com", 443, false));
  10997. // Edge case: Port 80 with is_ssl=true (should add port)
  10998. EXPECT_EQ("example.com:80",
  10999. detail::make_host_and_port_string("example.com", 80, true));
  11000. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  11001. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  11002. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  11003. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  11004. // Security fix: Already bracketed IPv6 should not get double brackets
  11005. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  11006. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  11007. EXPECT_EQ("[::1]:8080",
  11008. detail::make_host_and_port_string("[::1]", 8080, false));
  11009. EXPECT_EQ("[2001:db8::1]:8080",
  11010. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  11011. EXPECT_EQ("[fe80::1%eth0]",
  11012. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  11013. EXPECT_EQ("[fe80::1%eth0]:8080",
  11014. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  11015. // Edge case: Empty host (should return as-is)
  11016. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  11017. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  11018. // This is a known limitation but shouldn't crash
  11019. EXPECT_EQ("[host:name]",
  11020. detail::make_host_and_port_string("host:name", 80, false));
  11021. // Port number edge cases (no validation, but should not crash)
  11022. EXPECT_EQ("example.com:0",
  11023. detail::make_host_and_port_string("example.com", 0, false));
  11024. EXPECT_EQ("example.com:-1",
  11025. detail::make_host_and_port_string("example.com", -1, false));
  11026. EXPECT_EQ("example.com:65535",
  11027. detail::make_host_and_port_string("example.com", 65535, false));
  11028. EXPECT_EQ("example.com:65536",
  11029. detail::make_host_and_port_string("example.com", 65536, false));
  11030. }
  11031. #ifdef CPPHTTPLIB_SSL_ENABLED
  11032. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  11033. httplib::SSLClient cli("roblox.com", 443);
  11034. cli.set_follow_location(true);
  11035. auto res = cli.Get("/");
  11036. ASSERT_TRUE(res);
  11037. EXPECT_EQ(StatusCode::OK_200, res->status);
  11038. }
  11039. #endif
  11040. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  11041. Server svr;
  11042. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  11043. EXPECT_EQ(res.status, 400);
  11044. });
  11045. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11046. auto se = detail::scope_exit([&] {
  11047. svr.stop();
  11048. thread.join();
  11049. ASSERT_FALSE(svr.is_running());
  11050. });
  11051. svr.wait_until_ready();
  11052. Client cli(HOST, PORT);
  11053. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  11054. }
  11055. TEST(InvalidHeaderCharsTest, is_field_name) {
  11056. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  11057. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  11058. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  11059. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  11060. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  11061. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  11062. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  11063. EXPECT_FALSE(detail::fields::is_field_name(""));
  11064. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  11065. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  11066. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  11067. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  11068. }
  11069. TEST(InvalidHeaderCharsTest, is_field_value) {
  11070. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  11071. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  11072. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  11073. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  11074. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  11075. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  11076. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  11077. EXPECT_TRUE(detail::fields::is_field_value(""));
  11078. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  11079. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  11080. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  11081. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  11082. EXPECT_TRUE(detail::fields::is_field_value("0"));
  11083. }
  11084. TEST(InvalidHeaderCharsTest, OnServer) {
  11085. Server svr;
  11086. svr.Get("/test_name", [&](const Request &req, Response &res) {
  11087. std::string header = "Not Set";
  11088. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11089. res.set_header(header, "value");
  11090. res.set_content("Page Content Page Content", "text/plain");
  11091. });
  11092. svr.Get("/test_value", [&](const Request &req, Response &res) {
  11093. std::string header = "Not Set";
  11094. if (req.has_param("header")) { header = req.get_param_value("header"); }
  11095. res.set_header("X-Test", header);
  11096. res.set_content("Page Content Page Content", "text/plain");
  11097. });
  11098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11099. auto se = detail::scope_exit([&] {
  11100. svr.stop();
  11101. thread.join();
  11102. ASSERT_FALSE(svr.is_running());
  11103. });
  11104. svr.wait_until_ready();
  11105. Client cli(HOST, PORT);
  11106. {
  11107. auto res = cli.Get(
  11108. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11109. ASSERT_TRUE(res);
  11110. EXPECT_EQ("Page Content Page Content", res->body);
  11111. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11112. }
  11113. {
  11114. auto res = cli.Get(
  11115. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  11116. ASSERT_TRUE(res);
  11117. EXPECT_EQ("Page Content Page Content", res->body);
  11118. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  11119. }
  11120. }
  11121. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  11122. auto handled = false;
  11123. Server svr;
  11124. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11125. thread t = thread([&] { svr.listen(HOST, PORT); });
  11126. auto se = detail::scope_exit([&] {
  11127. svr.stop();
  11128. t.join();
  11129. ASSERT_FALSE(svr.is_running());
  11130. ASSERT_FALSE(handled);
  11131. });
  11132. svr.wait_until_ready();
  11133. auto req = "POST /test HTTP/1.1\r\n"
  11134. "Content-Length: x\r\n"
  11135. "\r\n";
  11136. std::string response;
  11137. ASSERT_TRUE(send_request(1, req, &response));
  11138. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11139. response.substr(0, response.find("\r\n")));
  11140. }
  11141. #ifndef _WIN32
  11142. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11143. static constexpr char reject[] = "Unauthorized";
  11144. static constexpr char accept[] = "Upload accepted";
  11145. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11146. Server svr;
  11147. svr.set_expect_100_continue_handler(
  11148. [](const Request & /*req*/, Response &res) {
  11149. res.status = StatusCode::Unauthorized_401;
  11150. res.set_content(reject, "text/plain");
  11151. return res.status;
  11152. });
  11153. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11154. res.set_content(accept, "text/plain");
  11155. });
  11156. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11157. auto se = detail::scope_exit([&] {
  11158. svr.stop();
  11159. thread.join();
  11160. ASSERT_FALSE(svr.is_running());
  11161. });
  11162. svr.wait_until_ready();
  11163. {
  11164. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11165. curl_easy_init(), &curl_easy_cleanup};
  11166. ASSERT_NE(curl, nullptr);
  11167. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11168. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11169. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11170. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11171. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11172. &curl_slist_free_all};
  11173. ASSERT_NE(list, nullptr);
  11174. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11175. struct read_data {
  11176. size_t read_size;
  11177. size_t total_size;
  11178. } data = {0, total_size};
  11179. using read_callback_t =
  11180. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11181. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11182. void *userdata) -> size_t {
  11183. read_data *d = (read_data *)userdata;
  11184. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11185. std::fill_n(ptr, size * nmemb, 'A');
  11186. d->read_size += size * nmemb;
  11187. return size * nmemb;
  11188. };
  11189. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11190. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11191. std::vector<char> buffer;
  11192. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11193. using write_callback_t =
  11194. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11195. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11196. void *userdata) -> size_t {
  11197. std::vector<char> *buf = (std::vector<char> *)userdata;
  11198. buf->reserve(buf->size() + size * nmemb + 1);
  11199. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11200. return size * nmemb;
  11201. };
  11202. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11203. {
  11204. const auto res = curl_easy_perform(curl.get());
  11205. ASSERT_EQ(res, CURLE_OK);
  11206. }
  11207. {
  11208. auto response_code = long{};
  11209. const auto res =
  11210. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11211. ASSERT_EQ(res, CURLE_OK);
  11212. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11213. }
  11214. {
  11215. auto dl = curl_off_t{};
  11216. const auto res =
  11217. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11218. ASSERT_EQ(res, CURLE_OK);
  11219. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11220. }
  11221. {
  11222. buffer.push_back('\0');
  11223. ASSERT_STRCASEEQ(buffer.data(), reject);
  11224. }
  11225. }
  11226. }
  11227. #endif
  11228. template <typename S, typename C>
  11229. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11230. svr.Get("/stream", [&](const Request &, Response &res) {
  11231. auto data = new std::string("01234567890123456789");
  11232. res.set_content_provider(
  11233. data->size(), "text/plain",
  11234. [&, data](size_t offset, size_t length, DataSink &sink) {
  11235. const size_t DATA_CHUNK_SIZE = 4;
  11236. const auto &d = *data;
  11237. std::this_thread::sleep_for(std::chrono::seconds(1));
  11238. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11239. return true;
  11240. },
  11241. [data](bool success) {
  11242. EXPECT_FALSE(success);
  11243. delete data;
  11244. });
  11245. });
  11246. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11247. auto i = new size_t(0);
  11248. res.set_content_provider(
  11249. "text/plain",
  11250. [i](size_t, DataSink &sink) {
  11251. if (*i < 5) {
  11252. std::this_thread::sleep_for(std::chrono::seconds(1));
  11253. sink.write("abcd", 4);
  11254. (*i)++;
  11255. } else {
  11256. sink.done();
  11257. }
  11258. return true;
  11259. },
  11260. [i](bool success) {
  11261. EXPECT_FALSE(success);
  11262. delete i;
  11263. });
  11264. });
  11265. svr.Get("/chunked", [&](const Request &, Response &res) {
  11266. auto i = new size_t(0);
  11267. res.set_chunked_content_provider(
  11268. "text/plain",
  11269. [i](size_t, DataSink &sink) {
  11270. if (*i < 5) {
  11271. std::this_thread::sleep_for(std::chrono::seconds(1));
  11272. sink.os << "abcd";
  11273. (*i)++;
  11274. } else {
  11275. sink.done();
  11276. }
  11277. return true;
  11278. },
  11279. [i](bool success) {
  11280. EXPECT_FALSE(success);
  11281. delete i;
  11282. });
  11283. });
  11284. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11285. auto se = detail::scope_exit([&] {
  11286. svr.stop();
  11287. listen_thread.join();
  11288. ASSERT_FALSE(svr.is_running());
  11289. });
  11290. svr.wait_until_ready();
  11291. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11292. {
  11293. auto start = std::chrono::steady_clock::now();
  11294. auto res = cli.Get("/stream");
  11295. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11296. std::chrono::steady_clock::now() - start)
  11297. .count();
  11298. ASSERT_FALSE(res);
  11299. EXPECT_EQ(Error::Read, res.error());
  11300. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11301. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11302. }
  11303. {
  11304. auto start = std::chrono::steady_clock::now();
  11305. auto res = cli.Get("/stream_without_length");
  11306. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11307. std::chrono::steady_clock::now() - start)
  11308. .count();
  11309. ASSERT_FALSE(res);
  11310. EXPECT_EQ(Error::Read, res.error());
  11311. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11312. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11313. }
  11314. {
  11315. auto start = std::chrono::steady_clock::now();
  11316. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11317. EXPECT_EQ("abcd", string(data, data_length));
  11318. return true;
  11319. });
  11320. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11321. std::chrono::steady_clock::now() - start)
  11322. .count();
  11323. ASSERT_FALSE(res);
  11324. EXPECT_EQ(Error::Read, res.error());
  11325. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11326. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11327. }
  11328. }
  11329. TEST(MaxTimeoutTest, ContentStream) {
  11330. time_t timeout = 2000;
  11331. time_t threshold = 200;
  11332. Server svr;
  11333. Client cli("localhost", PORT);
  11334. max_timeout_test(svr, cli, timeout, threshold);
  11335. }
  11336. #ifdef CPPHTTPLIB_SSL_ENABLED
  11337. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11338. time_t timeout = 2000;
  11339. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11340. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11341. SSLClient cli("localhost", PORT);
  11342. cli.enable_server_certificate_verification(false);
  11343. max_timeout_test(svr, cli, timeout, threshold);
  11344. }
  11345. #endif
  11346. class EventDispatcher {
  11347. public:
  11348. EventDispatcher() {}
  11349. bool wait_event(DataSink *sink) {
  11350. unique_lock<mutex> lk(m_);
  11351. int id = id_;
  11352. // Wait with timeout to prevent hanging if client disconnects
  11353. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11354. [&] { return cid_ == id; })) {
  11355. return false; // Timeout occurred
  11356. }
  11357. sink->write(message_.data(), message_.size());
  11358. return true;
  11359. }
  11360. void send_event(const string &message) {
  11361. lock_guard<mutex> lk(m_);
  11362. cid_ = id_++;
  11363. message_ = message;
  11364. cv_.notify_all();
  11365. }
  11366. private:
  11367. mutex m_;
  11368. condition_variable cv_;
  11369. atomic_int id_{0};
  11370. atomic_int cid_{-1};
  11371. string message_;
  11372. };
  11373. TEST(ClientInThreadTest, Issue2068) {
  11374. EventDispatcher ed;
  11375. Server svr;
  11376. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11377. res.set_chunked_content_provider("text/event-stream",
  11378. [&](size_t /*offset*/, DataSink &sink) {
  11379. return ed.wait_event(&sink);
  11380. });
  11381. });
  11382. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11383. svr.wait_until_ready();
  11384. thread event_thread([&] {
  11385. int id = 0;
  11386. while (svr.is_running()) {
  11387. this_thread::sleep_for(chrono::milliseconds(500));
  11388. std::stringstream ss;
  11389. ss << "data: " << id << "\n\n";
  11390. ed.send_event(ss.str());
  11391. id++;
  11392. }
  11393. });
  11394. auto se = detail::scope_exit([&] {
  11395. svr.stop();
  11396. listen_thread.join();
  11397. event_thread.join();
  11398. ASSERT_FALSE(svr.is_running());
  11399. });
  11400. {
  11401. auto client = detail::make_unique<Client>(HOST, PORT);
  11402. client->set_read_timeout(std::chrono::minutes(10));
  11403. std::atomic<bool> stop{false};
  11404. std::thread t([&] {
  11405. client->Get("/event1",
  11406. [&](const char *, size_t) -> bool { return !stop; });
  11407. });
  11408. std::this_thread::sleep_for(std::chrono::seconds(2));
  11409. stop = true;
  11410. client->stop();
  11411. t.join();
  11412. // Reset client after thread has finished
  11413. client.reset();
  11414. }
  11415. }
  11416. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11417. auto handled = false;
  11418. Server svr;
  11419. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11420. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11421. auto se = detail::scope_exit([&] {
  11422. svr.stop();
  11423. t.join();
  11424. ASSERT_FALSE(svr.is_running());
  11425. ASSERT_FALSE(handled);
  11426. });
  11427. svr.wait_until_ready();
  11428. // Two Content-Length headers with different values — must be rejected
  11429. auto req = "POST /test HTTP/1.1\r\n"
  11430. "Content-Length: 5\r\n"
  11431. "Content-Length: 10\r\n"
  11432. "\r\n"
  11433. "hello";
  11434. std::string response;
  11435. ASSERT_TRUE(send_request(1, req, &response));
  11436. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11437. response.substr(0, response.find("\r\n")));
  11438. }
  11439. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11440. auto handled = false;
  11441. Server svr;
  11442. svr.Post("/test", [&](const Request &, Response &res) {
  11443. handled = true;
  11444. res.set_content("ok", "text/plain");
  11445. });
  11446. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11447. auto se = detail::scope_exit([&] {
  11448. svr.stop();
  11449. t.join();
  11450. ASSERT_FALSE(svr.is_running());
  11451. ASSERT_TRUE(handled);
  11452. });
  11453. svr.wait_until_ready();
  11454. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11455. auto req = "POST /test HTTP/1.1\r\n"
  11456. "Content-Length: 5\r\n"
  11457. "Content-Length: 5\r\n"
  11458. "\r\n"
  11459. "hello";
  11460. std::string response;
  11461. ASSERT_TRUE(send_request(1, req, &response));
  11462. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11463. }
  11464. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11465. Server svr;
  11466. svr.Get("/", [](const Request &req, Response &res) {
  11467. EXPECT_EQ(2U, req.trailers.size());
  11468. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11469. // Denied
  11470. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11471. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11472. // Accepted
  11473. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11474. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11475. EXPECT_TRUE(req.has_trailer("X-World"));
  11476. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11477. res.set_content("ok", "text/plain");
  11478. });
  11479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11480. auto se = detail::scope_exit([&] {
  11481. svr.stop();
  11482. t.join();
  11483. ASSERT_FALSE(svr.is_running());
  11484. });
  11485. svr.wait_until_ready();
  11486. const std::string req = "GET / HTTP/1.1\r\n"
  11487. "Transfer-Encoding: chunked\r\n"
  11488. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11489. "\r\n"
  11490. "0\r\n"
  11491. "Content-Length: 10\r\n"
  11492. "Host: internal.local\r\n"
  11493. "Content-Type: malicious/content\r\n"
  11494. "Cookie: any\r\n"
  11495. "Set-Cookie: any\r\n"
  11496. "X-Forwarded-For: attacker.com\r\n"
  11497. "X-Real-Ip: 1.1.1.1\r\n"
  11498. "X-Hello: hello\r\n"
  11499. "X-World: world\r\n"
  11500. "\r\n";
  11501. std::string res;
  11502. ASSERT_TRUE(send_request(1, req, &res));
  11503. }
  11504. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11505. Server svr;
  11506. std::string observed_remote_addr;
  11507. std::string observed_xff;
  11508. svr.Get("/ip", [&](const Request &req, Response &res) {
  11509. observed_remote_addr = req.remote_addr;
  11510. observed_xff = req.get_header_value("X-Forwarded-For");
  11511. res.set_content("ok", "text/plain");
  11512. });
  11513. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11514. auto se = detail::scope_exit([&] {
  11515. svr.stop();
  11516. t.join();
  11517. ASSERT_FALSE(svr.is_running());
  11518. });
  11519. svr.wait_until_ready();
  11520. Client cli(HOST, PORT);
  11521. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11522. ASSERT_TRUE(res);
  11523. EXPECT_EQ(StatusCode::OK_200, res->status);
  11524. EXPECT_EQ(observed_xff, "203.0.113.66");
  11525. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11526. observed_remote_addr == "127.0.0.1");
  11527. }
  11528. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11529. Server svr;
  11530. svr.set_trusted_proxies({"203.0.113.66"});
  11531. std::string observed_remote_addr;
  11532. std::string observed_xff;
  11533. svr.Get("/ip", [&](const Request &req, Response &res) {
  11534. observed_remote_addr = req.remote_addr;
  11535. observed_xff = req.get_header_value("X-Forwarded-For");
  11536. res.set_content("ok", "text/plain");
  11537. });
  11538. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11539. auto se = detail::scope_exit([&] {
  11540. svr.stop();
  11541. t.join();
  11542. ASSERT_FALSE(svr.is_running());
  11543. });
  11544. svr.wait_until_ready();
  11545. Client cli(HOST, PORT);
  11546. auto res = cli.Get("/ip");
  11547. ASSERT_TRUE(res);
  11548. EXPECT_EQ(StatusCode::OK_200, res->status);
  11549. EXPECT_EQ(observed_xff, "");
  11550. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11551. observed_remote_addr == "127.0.0.1");
  11552. }
  11553. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11554. Server svr;
  11555. svr.set_trusted_proxies({"203.0.113.66"});
  11556. std::string observed_remote_addr;
  11557. std::string observed_xff;
  11558. svr.Get("/ip", [&](const Request &req, Response &res) {
  11559. observed_remote_addr = req.remote_addr;
  11560. observed_xff = req.get_header_value("X-Forwarded-For");
  11561. res.set_content("ok", "text/plain");
  11562. });
  11563. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11564. auto se = detail::scope_exit([&] {
  11565. svr.stop();
  11566. t.join();
  11567. ASSERT_FALSE(svr.is_running());
  11568. });
  11569. svr.wait_until_ready();
  11570. Client cli(HOST, PORT);
  11571. auto res =
  11572. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11573. ASSERT_TRUE(res);
  11574. EXPECT_EQ(StatusCode::OK_200, res->status);
  11575. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11576. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11577. }
  11578. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11579. Server svr;
  11580. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11581. std::string observed_remote_addr;
  11582. std::string observed_xff;
  11583. svr.Get("/ip", [&](const Request &req, Response &res) {
  11584. observed_remote_addr = req.remote_addr;
  11585. observed_xff = req.get_header_value("X-Forwarded-For");
  11586. res.set_content("ok", "text/plain");
  11587. });
  11588. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11589. auto se = detail::scope_exit([&] {
  11590. svr.stop();
  11591. t.join();
  11592. ASSERT_FALSE(svr.is_running());
  11593. });
  11594. svr.wait_until_ready();
  11595. Client cli(HOST, PORT);
  11596. auto res = cli.Get(
  11597. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11598. ASSERT_TRUE(res);
  11599. EXPECT_EQ(StatusCode::OK_200, res->status);
  11600. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11601. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11602. }
  11603. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11604. Server svr;
  11605. svr.set_trusted_proxies({"192.0.2.45"});
  11606. std::string observed_remote_addr;
  11607. std::string observed_xff;
  11608. svr.Get("/ip", [&](const Request &req, Response &res) {
  11609. observed_remote_addr = req.remote_addr;
  11610. observed_xff = req.get_header_value("X-Forwarded-For");
  11611. res.set_content("ok", "text/plain");
  11612. });
  11613. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11614. auto se = detail::scope_exit([&] {
  11615. svr.stop();
  11616. t.join();
  11617. ASSERT_FALSE(svr.is_running());
  11618. });
  11619. svr.wait_until_ready();
  11620. Client cli(HOST, PORT);
  11621. auto res =
  11622. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11623. ASSERT_TRUE(res);
  11624. EXPECT_EQ(StatusCode::OK_200, res->status);
  11625. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11626. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11627. }
  11628. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11629. Server svr;
  11630. svr.set_trusted_proxies({"192.0.2.45"});
  11631. std::string observed_remote_addr;
  11632. std::string observed_xff;
  11633. svr.Get("/ip", [&](const Request &req, Response &res) {
  11634. observed_remote_addr = req.remote_addr;
  11635. observed_xff = req.get_header_value("X-Forwarded-For");
  11636. res.set_content("ok", "text/plain");
  11637. });
  11638. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11639. auto se = detail::scope_exit([&] {
  11640. svr.stop();
  11641. t.join();
  11642. ASSERT_FALSE(svr.is_running());
  11643. });
  11644. svr.wait_until_ready();
  11645. Client cli(HOST, PORT);
  11646. auto res = cli.Get(
  11647. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11648. ASSERT_TRUE(res);
  11649. EXPECT_EQ(StatusCode::OK_200, res->status);
  11650. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11651. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11652. }
  11653. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11654. Server svr;
  11655. svr.set_trusted_proxies({"192.0.2.45"});
  11656. std::string observed_remote_addr;
  11657. std::string observed_xff;
  11658. svr.Get("/ip", [&](const Request &req, Response &res) {
  11659. observed_remote_addr = req.remote_addr;
  11660. observed_xff = req.get_header_value("X-Forwarded-For");
  11661. res.set_content("ok", "text/plain");
  11662. });
  11663. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11664. auto se = detail::scope_exit([&] {
  11665. svr.stop();
  11666. t.join();
  11667. ASSERT_FALSE(svr.is_running());
  11668. });
  11669. svr.wait_until_ready();
  11670. std::string raw_req =
  11671. "GET /ip HTTP/1.1\r\n"
  11672. "Host: localhost\r\n"
  11673. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11674. "Connection: close\r\n"
  11675. "\r\n";
  11676. std::string out;
  11677. ASSERT_TRUE(send_request(5, raw_req, &out));
  11678. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11679. // Header parser trims surrounding whitespace of the header value
  11680. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11681. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11682. }
  11683. #ifndef _WIN32
  11684. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11685. Server svr;
  11686. svr.Post("/post", [&](const Request &req, Response &res) {
  11687. res.set_content(req.body, "text/plain");
  11688. });
  11689. svr.Put("/put", [&](const Request &req, Response &res) {
  11690. res.set_content(req.body, "text/plain");
  11691. });
  11692. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11693. res.set_content(req.body, "text/plain");
  11694. });
  11695. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11696. res.set_content(req.body, "text/plain");
  11697. });
  11698. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11699. auto se = detail::scope_exit([&] {
  11700. svr.stop();
  11701. t.join();
  11702. ASSERT_FALSE(svr.is_running());
  11703. });
  11704. svr.wait_until_ready();
  11705. std::string resp;
  11706. // POST without Content-Length
  11707. ASSERT_TRUE(send_request(5,
  11708. "POST /post HTTP/1.1\r\n"
  11709. "Host: localhost\r\n"
  11710. "Connection: close\r\n"
  11711. "\r\n",
  11712. &resp));
  11713. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11714. // PUT without Content-Length
  11715. resp.clear();
  11716. ASSERT_TRUE(send_request(5,
  11717. "PUT /put HTTP/1.1\r\n"
  11718. "Host: localhost\r\n"
  11719. "Connection: close\r\n"
  11720. "\r\n",
  11721. &resp));
  11722. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11723. // PATCH without Content-Length
  11724. resp.clear();
  11725. ASSERT_TRUE(send_request(5,
  11726. "PATCH /patch HTTP/1.1\r\n"
  11727. "Host: localhost\r\n"
  11728. "Connection: close\r\n"
  11729. "\r\n",
  11730. &resp));
  11731. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11732. // DELETE without Content-Length
  11733. resp.clear();
  11734. ASSERT_TRUE(send_request(5,
  11735. "DELETE /delete HTTP/1.1\r\n"
  11736. "Host: localhost\r\n"
  11737. "Connection: close\r\n"
  11738. "\r\n",
  11739. &resp));
  11740. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11741. }
  11742. #endif
  11743. //==============================================================================
  11744. // open_stream() Tests
  11745. //==============================================================================
  11746. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11747. std::string result;
  11748. char buf[8192];
  11749. ssize_t n;
  11750. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11751. result.append(buf, static_cast<size_t>(n));
  11752. }
  11753. return result;
  11754. }
  11755. // Mock stream for unit tests
  11756. class MockStream : public Stream {
  11757. public:
  11758. std::string data;
  11759. size_t pos = 0;
  11760. ssize_t error_after = -1; // -1 = no error
  11761. explicit MockStream(const std::string &d, ssize_t err = -1)
  11762. : data(d), error_after(err) {}
  11763. bool is_readable() const override { return true; }
  11764. bool wait_readable() const override { return true; }
  11765. bool wait_writable() const override { return true; }
  11766. ssize_t read(char *ptr, size_t size) override {
  11767. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11768. if (pos >= data.size()) return 0;
  11769. size_t limit =
  11770. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11771. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11772. std::memcpy(ptr, data.data() + pos, to_read);
  11773. pos += to_read;
  11774. return static_cast<ssize_t>(to_read);
  11775. }
  11776. ssize_t write(const char *, size_t) override { return -1; }
  11777. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11778. ip = "127.0.0.1";
  11779. port = 0;
  11780. }
  11781. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11782. ip = "127.0.0.1";
  11783. port = 0;
  11784. }
  11785. socket_t socket() const override { return INVALID_SOCKET; }
  11786. time_t duration() const override { return 0; }
  11787. };
  11788. TEST(StreamHandleTest, Basic) {
  11789. ClientImpl::StreamHandle handle;
  11790. EXPECT_FALSE(handle.is_valid());
  11791. handle.response = detail::make_unique<Response>();
  11792. handle.error = Error::Connection;
  11793. EXPECT_FALSE(handle.is_valid());
  11794. handle.error = Error::Success;
  11795. EXPECT_TRUE(handle.is_valid());
  11796. }
  11797. TEST(BodyReaderTest, Basic) {
  11798. MockStream stream("Hello, World!");
  11799. detail::BodyReader reader;
  11800. reader.stream = &stream;
  11801. reader.content_length = 13;
  11802. char buf[32];
  11803. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11804. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11805. EXPECT_TRUE(reader.eof);
  11806. }
  11807. TEST(BodyReaderTest, NoStream) {
  11808. detail::BodyReader reader;
  11809. char buf[32];
  11810. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11811. EXPECT_EQ(Error::Connection, reader.last_error);
  11812. }
  11813. TEST(BodyReaderTest, Error) {
  11814. MockStream stream("Hello, World!", 5);
  11815. detail::BodyReader reader;
  11816. reader.stream = &stream;
  11817. reader.content_length = 13;
  11818. char buf[32];
  11819. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11820. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11821. EXPECT_EQ(Error::Read, reader.last_error);
  11822. }
  11823. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11824. // Mock-based StreamHandle tests relying on private internals are removed.
  11825. class OpenStreamTest : public ::testing::Test {
  11826. protected:
  11827. void SetUp() override {
  11828. svr_.Get("/hello", [](const Request &, Response &res) {
  11829. res.set_content("Hello World!", "text/plain");
  11830. });
  11831. svr_.Get("/large", [](const Request &, Response &res) {
  11832. res.set_content(std::string(10000, 'X'), "text/plain");
  11833. });
  11834. svr_.Get("/chunked", [](const Request &, Response &res) {
  11835. res.set_chunked_content_provider("text/plain",
  11836. [](size_t offset, DataSink &sink) {
  11837. if (offset < 15) {
  11838. sink.write("chunk", 5);
  11839. return true;
  11840. }
  11841. sink.done();
  11842. return true;
  11843. });
  11844. });
  11845. svr_.Get("/compressible", [](const Request &, Response &res) {
  11846. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11847. DataSink &sink) {
  11848. if (offset < 100 * 1024) {
  11849. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11850. sink.write(chunk.data(), chunk.size());
  11851. return true;
  11852. }
  11853. sink.done();
  11854. return true;
  11855. });
  11856. });
  11857. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11858. [](const Request & /*req*/, Response &res) {
  11859. auto i = new int(0);
  11860. res.set_header("Trailer", "Content-Length, X-Allowed");
  11861. res.set_chunked_content_provider(
  11862. "text/plain",
  11863. [i](size_t /*offset*/, DataSink &sink) {
  11864. switch (*i) {
  11865. case 0: sink.os << "123"; break;
  11866. case 1: sink.os << "456"; break;
  11867. case 2: sink.os << "789"; break;
  11868. case 3: {
  11869. sink.done_with_trailer(
  11870. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11871. } break;
  11872. }
  11873. (*i)++;
  11874. return true;
  11875. },
  11876. [i](bool success) {
  11877. EXPECT_TRUE(success);
  11878. delete i;
  11879. });
  11880. });
  11881. // Echo headers endpoint for header-related tests
  11882. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11883. std::string body;
  11884. for (const auto &h : req.headers) {
  11885. body.append(h.first);
  11886. body.push_back(':');
  11887. body.append(h.second);
  11888. body.push_back('\n');
  11889. }
  11890. res.set_content(body, "text/plain");
  11891. });
  11892. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11893. std::string body;
  11894. for (const auto &h : req.headers) {
  11895. body.append(h.first);
  11896. body.push_back(':');
  11897. body.append(h.second);
  11898. body.push_back('\n');
  11899. }
  11900. res.set_content(body, "text/plain");
  11901. });
  11902. port_ = svr_.bind_to_any_port("127.0.0.1");
  11903. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11904. svr_.wait_until_ready();
  11905. }
  11906. void TearDown() override {
  11907. svr_.stop();
  11908. if (thread_.joinable()) thread_.join();
  11909. }
  11910. Server svr_;
  11911. std::thread thread_;
  11912. int port_ = 0;
  11913. };
  11914. TEST_F(OpenStreamTest, Basic) {
  11915. Client cli("127.0.0.1", port_);
  11916. auto handle = cli.open_stream("GET", "/hello");
  11917. EXPECT_TRUE(handle.is_valid());
  11918. EXPECT_EQ("Hello World!", read_all(handle));
  11919. }
  11920. TEST_F(OpenStreamTest, SmallBuffer) {
  11921. Client cli("127.0.0.1", port_);
  11922. auto handle = cli.open_stream("GET", "/hello");
  11923. std::string result;
  11924. char buf[4];
  11925. ssize_t n;
  11926. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11927. result.append(buf, static_cast<size_t>(n));
  11928. EXPECT_EQ("Hello World!", result);
  11929. }
  11930. TEST_F(OpenStreamTest, DefaultHeaders) {
  11931. Client cli("127.0.0.1", port_);
  11932. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11933. {
  11934. auto handle = cli.open_stream("GET", "/echo-headers");
  11935. ASSERT_TRUE(handle.is_valid());
  11936. auto body = read_all(handle);
  11937. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11938. std::string::npos);
  11939. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11940. std::string::npos);
  11941. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11942. }
  11943. // open_stream POST with body and no explicit content_type should NOT add
  11944. // text/plain Content-Type (behavior differs from non-streaming path), but
  11945. // should include Content-Length
  11946. {
  11947. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11948. ASSERT_TRUE(handle.is_valid());
  11949. auto body = read_all(handle);
  11950. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11951. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11952. }
  11953. // open_stream POST with explicit Content-Type should preserve it
  11954. {
  11955. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11956. {{"Content-Type", "application/custom"}},
  11957. "{}", "application/custom");
  11958. ASSERT_TRUE(handle.is_valid());
  11959. auto body = read_all(handle);
  11960. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11961. }
  11962. // User-specified User-Agent must not be overwritten for stream API
  11963. {
  11964. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11965. {{"User-Agent", "MyAgent/1.2"}});
  11966. ASSERT_TRUE(handle.is_valid());
  11967. auto body = read_all(handle);
  11968. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11969. }
  11970. }
  11971. TEST_F(OpenStreamTest, Large) {
  11972. Client cli("127.0.0.1", port_);
  11973. auto handle = cli.open_stream("GET", "/large");
  11974. EXPECT_EQ(10000u, read_all(handle).size());
  11975. }
  11976. TEST_F(OpenStreamTest, ConnectionError) {
  11977. Client cli("127.0.0.1", 9999);
  11978. auto handle = cli.open_stream("GET", "/hello");
  11979. EXPECT_FALSE(handle.is_valid());
  11980. }
  11981. TEST_F(OpenStreamTest, Chunked) {
  11982. Client cli("127.0.0.1", port_);
  11983. auto handle = cli.open_stream("GET", "/chunked");
  11984. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11985. "Transfer-Encoding") == "chunked");
  11986. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11987. }
  11988. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11989. Client cli("127.0.0.1", port_);
  11990. auto handle =
  11991. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11992. ASSERT_TRUE(handle.is_valid());
  11993. // Consume body to allow trailers to be received/parsed
  11994. auto body = read_all(handle);
  11995. // Explicitly parse trailers (ensure trailers are available for assertion)
  11996. handle.parse_trailers_if_needed();
  11997. EXPECT_EQ(std::string("123456789"), body);
  11998. // The response should include a Trailer header declaring both names
  11999. ASSERT_TRUE(handle.response);
  12000. EXPECT_TRUE(handle.response->has_header("Trailer"));
  12001. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  12002. handle.response->get_header_value("Trailer"));
  12003. // Prohibited trailer must not be present
  12004. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  12005. // Allowed trailer should be present
  12006. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  12007. EXPECT_EQ(std::string("yes"),
  12008. handle.response->get_trailer_value("X-Allowed"));
  12009. // Verify trailers are NOT present as regular headers
  12010. EXPECT_EQ(std::string(""),
  12011. handle.response->get_header_value("Content-Length"));
  12012. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  12013. }
  12014. static std::thread serve_single_response(std::promise<int> &port_promise,
  12015. const std::string &response) {
  12016. return std::thread([&port_promise, response] {
  12017. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12018. default_socket_options(srv);
  12019. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12020. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12021. sockaddr_in addr{};
  12022. addr.sin_family = AF_INET;
  12023. addr.sin_port = htons(0); // Let OS assign a free port
  12024. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12025. int opt = 1;
  12026. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12027. #ifdef _WIN32
  12028. reinterpret_cast<const char *>(&opt),
  12029. #else
  12030. &opt,
  12031. #endif
  12032. sizeof(opt));
  12033. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  12034. ::listen(srv, 1) != 0) {
  12035. port_promise.set_value(-1);
  12036. detail::close_socket(srv);
  12037. return;
  12038. }
  12039. socklen_t addr_len = sizeof(addr);
  12040. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  12041. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  12042. sockaddr_in cli_addr{};
  12043. socklen_t cli_len = sizeof(cli_addr);
  12044. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12045. if (cli != INVALID_SOCKET) {
  12046. // Read the complete HTTP request (until the blank line that terminates
  12047. // headers) before sending the response. If the server closes the socket
  12048. // while the client's request data is still unread in the kernel receive
  12049. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  12050. // connection on both sides: it discards the client's receive buffer
  12051. // (which already holds our response) and causes any in-progress write on
  12052. // the client to fail with ECONNRESET. Reading all request data first
  12053. // ensures close() emits a graceful FIN.
  12054. {
  12055. char rbuf[256];
  12056. std::string req;
  12057. while (req.find("\r\n\r\n") == std::string::npos) {
  12058. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  12059. if (n <= 0) { break; }
  12060. req.append(rbuf, static_cast<size_t>(n));
  12061. }
  12062. }
  12063. ::send(cli,
  12064. #ifdef _WIN32
  12065. static_cast<const char *>(response.c_str()),
  12066. static_cast<int>(response.size()),
  12067. #else
  12068. response.c_str(), response.size(),
  12069. #endif
  12070. 0);
  12071. detail::close_socket(cli);
  12072. }
  12073. detail::close_socket(srv);
  12074. });
  12075. }
  12076. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  12077. #ifndef _WIN32
  12078. signal(SIGPIPE, SIG_IGN);
  12079. #endif
  12080. std::promise<int> port_promise;
  12081. auto port_future = port_promise.get_future();
  12082. auto server_thread =
  12083. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  12084. "Content-Type: text/plain\r\n"
  12085. "Content-Length: not-a-number\r\n"
  12086. "Connection: close\r\n"
  12087. "\r\n"
  12088. "hello");
  12089. auto port = port_future.get();
  12090. ASSERT_GT(port, 0);
  12091. Client cli("127.0.0.1", port);
  12092. auto handle = cli.open_stream("GET", "/");
  12093. EXPECT_FALSE(handle.is_valid());
  12094. server_thread.join();
  12095. }
  12096. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  12097. #ifndef _WIN32
  12098. signal(SIGPIPE, SIG_IGN);
  12099. #endif
  12100. std::promise<int> port_promise;
  12101. auto port_future = port_promise.get_future();
  12102. auto server_thread = serve_single_response(
  12103. port_promise, "HTTP/1.1 200 OK\r\n"
  12104. "Content-Type: text/plain\r\n"
  12105. "Content-Length: 99999999999999999999999999\r\n"
  12106. "Connection: close\r\n"
  12107. "\r\n"
  12108. "hello");
  12109. auto port = port_future.get();
  12110. ASSERT_GT(port, 0);
  12111. // Before the fix, std::stoull would throw std::out_of_range here and
  12112. // crash the process. After the fix, strtoull silently clamps to
  12113. // ULLONG_MAX so the stream opens without crashing. The important thing
  12114. // is that the process does NOT terminate.
  12115. Client cli("127.0.0.1", port);
  12116. auto handle = cli.open_stream("GET", "/");
  12117. EXPECT_TRUE(handle.is_valid());
  12118. server_thread.join();
  12119. }
  12120. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12121. TEST_F(OpenStreamTest, Gzip) {
  12122. Client cli("127.0.0.1", port_);
  12123. auto handle = cli.open_stream("GET", "/compressible", {},
  12124. {{"Accept-Encoding", "gzip"}});
  12125. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  12126. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12127. }
  12128. #endif
  12129. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12130. TEST_F(OpenStreamTest, Brotli) {
  12131. Client cli("127.0.0.1", port_);
  12132. auto handle =
  12133. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  12134. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  12135. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12136. }
  12137. #endif
  12138. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12139. TEST_F(OpenStreamTest, Zstd) {
  12140. Client cli("127.0.0.1", port_);
  12141. auto handle = cli.open_stream("GET", "/compressible", {},
  12142. {{"Accept-Encoding", "zstd"}});
  12143. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  12144. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  12145. }
  12146. #endif
  12147. #ifdef CPPHTTPLIB_SSL_ENABLED
  12148. class SSLOpenStreamTest : public ::testing::Test {
  12149. protected:
  12150. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  12151. void SetUp() override {
  12152. svr_.Get("/hello", [](const Request &, Response &res) {
  12153. res.set_content("Hello SSL World!", "text/plain");
  12154. });
  12155. svr_.Get("/chunked", [](const Request &, Response &res) {
  12156. res.set_chunked_content_provider("text/plain",
  12157. [](size_t offset, DataSink &sink) {
  12158. if (offset < 15) {
  12159. sink.write("chunk", 5);
  12160. return true;
  12161. }
  12162. sink.done();
  12163. return true;
  12164. });
  12165. });
  12166. svr_.Post("/echo", [](const Request &req, Response &res) {
  12167. res.set_content(req.body, req.get_header_value("Content-Type"));
  12168. });
  12169. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12170. std::string body = req.body;
  12171. res.set_chunked_content_provider(
  12172. "text/plain", [body](size_t offset, DataSink &sink) {
  12173. if (offset < body.size()) {
  12174. sink.write(body.data() + offset, body.size() - offset);
  12175. }
  12176. sink.done();
  12177. return true;
  12178. });
  12179. });
  12180. port_ = svr_.bind_to_any_port("127.0.0.1");
  12181. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12182. svr_.wait_until_ready();
  12183. }
  12184. void TearDown() override {
  12185. svr_.stop();
  12186. if (thread_.joinable()) thread_.join();
  12187. }
  12188. SSLServer svr_;
  12189. std::thread thread_;
  12190. int port_ = 0;
  12191. };
  12192. TEST_F(SSLOpenStreamTest, Basic) {
  12193. SSLClient cli("127.0.0.1", port_);
  12194. cli.enable_server_certificate_verification(false);
  12195. auto handle = cli.open_stream("GET", "/hello");
  12196. ASSERT_TRUE(handle.is_valid());
  12197. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12198. }
  12199. TEST_F(SSLOpenStreamTest, Chunked) {
  12200. SSLClient cli("127.0.0.1", port_);
  12201. cli.enable_server_certificate_verification(false);
  12202. auto handle = cli.open_stream("GET", "/chunked");
  12203. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12204. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12205. "Transfer-Encoding") == "chunked");
  12206. auto body = read_all(handle);
  12207. EXPECT_EQ("chunkchunkchunk", body);
  12208. }
  12209. TEST_F(SSLOpenStreamTest, Post) {
  12210. SSLClient cli("127.0.0.1", port_);
  12211. cli.enable_server_certificate_verification(false);
  12212. auto handle =
  12213. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12214. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12215. EXPECT_EQ(200, handle.response->status);
  12216. auto body = read_all(handle);
  12217. EXPECT_EQ("Hello SSL POST", body);
  12218. }
  12219. TEST_F(SSLOpenStreamTest, PostChunked) {
  12220. SSLClient cli("127.0.0.1", port_);
  12221. cli.enable_server_certificate_verification(false);
  12222. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12223. "Chunked SSL Data", "text/plain");
  12224. ASSERT_TRUE(handle.is_valid());
  12225. EXPECT_EQ(200, handle.response->status);
  12226. auto body = read_all(handle);
  12227. EXPECT_EQ("Chunked SSL Data", body);
  12228. }
  12229. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  12230. // Content-Length is terminated by the server closing the connection. When the
  12231. // SSL peer sends a close_notify after the body, the client must treat it as a
  12232. // clean EOF and return a successful response rather than an error.
  12233. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  12234. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12235. ASSERT_TRUE(svr.is_valid());
  12236. svr.set_keep_alive_max_count(1);
  12237. const std::string expected_body = "Hello from connection-close response!";
  12238. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  12239. res.set_content_provider("text/plain",
  12240. [&](size_t offset, DataSink &sink) -> bool {
  12241. if (offset < expected_body.size()) {
  12242. sink.write(expected_body.data() + offset,
  12243. expected_body.size() - offset);
  12244. }
  12245. sink.done();
  12246. return true;
  12247. });
  12248. });
  12249. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12250. auto se = detail::scope_exit([&] {
  12251. svr.stop();
  12252. listen_thread.join();
  12253. ASSERT_FALSE(svr.is_running());
  12254. });
  12255. svr.wait_until_ready();
  12256. SSLClient cli(HOST, PORT);
  12257. cli.enable_server_certificate_verification(false);
  12258. auto res = cli.Get("/no-content-length");
  12259. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  12260. EXPECT_EQ(StatusCode::OK_200, res->status);
  12261. EXPECT_EQ(expected_body, res->body);
  12262. }
  12263. #endif // CPPHTTPLIB_SSL_ENABLED
  12264. //==============================================================================
  12265. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12266. // results for various scenarios.
  12267. //==============================================================================
  12268. TEST(ParityTest, GetVsOpenStream) {
  12269. Server svr;
  12270. const std::string path = "/parity";
  12271. const std::string content = "Parity test content: hello world";
  12272. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12273. res.set_content(content, "text/plain");
  12274. });
  12275. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12276. auto se = detail::scope_exit([&] {
  12277. svr.stop();
  12278. t.join();
  12279. ASSERT_FALSE(svr.is_running());
  12280. });
  12281. svr.wait_until_ready();
  12282. Client cli(HOST, PORT);
  12283. // Non-stream path
  12284. auto r1 = cli.Get(path);
  12285. ASSERT_TRUE(r1);
  12286. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12287. // Stream path
  12288. auto h = cli.open_stream("GET", path);
  12289. ASSERT_TRUE(h.is_valid());
  12290. EXPECT_EQ(r1->body, read_all(h));
  12291. }
  12292. // Helper to compress data with provided compressor type T
  12293. template <typename Compressor>
  12294. static std::string compress_payload_for_parity(const std::string &in) {
  12295. std::string out;
  12296. Compressor compressor;
  12297. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12298. [&](const char *data, size_t n) {
  12299. out.append(data, n);
  12300. return true;
  12301. });
  12302. EXPECT_TRUE(ok);
  12303. return out;
  12304. }
  12305. // Helper function for compression parity tests
  12306. template <typename Compressor>
  12307. static void test_compression_parity(const std::string &original,
  12308. const std::string &path,
  12309. const std::string &encoding) {
  12310. const std::string compressed =
  12311. compress_payload_for_parity<Compressor>(original);
  12312. Server svr;
  12313. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12314. res.set_content(compressed, "application/octet-stream");
  12315. res.set_header("Content-Encoding", encoding);
  12316. });
  12317. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12318. auto se = detail::scope_exit([&] {
  12319. svr.stop();
  12320. t.join();
  12321. ASSERT_FALSE(svr.is_running());
  12322. });
  12323. svr.wait_until_ready();
  12324. Client cli(HOST, PORT);
  12325. // Non-streaming
  12326. {
  12327. auto res = cli.Get(path);
  12328. ASSERT_TRUE(res);
  12329. EXPECT_EQ(StatusCode::OK_200, res->status);
  12330. EXPECT_EQ(original, res->body);
  12331. }
  12332. // Streaming
  12333. {
  12334. auto h = cli.open_stream("GET", path);
  12335. ASSERT_TRUE(h.is_valid());
  12336. EXPECT_EQ(original, read_all(h));
  12337. }
  12338. }
  12339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12340. TEST(ParityTest, Gzip) {
  12341. test_compression_parity<detail::gzip_compressor>(
  12342. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12343. }
  12344. #endif
  12345. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12346. TEST(ParityTest, Brotli) {
  12347. test_compression_parity<detail::brotli_compressor>(
  12348. "Hello, brotli parity test payload", "/parity-br", "br");
  12349. }
  12350. #endif
  12351. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12352. TEST(ParityTest, Zstd) {
  12353. test_compression_parity<detail::zstd_compressor>(
  12354. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12355. }
  12356. #endif
  12357. //==============================================================================
  12358. // New Stream API Tests
  12359. //==============================================================================
  12360. inline std::string read_body(httplib::stream::Result &result) {
  12361. std::string body;
  12362. while (result.next()) {
  12363. body.append(result.data(), result.size());
  12364. }
  12365. return body;
  12366. }
  12367. TEST(ClientConnectionTest, Basic) {
  12368. httplib::ClientConnection conn;
  12369. EXPECT_FALSE(conn.is_open());
  12370. conn.sock = 1;
  12371. EXPECT_TRUE(conn.is_open());
  12372. httplib::ClientConnection conn2(std::move(conn));
  12373. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12374. conn2.sock = INVALID_SOCKET;
  12375. }
  12376. // Unified test server for all stream::* tests
  12377. class StreamApiTest : public ::testing::Test {
  12378. protected:
  12379. void SetUp() override {
  12380. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12381. res.set_content("Hello World!", "text/plain");
  12382. });
  12383. svr_.Get("/echo-params",
  12384. [](const httplib::Request &req, httplib::Response &res) {
  12385. std::string r;
  12386. for (const auto &p : req.params) {
  12387. if (!r.empty()) r += "&";
  12388. r += p.first + "=" + p.second;
  12389. }
  12390. res.set_content(r, "text/plain");
  12391. });
  12392. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12393. res.set_content(req.body, req.get_header_value("Content-Type"));
  12394. });
  12395. svr_.Post("/echo-headers",
  12396. [](const httplib::Request &req, httplib::Response &res) {
  12397. std::string r;
  12398. for (const auto &h : req.headers)
  12399. r += h.first + ": " + h.second + "\n";
  12400. res.set_content(r, "text/plain");
  12401. });
  12402. svr_.Post("/echo-params",
  12403. [](const httplib::Request &req, httplib::Response &res) {
  12404. std::string r = "params:";
  12405. for (const auto &p : req.params)
  12406. r += p.first + "=" + p.second + ";";
  12407. res.set_content(r + " body:" + req.body, "text/plain");
  12408. });
  12409. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12410. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12411. });
  12412. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12413. res.set_content("PUT:" + req.body, "text/plain");
  12414. });
  12415. svr_.Patch("/echo",
  12416. [](const httplib::Request &req, httplib::Response &res) {
  12417. res.set_content("PATCH:" + req.body, "text/plain");
  12418. });
  12419. svr_.Delete(
  12420. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12421. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12422. "text/plain");
  12423. });
  12424. svr_.Get("/head-test",
  12425. [](const httplib::Request &, httplib::Response &res) {
  12426. res.set_content("body for HEAD", "text/plain");
  12427. });
  12428. svr_.Options("/options",
  12429. [](const httplib::Request &, httplib::Response &res) {
  12430. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12431. });
  12432. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12433. svr_.wait_until_ready();
  12434. }
  12435. void TearDown() override {
  12436. svr_.stop();
  12437. if (thread_.joinable()) thread_.join();
  12438. }
  12439. httplib::Server svr_;
  12440. std::thread thread_;
  12441. };
  12442. // stream::Get tests
  12443. TEST_F(StreamApiTest, GetBasic) {
  12444. httplib::Client cli(HOST, PORT);
  12445. auto result = httplib::stream::Get(cli, "/hello");
  12446. ASSERT_TRUE(result.is_valid());
  12447. EXPECT_EQ(200, result.status());
  12448. EXPECT_EQ("Hello World!", read_body(result));
  12449. }
  12450. TEST_F(StreamApiTest, GetWithParams) {
  12451. httplib::Client cli(HOST, PORT);
  12452. httplib::Params params{{"foo", "bar"}};
  12453. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12454. ASSERT_TRUE(result.is_valid());
  12455. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12456. }
  12457. TEST_F(StreamApiTest, GetConnectionError) {
  12458. httplib::Client cli(HOST, 9999);
  12459. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12460. }
  12461. TEST_F(StreamApiTest, Get404) {
  12462. httplib::Client cli(HOST, PORT);
  12463. auto result = httplib::stream::Get(cli, "/nonexistent");
  12464. EXPECT_TRUE(result.is_valid());
  12465. EXPECT_EQ(404, result.status());
  12466. }
  12467. // stream::Post tests
  12468. TEST_F(StreamApiTest, PostBasic) {
  12469. httplib::Client cli(HOST, PORT);
  12470. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12471. "application/json");
  12472. ASSERT_TRUE(result.is_valid());
  12473. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12474. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12475. }
  12476. TEST_F(StreamApiTest, PostWithHeaders) {
  12477. httplib::Client cli(HOST, PORT);
  12478. httplib::Headers headers{{"X-Custom", "value"}};
  12479. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12480. "text/plain");
  12481. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12482. }
  12483. TEST_F(StreamApiTest, PostWithParams) {
  12484. httplib::Client cli(HOST, PORT);
  12485. httplib::Params params{{"k", "v"}};
  12486. auto result =
  12487. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12488. auto body = read_body(result);
  12489. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12490. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12491. }
  12492. TEST_F(StreamApiTest, PostLarge) {
  12493. httplib::Client cli(HOST, PORT);
  12494. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12495. size_t total = 0;
  12496. while (result.next()) {
  12497. total += result.size();
  12498. }
  12499. EXPECT_EQ(100u * 1024u, total);
  12500. }
  12501. // stream::Put/Patch tests
  12502. TEST_F(StreamApiTest, PutAndPatch) {
  12503. httplib::Client cli(HOST, PORT);
  12504. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12505. EXPECT_EQ("PUT:test", read_body(put));
  12506. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12507. EXPECT_EQ("PATCH:test", read_body(patch));
  12508. }
  12509. // stream::Delete tests
  12510. TEST_F(StreamApiTest, Delete) {
  12511. httplib::Client cli(HOST, PORT);
  12512. auto del1 = httplib::stream::Delete(cli, "/resource");
  12513. EXPECT_EQ("Deleted", read_body(del1));
  12514. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12515. EXPECT_EQ("Deleted:data", read_body(del2));
  12516. }
  12517. // stream::Head/Options tests
  12518. TEST_F(StreamApiTest, HeadAndOptions) {
  12519. httplib::Client cli(HOST, PORT);
  12520. auto head = httplib::stream::Head(cli, "/head-test");
  12521. EXPECT_TRUE(head.is_valid());
  12522. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12523. auto opts = httplib::stream::Options(cli, "/options");
  12524. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12525. }
  12526. // SSL stream::* tests
  12527. #ifdef CPPHTTPLIB_SSL_ENABLED
  12528. class SSLStreamApiTest : public ::testing::Test {
  12529. protected:
  12530. void SetUp() override {
  12531. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12532. res.set_content("Hello SSL!", "text/plain");
  12533. });
  12534. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12535. res.set_content(req.body, "text/plain");
  12536. });
  12537. port_ = svr_.bind_to_any_port("127.0.0.1");
  12538. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12539. svr_.wait_until_ready();
  12540. }
  12541. void TearDown() override {
  12542. svr_.stop();
  12543. if (thread_.joinable()) thread_.join();
  12544. }
  12545. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12546. std::thread thread_;
  12547. int port_ = 0;
  12548. };
  12549. TEST_F(SSLStreamApiTest, GetAndPost) {
  12550. httplib::SSLClient cli("127.0.0.1", port_);
  12551. cli.enable_server_certificate_verification(false);
  12552. auto get = httplib::stream::Get(cli, "/hello");
  12553. EXPECT_EQ("Hello SSL!", read_body(get));
  12554. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12555. EXPECT_EQ("test", read_body(post));
  12556. }
  12557. #endif
  12558. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12559. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12560. // BodyReader
  12561. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12562. // Test that read timeout during streaming is detected
  12563. // Use a large content-length response where server delays mid-stream
  12564. Server svr;
  12565. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12566. // Send a large response with delay in the middle
  12567. res.set_content_provider(
  12568. 1000, // content_length
  12569. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12570. if (offset < 100) {
  12571. // Send first 100 bytes immediately
  12572. std::string data(100, 'A');
  12573. sink.write(data.c_str(), data.size());
  12574. return true;
  12575. }
  12576. // Then delay longer than client timeout
  12577. std::this_thread::sleep_for(std::chrono::seconds(3));
  12578. std::string data(900, 'B');
  12579. sink.write(data.c_str(), data.size());
  12580. return true;
  12581. });
  12582. });
  12583. auto port = 8091;
  12584. std::thread t([&]() { svr.listen("localhost", port); });
  12585. svr.wait_until_ready();
  12586. Client cli("localhost", port);
  12587. cli.set_read_timeout(1, 0); // 1 second timeout
  12588. auto handle = cli.open_stream("GET", "/slow-stream");
  12589. ASSERT_TRUE(handle.is_valid());
  12590. char buf[256];
  12591. ssize_t total = 0;
  12592. ssize_t n;
  12593. bool got_error = false;
  12594. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12595. total += n;
  12596. }
  12597. if (n < 0) {
  12598. got_error = true;
  12599. // Should be timeout or read error
  12600. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12601. handle.get_read_error() == Error::Read)
  12602. << "Actual error: " << to_string(handle.get_read_error());
  12603. }
  12604. // Either we got an error, or we got less data than expected
  12605. EXPECT_TRUE(got_error || total < 1000)
  12606. << "Expected timeout but got all " << total << " bytes";
  12607. svr.stop();
  12608. t.join();
  12609. }
  12610. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12611. // Test connection closed detection via BodyReader
  12612. Server svr;
  12613. std::atomic<bool> close_now{false};
  12614. svr.Get("/will-close", [&](const Request &, Response &res) {
  12615. res.set_content_provider(
  12616. 10000, // Large content_length that we won't fully send
  12617. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12618. if (offset < 100) {
  12619. std::string data(100, 'X');
  12620. sink.write(data.c_str(), data.size());
  12621. return true;
  12622. }
  12623. // Wait for signal then abort
  12624. while (!close_now) {
  12625. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12626. }
  12627. return false; // Abort - server will close connection
  12628. });
  12629. });
  12630. auto port = 8092;
  12631. std::thread t([&]() { svr.listen("localhost", port); });
  12632. svr.wait_until_ready();
  12633. Client cli("localhost", port);
  12634. auto handle = cli.open_stream("GET", "/will-close");
  12635. ASSERT_TRUE(handle.is_valid());
  12636. char buf[256];
  12637. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12638. EXPECT_GT(n, 0) << "First read should succeed";
  12639. // Signal server to close
  12640. close_now = true;
  12641. // Keep reading until error or EOF
  12642. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12643. // Keep reading
  12644. }
  12645. // Should get an error since content_length wasn't satisfied
  12646. if (n < 0) {
  12647. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12648. handle.get_read_error() == Error::Read)
  12649. << "Actual error: " << to_string(handle.get_read_error());
  12650. }
  12651. svr.stop();
  12652. t.join();
  12653. }
  12654. #ifdef CPPHTTPLIB_SSL_ENABLED
  12655. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12656. // Test that read timeout during SSL streaming is detected
  12657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12658. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12659. res.set_content_provider(
  12660. 1000, "text/plain",
  12661. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12662. if (offset < 100) {
  12663. std::string data(100, 'A');
  12664. sink.write(data.c_str(), data.size());
  12665. return true;
  12666. }
  12667. std::this_thread::sleep_for(std::chrono::seconds(3));
  12668. std::string data(900, 'B');
  12669. sink.write(data.c_str(), data.size());
  12670. return true;
  12671. });
  12672. });
  12673. auto port = 8093;
  12674. std::thread t([&]() { svr.listen("localhost", port); });
  12675. svr.wait_until_ready();
  12676. SSLClient cli("localhost", port);
  12677. cli.enable_server_certificate_verification(false);
  12678. cli.set_read_timeout(1, 0); // 1 second timeout
  12679. auto handle = cli.open_stream("GET", "/slow-stream");
  12680. ASSERT_TRUE(handle.is_valid());
  12681. char buf[256];
  12682. ssize_t total = 0;
  12683. ssize_t n;
  12684. bool got_error = false;
  12685. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12686. total += n;
  12687. }
  12688. if (n < 0) {
  12689. got_error = true;
  12690. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12691. handle.get_read_error() == Error::Read)
  12692. << "Actual error: " << to_string(handle.get_read_error());
  12693. }
  12694. EXPECT_TRUE(got_error || total < 1000)
  12695. << "Expected timeout but got all " << total << " bytes";
  12696. svr.stop();
  12697. t.join();
  12698. }
  12699. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12700. // Test SSL connection closed detection
  12701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12702. std::atomic<bool> close_now{false};
  12703. svr.Get("/will-close", [&](const Request &, Response &res) {
  12704. res.set_content_provider(
  12705. 10000, "text/plain",
  12706. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12707. if (offset < 100) {
  12708. std::string data(100, 'X');
  12709. sink.write(data.c_str(), data.size());
  12710. return true;
  12711. }
  12712. while (!close_now) {
  12713. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12714. }
  12715. return false;
  12716. });
  12717. });
  12718. auto port = 8094;
  12719. std::thread t([&]() { svr.listen("localhost", port); });
  12720. svr.wait_until_ready();
  12721. SSLClient cli("localhost", port);
  12722. cli.enable_server_certificate_verification(false);
  12723. auto handle = cli.open_stream("GET", "/will-close");
  12724. ASSERT_TRUE(handle.is_valid());
  12725. char buf[256];
  12726. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12727. EXPECT_GT(n, 0);
  12728. // Signal server to close
  12729. close_now = true;
  12730. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12731. // Keep reading
  12732. }
  12733. if (n < 0) {
  12734. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12735. handle.get_read_error() == Error::Read)
  12736. << "Actual error: " << to_string(handle.get_read_error());
  12737. }
  12738. svr.stop();
  12739. t.join();
  12740. }
  12741. #endif
  12742. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12743. using namespace httplib;
  12744. // Create a test file
  12745. const char *fname = "etag_testfile.txt";
  12746. const char *content = "etag-content";
  12747. {
  12748. std::ofstream ofs(fname);
  12749. ofs << content;
  12750. ASSERT_TRUE(ofs.good());
  12751. }
  12752. Server svr;
  12753. svr.set_mount_point("/static", ".");
  12754. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12755. svr.wait_until_ready();
  12756. Client cli(HOST, PORT);
  12757. // First request: should get 200 with ETag header
  12758. auto res1 = cli.Get("/static/etag_testfile.txt");
  12759. ASSERT_TRUE(res1);
  12760. ASSERT_EQ(200, res1->status);
  12761. ASSERT_TRUE(res1->has_header("ETag"));
  12762. std::string etag = res1->get_header_value("ETag");
  12763. EXPECT_FALSE(etag.empty());
  12764. // Verify ETag format: W/"hex-hex"
  12765. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12766. EXPECT_EQ('W', etag[0]);
  12767. EXPECT_EQ('/', etag[1]);
  12768. EXPECT_EQ('"', etag[2]);
  12769. EXPECT_EQ('"', etag.back());
  12770. // Exact match: expect 304 Not Modified
  12771. Headers h2 = {{"If-None-Match", etag}};
  12772. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12773. ASSERT_TRUE(res2);
  12774. EXPECT_EQ(304, res2->status);
  12775. // Wildcard match: expect 304 Not Modified
  12776. Headers h3 = {{"If-None-Match", "*"}};
  12777. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12778. ASSERT_TRUE(res3);
  12779. EXPECT_EQ(304, res3->status);
  12780. // Non-matching ETag: expect 200
  12781. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12782. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12783. ASSERT_TRUE(res4);
  12784. EXPECT_EQ(200, res4->status);
  12785. // Multiple ETags with one matching: expect 304
  12786. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12787. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12788. ASSERT_TRUE(res5);
  12789. EXPECT_EQ(304, res5->status);
  12790. svr.stop();
  12791. t.join();
  12792. std::remove(fname);
  12793. }
  12794. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12795. using namespace httplib;
  12796. Server svr;
  12797. svr.set_mount_point("/static", ".");
  12798. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12799. svr.wait_until_ready();
  12800. Client cli(HOST, PORT);
  12801. // Send If-None-Match: * to a non-existent file
  12802. Headers h = {{"If-None-Match", "*"}};
  12803. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12804. ASSERT_TRUE(res);
  12805. EXPECT_EQ(404, res->status);
  12806. svr.stop();
  12807. t.join();
  12808. }
  12809. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12810. using namespace httplib;
  12811. // Create a test file
  12812. const char *fname = "etag_boundary_testfile.txt";
  12813. const char *content = "boundary-test";
  12814. {
  12815. std::ofstream ofs(fname);
  12816. ofs << content;
  12817. ASSERT_TRUE(ofs.good());
  12818. }
  12819. Server svr;
  12820. svr.set_mount_point("/static", ".");
  12821. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12822. svr.wait_until_ready();
  12823. Client cli(HOST, PORT);
  12824. // Get the actual ETag
  12825. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12826. ASSERT_TRUE(res1);
  12827. ASSERT_EQ(200, res1->status);
  12828. ASSERT_TRUE(res1->has_header("ETag"));
  12829. std::string etag = res1->get_header_value("ETag");
  12830. // Test 1: Very long ETag value (longer than actual ETag)
  12831. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12832. Headers h1 = {{"If-None-Match", "W/"
  12833. "\"very-long-etag-value-that-is-much-longer-"
  12834. "than-the-actual-etag-value\""}};
  12835. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12836. ASSERT_TRUE(res2);
  12837. EXPECT_EQ(200, res2->status); // Should not match
  12838. // Test 2: Long string followed by wildcard
  12839. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12840. // string)
  12841. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12842. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12843. ASSERT_TRUE(res3);
  12844. EXPECT_EQ(304, res3->status); // Should match on "*"
  12845. // Test 3: Wildcard followed by long string
  12846. // Should match on "*" immediately and return 304
  12847. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12848. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12849. ASSERT_TRUE(res4);
  12850. EXPECT_EQ(304, res4->status); // Should match on "*"
  12851. // Test 4: Multiple long non-matching values
  12852. // Should NOT match and return 200 (test that all comparisons are safe)
  12853. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12854. "W/\"second-long-non-matching-value\", "
  12855. "W/\"third-long-non-matching-value\""}};
  12856. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12857. ASSERT_TRUE(res5);
  12858. EXPECT_EQ(200, res5->status); // Should not match
  12859. // Test 5: Single character that is not "*" (edge case)
  12860. Headers h5 = {{"If-None-Match", "X"}};
  12861. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12862. ASSERT_TRUE(res6);
  12863. EXPECT_EQ(200, res6->status); // Should not match
  12864. svr.stop();
  12865. t.join();
  12866. std::remove(fname);
  12867. }
  12868. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12869. using namespace httplib;
  12870. // Create a test file
  12871. const char *fname = "ims_testfile.txt";
  12872. const char *content = "if-modified-since-test";
  12873. {
  12874. std::ofstream ofs(fname);
  12875. ofs << content;
  12876. ASSERT_TRUE(ofs.good());
  12877. }
  12878. Server svr;
  12879. svr.set_mount_point("/static", ".");
  12880. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12881. svr.wait_until_ready();
  12882. Client cli(HOST, PORT);
  12883. // First request: should get 200 with Last-Modified header
  12884. auto res1 = cli.Get("/static/ims_testfile.txt");
  12885. ASSERT_TRUE(res1);
  12886. ASSERT_EQ(200, res1->status);
  12887. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12888. std::string last_modified = res1->get_header_value("Last-Modified");
  12889. EXPECT_FALSE(last_modified.empty());
  12890. // If-Modified-Since with same time: expect 304
  12891. Headers h2 = {{"If-Modified-Since", last_modified}};
  12892. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12893. ASSERT_TRUE(res2);
  12894. EXPECT_EQ(304, res2->status);
  12895. // If-Modified-Since with future time: expect 304
  12896. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12897. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12898. ASSERT_TRUE(res3);
  12899. EXPECT_EQ(304, res3->status);
  12900. // If-Modified-Since with past time: expect 200
  12901. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12902. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12903. ASSERT_TRUE(res4);
  12904. EXPECT_EQ(200, res4->status);
  12905. // If-None-Match takes precedence over If-Modified-Since
  12906. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12907. ASSERT_TRUE(res1->has_header("ETag"));
  12908. std::string etag = res1->get_header_value("ETag");
  12909. Headers h5 = {{"If-None-Match", etag},
  12910. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12911. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12912. ASSERT_TRUE(res5);
  12913. EXPECT_EQ(304, res5->status);
  12914. svr.stop();
  12915. t.join();
  12916. std::remove(fname);
  12917. }
  12918. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12919. using namespace httplib;
  12920. Server svr;
  12921. // Endpoint that returns compressible content
  12922. svr.Get("/compressible", [](const Request &, Response &res) {
  12923. // Return a large enough body to trigger compression
  12924. std::string body(1000, 'a');
  12925. res.set_content(body, "text/plain");
  12926. });
  12927. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12928. svr.wait_until_ready();
  12929. Client cli(HOST, PORT);
  12930. // Request with gzip support: should get Vary header when compressed
  12931. cli.set_compress(true);
  12932. auto res1 = cli.Get("/compressible");
  12933. ASSERT_TRUE(res1);
  12934. EXPECT_EQ(200, res1->status);
  12935. // If Content-Encoding is set, Vary should also be set
  12936. if (res1->has_header("Content-Encoding")) {
  12937. EXPECT_TRUE(res1->has_header("Vary"));
  12938. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12939. }
  12940. // Request without Accept-Encoding header: should not have compression
  12941. Headers h_no_compress;
  12942. auto res2 = cli.Get("/compressible", h_no_compress);
  12943. ASSERT_TRUE(res2);
  12944. EXPECT_EQ(200, res2->status);
  12945. // Verify Vary header is present when compression is applied
  12946. // (the exact behavior depends on server configuration)
  12947. svr.stop();
  12948. t.join();
  12949. }
  12950. TEST(ETagTest, IfRangeWithETag) {
  12951. using namespace httplib;
  12952. // Create a test file with known content
  12953. const char *fname = "if_range_testfile.txt";
  12954. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12955. {
  12956. std::ofstream ofs(fname);
  12957. ofs << content;
  12958. ASSERT_TRUE(ofs.good());
  12959. }
  12960. Server svr;
  12961. svr.set_mount_point("/static", ".");
  12962. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12963. svr.wait_until_ready();
  12964. Client cli(HOST, PORT);
  12965. // First request: get ETag
  12966. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12967. ASSERT_TRUE(res1);
  12968. ASSERT_EQ(200, res1->status);
  12969. ASSERT_TRUE(res1->has_header("ETag"));
  12970. std::string etag = res1->get_header_value("ETag");
  12971. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12972. // Since our server generates weak ETags (W/"..."), If-Range with our
  12973. // ETag should NOT result in partial content - it should return full content.
  12974. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12975. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12976. ASSERT_TRUE(res2);
  12977. // Weak ETag in If-Range -> full content (200), not partial (206)
  12978. EXPECT_EQ(200, res2->status);
  12979. EXPECT_EQ(content, res2->body);
  12980. EXPECT_FALSE(res2->has_header("Content-Range"));
  12981. // Range request with non-matching If-Range (ETag): should get 200 (full
  12982. // content)
  12983. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12984. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12985. ASSERT_TRUE(res3);
  12986. EXPECT_EQ(200, res3->status);
  12987. EXPECT_EQ(content, res3->body);
  12988. EXPECT_FALSE(res3->has_header("Content-Range"));
  12989. // Range request with strong ETag (hypothetical - our server doesn't generate
  12990. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12991. // should return full content)
  12992. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12993. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12994. ASSERT_TRUE(res4);
  12995. EXPECT_EQ(200, res4->status);
  12996. EXPECT_EQ(content, res4->body);
  12997. EXPECT_FALSE(res4->has_header("Content-Range"));
  12998. svr.stop();
  12999. t.join();
  13000. std::remove(fname);
  13001. }
  13002. TEST(ETagTest, IfRangeWithDate) {
  13003. using namespace httplib;
  13004. // Create a test file
  13005. const char *fname = "if_range_date_testfile.txt";
  13006. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  13007. {
  13008. std::ofstream ofs(fname);
  13009. ofs << content;
  13010. ASSERT_TRUE(ofs.good());
  13011. }
  13012. Server svr;
  13013. svr.set_mount_point("/static", ".");
  13014. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13015. svr.wait_until_ready();
  13016. Client cli(HOST, PORT);
  13017. // First request: get Last-Modified
  13018. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  13019. ASSERT_TRUE(res1);
  13020. ASSERT_EQ(200, res1->status);
  13021. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13022. std::string last_modified = res1->get_header_value("Last-Modified");
  13023. // Range request with matching If-Range (date): should get 206
  13024. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  13025. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  13026. ASSERT_TRUE(res2);
  13027. EXPECT_EQ(206, res2->status);
  13028. EXPECT_EQ("FGHIJ", res2->body);
  13029. // Range request with old If-Range date: should get 200 (full content)
  13030. Headers h3 = {{"Range", "bytes=5-9"},
  13031. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  13032. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  13033. ASSERT_TRUE(res3);
  13034. EXPECT_EQ(200, res3->status);
  13035. EXPECT_EQ(content, res3->body);
  13036. // Range request with future If-Range date: should get 206
  13037. Headers h4 = {{"Range", "bytes=0-4"},
  13038. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  13039. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  13040. ASSERT_TRUE(res4);
  13041. EXPECT_EQ(206, res4->status);
  13042. EXPECT_EQ("ABCDE", res4->body);
  13043. svr.stop();
  13044. t.join();
  13045. std::remove(fname);
  13046. }
  13047. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  13048. using namespace httplib;
  13049. const char *fname = "etag_malformed.txt";
  13050. const char *content = "malformed-etag";
  13051. {
  13052. std::ofstream ofs(fname);
  13053. ofs << content;
  13054. ASSERT_TRUE(ofs.good());
  13055. }
  13056. Server svr;
  13057. svr.set_mount_point("/static", ".");
  13058. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13059. svr.wait_until_ready();
  13060. Client cli(HOST, PORT);
  13061. // baseline: should get 200 and an ETag
  13062. auto res1 = cli.Get("/static/etag_malformed.txt");
  13063. ASSERT_TRUE(res1);
  13064. ASSERT_EQ(200, res1->status);
  13065. ASSERT_TRUE(res1->has_header("ETag"));
  13066. // Malformed ETag value (missing quotes) should be treated as non-matching
  13067. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  13068. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  13069. ASSERT_TRUE(res_bad);
  13070. EXPECT_EQ(200, res_bad->status);
  13071. // Whitespace-only header value should be considered invalid / non-matching
  13072. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  13073. "Host: localhost\r\n"
  13074. "If-None-Match: \r\n"
  13075. "Connection: close\r\n"
  13076. "\r\n";
  13077. std::string out;
  13078. ASSERT_TRUE(send_request(5, raw_req, &out));
  13079. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  13080. svr.stop();
  13081. t.join();
  13082. std::remove(fname);
  13083. }
  13084. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  13085. using namespace httplib;
  13086. const char *fname = "ims_invalid_format.txt";
  13087. const char *content = "ims-bad-format";
  13088. {
  13089. std::ofstream ofs(fname);
  13090. ofs << content;
  13091. ASSERT_TRUE(ofs.good());
  13092. }
  13093. Server svr;
  13094. svr.set_mount_point("/static", ".");
  13095. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13096. svr.wait_until_ready();
  13097. Client cli(HOST, PORT);
  13098. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  13099. ASSERT_TRUE(res1);
  13100. ASSERT_EQ(200, res1->status);
  13101. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13102. // If-Modified-Since with invalid format should not result in 304
  13103. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  13104. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  13105. ASSERT_TRUE(res_bad);
  13106. EXPECT_EQ(200, res_bad->status);
  13107. // If-Range with invalid date format should be treated as mismatch -> full
  13108. // content (200)
  13109. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  13110. {"If-Range", "invalid-date"}};
  13111. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  13112. ASSERT_TRUE(res_ifrange);
  13113. EXPECT_EQ(200, res_ifrange->status);
  13114. svr.stop();
  13115. t.join();
  13116. std::remove(fname);
  13117. }
  13118. TEST(ETagTest, IfRangeWithMalformedETag) {
  13119. using namespace httplib;
  13120. const char *fname = "ifrange_malformed.txt";
  13121. const std::string content = "0123456789";
  13122. {
  13123. std::ofstream ofs(fname);
  13124. ofs << content;
  13125. ASSERT_TRUE(ofs.good());
  13126. }
  13127. Server svr;
  13128. svr.set_mount_point("/static", ".");
  13129. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13130. svr.wait_until_ready();
  13131. Client cli(HOST, PORT);
  13132. // First request: get ETag
  13133. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  13134. ASSERT_TRUE(res1);
  13135. ASSERT_EQ(200, res1->status);
  13136. ASSERT_TRUE(res1->has_header("ETag"));
  13137. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  13138. // full content (200)
  13139. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  13140. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  13141. ASSERT_TRUE(res2);
  13142. EXPECT_EQ(200, res2->status);
  13143. EXPECT_EQ(content, res2->body);
  13144. svr.stop();
  13145. t.join();
  13146. std::remove(fname);
  13147. }
  13148. TEST(ETagTest, ExtremeLargeDateValues) {
  13149. using namespace httplib;
  13150. const char *fname = "ims_extreme_date.txt";
  13151. const char *content = "ims-extreme-date";
  13152. {
  13153. std::ofstream ofs(fname);
  13154. ofs << content;
  13155. ASSERT_TRUE(ofs.good());
  13156. }
  13157. Server svr;
  13158. svr.set_mount_point("/static", ".");
  13159. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13160. svr.wait_until_ready();
  13161. Client cli(HOST, PORT);
  13162. auto res1 = cli.Get(std::string("/static/") + fname);
  13163. ASSERT_TRUE(res1);
  13164. ASSERT_EQ(200, res1->status);
  13165. ASSERT_TRUE(res1->has_header("Last-Modified"));
  13166. // Extremely large year that may overflow date parsing routines.
  13167. Headers h_large_date = {
  13168. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13169. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  13170. ASSERT_TRUE(res_bad);
  13171. // Expect server to treat this as invalid/mismatch and return full content
  13172. EXPECT_EQ(200, res_bad->status);
  13173. // If-Range with extremely large date should be treated as mismatch -> full
  13174. // content (200)
  13175. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  13176. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13177. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  13178. ASSERT_TRUE(res_ifrange);
  13179. EXPECT_EQ(200, res_ifrange->status);
  13180. svr.stop();
  13181. t.join();
  13182. std::remove(fname);
  13183. }
  13184. TEST(ETagTest, NegativeFileModificationTime) {
  13185. using namespace httplib;
  13186. const char *fname = "ims_negative_mtime.txt";
  13187. const std::string content = "negative-mtime";
  13188. {
  13189. std::ofstream ofs(fname);
  13190. ofs << content;
  13191. ASSERT_TRUE(ofs.good());
  13192. }
  13193. // Try to set file mtime to a negative value. This may fail on some
  13194. // platforms/filesystems; if it fails, the test will still verify server
  13195. // behaves safely by performing a regular conditional request.
  13196. #if defined(__APPLE__) || defined(__linux__)
  13197. bool set_negative = false;
  13198. do {
  13199. struct timeval times[2];
  13200. // access time: now
  13201. times[0].tv_sec = time(nullptr);
  13202. times[0].tv_usec = 0;
  13203. // modification time: negative (e.g., -1)
  13204. times[1].tv_sec = -1;
  13205. times[1].tv_usec = 0;
  13206. if (utimes(fname, times) == 0) { set_negative = true; }
  13207. } while (0);
  13208. #else
  13209. bool set_negative = false;
  13210. #endif
  13211. Server svr;
  13212. svr.set_mount_point("/static", ".");
  13213. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13214. svr.wait_until_ready();
  13215. Client cli(HOST, PORT);
  13216. auto res1 = cli.Get(std::string("/static/") + fname);
  13217. ASSERT_TRUE(res1);
  13218. ASSERT_EQ(200, res1->status);
  13219. bool has_last_modified = res1->has_header("Last-Modified");
  13220. std::string last_modified;
  13221. if (has_last_modified) {
  13222. last_modified = res1->get_header_value("Last-Modified");
  13223. }
  13224. if (set_negative) {
  13225. // If we successfully set a negative mtime, ensure server returns a
  13226. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13227. // with an old date and ensure server handles it without crash.
  13228. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13229. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13230. ASSERT_TRUE(res2);
  13231. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13232. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13233. } else {
  13234. // Could not set negative mtime on this platform; fall back to verifying
  13235. // that normal invalid/malformed dates are treated safely (non-304).
  13236. Headers h_bad_date = {
  13237. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13238. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13239. ASSERT_TRUE(res_bad);
  13240. EXPECT_EQ(200, res_bad->status);
  13241. }
  13242. svr.stop();
  13243. t.join();
  13244. std::remove(fname);
  13245. }
  13246. //==============================================================================
  13247. // SSE Parsing Tests
  13248. //==============================================================================
  13249. class SSEParsingTest : public ::testing::Test {
  13250. protected:
  13251. // Test helper that mimics SSE parsing behavior
  13252. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13253. int &retry_ms) {
  13254. // Blank line signals end of event
  13255. if (line.empty() || line == "\r") { return true; }
  13256. // Lines starting with ':' are comments (ignored)
  13257. if (!line.empty() && line[0] == ':') { return false; }
  13258. // Find the colon separator
  13259. auto colon_pos = line.find(':');
  13260. if (colon_pos == std::string::npos) {
  13261. // Line with no colon is treated as field name with empty value
  13262. return false;
  13263. }
  13264. std::string field = line.substr(0, colon_pos);
  13265. std::string value;
  13266. // Value starts after colon, skip optional single space
  13267. if (colon_pos + 1 < line.size()) {
  13268. size_t value_start = colon_pos + 1;
  13269. if (line[value_start] == ' ') { value_start++; }
  13270. value = line.substr(value_start);
  13271. // Remove trailing \r if present
  13272. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13273. }
  13274. // Handle known fields
  13275. if (field == "event") {
  13276. msg.event = value;
  13277. } else if (field == "data") {
  13278. // Multiple data lines are concatenated with newlines
  13279. if (!msg.data.empty()) { msg.data += "\n"; }
  13280. msg.data += value;
  13281. } else if (field == "id") {
  13282. // Empty id is valid (clears the last event ID)
  13283. msg.id = value;
  13284. } else if (field == "retry") {
  13285. // Parse retry interval in milliseconds
  13286. {
  13287. int v = 0;
  13288. auto res =
  13289. detail::from_chars(value.data(), value.data() + value.size(), v);
  13290. if (res.ec == std::errc{}) { retry_ms = v; }
  13291. }
  13292. }
  13293. // Unknown fields are ignored per SSE spec
  13294. return false;
  13295. }
  13296. };
  13297. // Test: Single-line data
  13298. TEST_F(SSEParsingTest, SingleLineData) {
  13299. sse::SSEMessage msg;
  13300. int retry_ms = 3000;
  13301. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13302. EXPECT_EQ(msg.data, "hello");
  13303. EXPECT_EQ(msg.event, "message");
  13304. // Blank line ends event
  13305. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13306. }
  13307. // Test: Multi-line data
  13308. TEST_F(SSEParsingTest, MultiLineData) {
  13309. sse::SSEMessage msg;
  13310. int retry_ms = 3000;
  13311. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13312. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13313. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13314. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13315. }
  13316. // Test: Custom event types
  13317. TEST_F(SSEParsingTest, CustomEventType) {
  13318. sse::SSEMessage msg;
  13319. int retry_ms = 3000;
  13320. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13321. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13322. EXPECT_EQ(msg.event, "update");
  13323. EXPECT_EQ(msg.data, "payload");
  13324. }
  13325. // Test: Event ID handling
  13326. TEST_F(SSEParsingTest, EventIdHandling) {
  13327. sse::SSEMessage msg;
  13328. int retry_ms = 3000;
  13329. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13330. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13331. EXPECT_EQ(msg.id, "12345");
  13332. }
  13333. // Test: Empty event ID (clears last event ID)
  13334. TEST_F(SSEParsingTest, EmptyEventId) {
  13335. sse::SSEMessage msg;
  13336. msg.id = "previous";
  13337. int retry_ms = 3000;
  13338. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13339. EXPECT_EQ(msg.id, "");
  13340. }
  13341. // Test: Retry field parsing
  13342. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13343. sse::SSEMessage msg;
  13344. int retry_ms = 3000;
  13345. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13346. EXPECT_EQ(retry_ms, 5000);
  13347. }
  13348. // Test: Invalid retry value
  13349. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13350. sse::SSEMessage msg;
  13351. int retry_ms = 3000;
  13352. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13353. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13354. }
  13355. // Test: Comments (lines starting with :)
  13356. TEST_F(SSEParsingTest, CommentsIgnored) {
  13357. sse::SSEMessage msg;
  13358. int retry_ms = 3000;
  13359. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13360. EXPECT_EQ(msg.data, "");
  13361. EXPECT_EQ(msg.event, "message");
  13362. }
  13363. // Test: Colon in value
  13364. TEST_F(SSEParsingTest, ColonInValue) {
  13365. sse::SSEMessage msg;
  13366. int retry_ms = 3000;
  13367. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13368. EXPECT_EQ(msg.data, "hello:world:test");
  13369. }
  13370. // Test: Line with no colon (field name only)
  13371. TEST_F(SSEParsingTest, FieldNameOnly) {
  13372. sse::SSEMessage msg;
  13373. int retry_ms = 3000;
  13374. // According to SSE spec, this is treated as field name with empty value
  13375. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13376. // Since we don't recognize "data" without colon, data should be empty
  13377. EXPECT_EQ(msg.data, "");
  13378. }
  13379. // Test: Trailing \r handling
  13380. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13381. sse::SSEMessage msg;
  13382. int retry_ms = 3000;
  13383. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13384. EXPECT_EQ(msg.data, "hello");
  13385. }
  13386. // Test: Unknown fields ignored
  13387. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13388. sse::SSEMessage msg;
  13389. int retry_ms = 3000;
  13390. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13391. EXPECT_EQ(msg.data, "");
  13392. EXPECT_EQ(msg.event, "message");
  13393. }
  13394. // Test: Space after colon is optional
  13395. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13396. sse::SSEMessage msg1, msg2;
  13397. int retry_ms = 3000;
  13398. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13399. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13400. EXPECT_EQ(msg1.data, "hello");
  13401. EXPECT_EQ(msg2.data, "hello");
  13402. }
  13403. // Test: SSEMessage clear
  13404. TEST_F(SSEParsingTest, MessageClear) {
  13405. sse::SSEMessage msg;
  13406. msg.event = "custom";
  13407. msg.data = "some data";
  13408. msg.id = "123";
  13409. msg.clear();
  13410. EXPECT_EQ(msg.event, "message");
  13411. EXPECT_EQ(msg.data, "");
  13412. EXPECT_EQ(msg.id, "");
  13413. }
  13414. // Test: Complete event parsing
  13415. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13416. sse::SSEMessage msg;
  13417. int retry_ms = 3000;
  13418. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13419. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13420. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13421. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13422. // Blank line ends event
  13423. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13424. EXPECT_EQ(msg.event, "notification");
  13425. EXPECT_EQ(msg.id, "evt-42");
  13426. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13427. EXPECT_EQ(retry_ms, 1000);
  13428. }
  13429. //==============================================================================
  13430. // Integration Tests with Server
  13431. //==============================================================================
  13432. class SSEIntegrationTest : public ::testing::Test {
  13433. protected:
  13434. void SetUp() override {
  13435. stop_server_.store(false);
  13436. events_.clear();
  13437. server_ = httplib::detail::make_unique<Server>();
  13438. setup_server();
  13439. start_server();
  13440. }
  13441. void TearDown() override {
  13442. stop_server_.store(true);
  13443. event_cv_.notify_all();
  13444. server_->stop();
  13445. if (server_thread_.joinable()) { server_thread_.join(); }
  13446. }
  13447. void setup_server() {
  13448. // Simple SSE endpoint
  13449. server_->Get("/events", [this](const Request &req, Response &res) {
  13450. auto last_id = req.get_header_value("Last-Event-ID");
  13451. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13452. res.set_chunked_content_provider(
  13453. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13454. std::unique_lock<std::mutex> lock(event_mutex_);
  13455. if (event_cv_.wait_for(
  13456. lock, std::chrono::milliseconds(200), [this] {
  13457. return !events_.empty() || stop_server_.load();
  13458. })) {
  13459. if (stop_server_.load()) { return false; }
  13460. if (!events_.empty()) {
  13461. std::string event = events_.front();
  13462. events_.erase(events_.begin());
  13463. sink.write(event.data(), event.size());
  13464. return true;
  13465. }
  13466. }
  13467. return !stop_server_.load();
  13468. });
  13469. });
  13470. // Endpoint that returns error
  13471. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13472. res.status = 500;
  13473. res.set_content("Internal Server Error", "text/plain");
  13474. });
  13475. // Endpoint for custom event types
  13476. server_->Get("/custom-events", [](const Request &, Response &res) {
  13477. res.set_chunked_content_provider(
  13478. "text/event-stream", [](size_t offset, DataSink &sink) {
  13479. if (offset == 0) {
  13480. std::string event = "event: update\ndata: updated\n\n"
  13481. "event: delete\ndata: deleted\n\n";
  13482. sink.write(event.data(), event.size());
  13483. }
  13484. return false; // End stream after sending
  13485. });
  13486. });
  13487. }
  13488. void start_server() {
  13489. port_ = server_->bind_to_any_port(HOST);
  13490. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13491. // Wait for server to start
  13492. while (!server_->is_running()) {
  13493. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13494. }
  13495. }
  13496. int get_port() const { return port_; }
  13497. void send_event(const std::string &event) {
  13498. std::lock_guard<std::mutex> lock(event_mutex_);
  13499. events_.push_back(event);
  13500. event_cv_.notify_all();
  13501. }
  13502. std::unique_ptr<Server> server_;
  13503. std::thread server_thread_;
  13504. std::mutex event_mutex_;
  13505. std::condition_variable event_cv_;
  13506. std::vector<std::string> events_;
  13507. std::atomic<bool> stop_server_{false};
  13508. std::string last_received_event_id_;
  13509. int port_ = 0;
  13510. };
  13511. // Test: Successful connection and on_open callback
  13512. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13513. // Add a simple endpoint that sends one event and closes
  13514. server_->Get("/simple-event", [](const Request &, Response &res) {
  13515. res.set_chunked_content_provider(
  13516. "text/event-stream", [](size_t offset, DataSink &sink) {
  13517. if (offset == 0) {
  13518. std::string event = "data: hello\n\n";
  13519. sink.write(event.data(), event.size());
  13520. }
  13521. return false; // Close stream after sending
  13522. });
  13523. });
  13524. Client client("localhost", get_port());
  13525. sse::SSEClient sse(client, "/simple-event");
  13526. std::atomic<bool> open_called{false};
  13527. std::atomic<bool> message_received{false};
  13528. sse.on_open([&open_called]() { open_called.store(true); });
  13529. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13530. if (msg.data == "hello") { message_received.store(true); }
  13531. });
  13532. sse.set_reconnect_interval(100);
  13533. sse.set_max_reconnect_attempts(1);
  13534. // Start async
  13535. sse.start_async();
  13536. // Wait for message to be processed
  13537. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13538. sse.stop();
  13539. EXPECT_TRUE(open_called.load());
  13540. EXPECT_TRUE(message_received.load());
  13541. }
  13542. // Test: on_message callback
  13543. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13544. // Endpoint that sends multiple events then closes
  13545. server_->Get("/multi-event", [](const Request &, Response &res) {
  13546. res.set_chunked_content_provider(
  13547. "text/event-stream", [](size_t offset, DataSink &sink) {
  13548. if (offset == 0) {
  13549. std::string events = "data: message1\n\ndata: message2\n\n";
  13550. sink.write(events.data(), events.size());
  13551. }
  13552. return false;
  13553. });
  13554. });
  13555. Client client("localhost", get_port());
  13556. sse::SSEClient sse(client, "/multi-event");
  13557. std::vector<std::string> received_messages;
  13558. std::mutex messages_mutex;
  13559. sse.on_message([&](const sse::SSEMessage &msg) {
  13560. std::lock_guard<std::mutex> lock(messages_mutex);
  13561. received_messages.push_back(msg.data);
  13562. });
  13563. sse.set_reconnect_interval(100);
  13564. sse.set_max_reconnect_attempts(1);
  13565. sse.start_async();
  13566. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13567. sse.stop();
  13568. std::lock_guard<std::mutex> lock(messages_mutex);
  13569. EXPECT_GE(received_messages.size(), 2u);
  13570. if (received_messages.size() >= 2) {
  13571. EXPECT_EQ(received_messages[0], "message1");
  13572. EXPECT_EQ(received_messages[1], "message2");
  13573. }
  13574. }
  13575. // Test: on_event for specific types
  13576. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13577. Client client("localhost", get_port());
  13578. sse::SSEClient sse(client, "/custom-events");
  13579. std::atomic<bool> update_received{false};
  13580. std::atomic<bool> delete_received{false};
  13581. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13582. if (msg.data == "updated") { update_received.store(true); }
  13583. });
  13584. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13585. if (msg.data == "deleted") { delete_received.store(true); }
  13586. });
  13587. sse.set_max_reconnect_attempts(1);
  13588. sse.start_async();
  13589. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13590. sse.stop();
  13591. EXPECT_TRUE(update_received.load());
  13592. EXPECT_TRUE(delete_received.load());
  13593. }
  13594. // Test: on_error callback on connection failure
  13595. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13596. // Connect to a non-existent port
  13597. Client client("localhost", 59999);
  13598. sse::SSEClient sse(client, "/events");
  13599. std::atomic<bool> error_called{false};
  13600. Error received_error = Error::Success;
  13601. sse.on_error([&](Error err) {
  13602. error_called.store(true);
  13603. received_error = err;
  13604. });
  13605. sse.set_reconnect_interval(50);
  13606. sse.set_max_reconnect_attempts(1);
  13607. sse.start_async();
  13608. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13609. sse.stop();
  13610. EXPECT_TRUE(error_called.load());
  13611. EXPECT_NE(received_error, Error::Success);
  13612. }
  13613. // Test: Last-Event-ID header sent on reconnect
  13614. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13615. // Endpoint that sends event with ID
  13616. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13617. res.set_chunked_content_provider(
  13618. "text/event-stream", [](size_t offset, DataSink &sink) {
  13619. if (offset == 0) {
  13620. std::string event = "id: evt-123\ndata: test\n\n";
  13621. sink.write(event.data(), event.size());
  13622. }
  13623. return false;
  13624. });
  13625. });
  13626. Client client("localhost", get_port());
  13627. sse::SSEClient sse(client, "/event-with-id");
  13628. std::atomic<bool> id_received{false};
  13629. sse.on_message([&](const sse::SSEMessage &msg) {
  13630. if (!msg.id.empty()) { id_received.store(true); }
  13631. });
  13632. sse.set_reconnect_interval(100);
  13633. sse.set_max_reconnect_attempts(1);
  13634. sse.start_async();
  13635. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13636. sse.stop();
  13637. EXPECT_TRUE(id_received.load());
  13638. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13639. }
  13640. // Test: Manual stop
  13641. TEST_F(SSEIntegrationTest, ManualStop) {
  13642. // Endpoint that sends one event and stays open briefly
  13643. std::atomic<bool> handler_running{true};
  13644. server_->Get("/stay-open", [&handler_running](const Request &,
  13645. Response &res) {
  13646. res.set_chunked_content_provider(
  13647. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13648. if (offset == 0) {
  13649. std::string event = "data: connected\n\n";
  13650. sink.write(event.data(), event.size());
  13651. }
  13652. // Keep connection open while handler_running is true
  13653. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13654. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13655. }
  13656. return false;
  13657. });
  13658. });
  13659. Client client("localhost", get_port());
  13660. sse::SSEClient sse(client, "/stay-open");
  13661. std::atomic<bool> connected{false};
  13662. sse.on_open([&connected]() { connected.store(true); });
  13663. sse.set_reconnect_interval(100);
  13664. sse.set_max_reconnect_attempts(1);
  13665. sse.start_async();
  13666. // Wait for connection to establish
  13667. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13668. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13669. }
  13670. EXPECT_TRUE(connected.load());
  13671. EXPECT_TRUE(sse.is_connected());
  13672. // Signal handler to stop
  13673. handler_running.store(false);
  13674. // Stop SSE client
  13675. sse.stop();
  13676. EXPECT_FALSE(sse.is_connected());
  13677. }
  13678. // Test: SSEClient with custom headers
  13679. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13680. // Setup a server endpoint that checks for custom header
  13681. std::atomic<bool> header_received{false};
  13682. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13683. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13684. header_received.store(true);
  13685. }
  13686. res.set_chunked_content_provider("text/event-stream",
  13687. [](size_t, DataSink &) { return false; });
  13688. });
  13689. Client client("localhost", get_port());
  13690. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13691. sse::SSEClient sse(client, "/header-check", headers);
  13692. sse.set_max_reconnect_attempts(1);
  13693. sse.start_async();
  13694. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13695. sse.stop();
  13696. EXPECT_TRUE(header_received.load());
  13697. }
  13698. // Test: Reconnect interval configuration
  13699. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13700. Client client("localhost", get_port());
  13701. sse::SSEClient sse(client, "/events");
  13702. auto &result = sse.set_reconnect_interval(500);
  13703. // Builder pattern should return reference to self
  13704. EXPECT_EQ(&result, &sse);
  13705. }
  13706. // Test: Max reconnect attempts
  13707. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13708. // Connect to non-existent port to force reconnects
  13709. Client client("localhost", 59998);
  13710. sse::SSEClient sse(client, "/events");
  13711. std::atomic<int> error_count{0};
  13712. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13713. sse.set_reconnect_interval(50);
  13714. sse.set_max_reconnect_attempts(2);
  13715. auto start = std::chrono::steady_clock::now();
  13716. sse.start(); // Blocking call
  13717. auto end = std::chrono::steady_clock::now();
  13718. // Should have stopped after 2 failed attempts
  13719. EXPECT_GE(error_count.load(), 2);
  13720. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13721. auto duration =
  13722. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13723. #ifdef _WIN32
  13724. // Windows is much slower for socket connection failures
  13725. EXPECT_LT(duration.count(), 7000);
  13726. #else
  13727. EXPECT_LT(duration.count(), 1000);
  13728. #endif
  13729. }
  13730. // Test: Multi-line data in integration
  13731. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13732. // Endpoint with multi-line data
  13733. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13734. res.set_chunked_content_provider(
  13735. "text/event-stream", [](size_t offset, DataSink &sink) {
  13736. if (offset == 0) {
  13737. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13738. sink.write(event.data(), event.size());
  13739. }
  13740. return false;
  13741. });
  13742. });
  13743. Client client("localhost", get_port());
  13744. sse::SSEClient sse(client, "/multiline-data");
  13745. std::string received_data;
  13746. std::mutex data_mutex;
  13747. sse.on_message([&](const sse::SSEMessage &msg) {
  13748. std::lock_guard<std::mutex> lock(data_mutex);
  13749. received_data = msg.data;
  13750. });
  13751. sse.set_reconnect_interval(100);
  13752. sse.set_max_reconnect_attempts(1);
  13753. sse.start_async();
  13754. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13755. sse.stop();
  13756. std::lock_guard<std::mutex> lock(data_mutex);
  13757. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13758. }
  13759. // Test: Auto-reconnect after server disconnection
  13760. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13761. std::atomic<int> connection_count{0};
  13762. std::atomic<int> message_count{0};
  13763. // Endpoint that sends one event and closes, forcing reconnect
  13764. server_->Get("/reconnect-test",
  13765. [&connection_count](const Request &, Response &res) {
  13766. connection_count.fetch_add(1);
  13767. res.set_chunked_content_provider(
  13768. "text/event-stream", [](size_t offset, DataSink &sink) {
  13769. if (offset == 0) {
  13770. std::string event = "data: hello\n\n";
  13771. sink.write(event.data(), event.size());
  13772. }
  13773. return false; // Close connection after sending
  13774. });
  13775. });
  13776. Client client("localhost", get_port());
  13777. sse::SSEClient sse(client, "/reconnect-test");
  13778. sse.on_message([&message_count](const sse::SSEMessage &) {
  13779. message_count.fetch_add(1);
  13780. });
  13781. sse.set_reconnect_interval(100);
  13782. sse.set_max_reconnect_attempts(3);
  13783. sse.start_async();
  13784. // Wait long enough for multiple reconnects
  13785. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13786. sse.stop();
  13787. // Should have connected multiple times (initial + reconnects)
  13788. EXPECT_GE(connection_count.load(), 2);
  13789. // Should have received messages from multiple connections
  13790. EXPECT_GE(message_count.load(), 2);
  13791. }
  13792. // Test: Last-Event-ID sent on reconnect
  13793. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13794. std::atomic<int> connection_count{0};
  13795. std::vector<std::string> received_last_event_ids;
  13796. std::mutex id_mutex;
  13797. // Endpoint that checks Last-Event-ID header and sends event with ID
  13798. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13799. int conn = connection_count.fetch_add(1);
  13800. // Capture the Last-Event-ID header from each connection
  13801. {
  13802. std::lock_guard<std::mutex> lock(id_mutex);
  13803. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13804. }
  13805. res.set_chunked_content_provider(
  13806. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13807. if (offset == 0) {
  13808. std::string event =
  13809. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13810. sink.write(event.data(), event.size());
  13811. }
  13812. return false;
  13813. });
  13814. });
  13815. Client client("localhost", get_port());
  13816. sse::SSEClient sse(client, "/reconnect-with-id");
  13817. sse.set_reconnect_interval(100);
  13818. sse.set_max_reconnect_attempts(3);
  13819. sse.start_async();
  13820. // Wait for at least 2 connections
  13821. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13822. sse.stop();
  13823. // Verify behavior
  13824. std::lock_guard<std::mutex> lock(id_mutex);
  13825. EXPECT_GE(received_last_event_ids.size(), 2u);
  13826. // First connection should have no Last-Event-ID
  13827. if (!received_last_event_ids.empty()) {
  13828. EXPECT_EQ(received_last_event_ids[0], "");
  13829. }
  13830. // Second connection should have Last-Event-ID from first connection
  13831. if (received_last_event_ids.size() >= 2) {
  13832. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13833. }
  13834. }
  13835. // Test: set_headers updates headers used on reconnect
  13836. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13837. std::vector<std::string> received_tokens;
  13838. std::mutex token_mutex;
  13839. // Endpoint that captures Authorization header
  13840. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13841. {
  13842. std::lock_guard<std::mutex> lock(token_mutex);
  13843. received_tokens.push_back(req.get_header_value("Authorization"));
  13844. }
  13845. res.set_chunked_content_provider(
  13846. "text/event-stream", [](size_t offset, DataSink &sink) {
  13847. if (offset == 0) {
  13848. std::string event = "data: hello\n\n";
  13849. sink.write(event.data(), event.size());
  13850. }
  13851. return false; // Close connection to trigger reconnect
  13852. });
  13853. });
  13854. Client client("localhost", get_port());
  13855. Headers headers = {{"Authorization", "Bearer old-token"}};
  13856. sse::SSEClient sse(client, "/auth-check", headers);
  13857. // Update headers on each successful connection
  13858. sse.on_open(
  13859. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13860. sse.set_reconnect_interval(100);
  13861. sse.set_max_reconnect_attempts(3);
  13862. sse.start_async();
  13863. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13864. sse.stop();
  13865. std::lock_guard<std::mutex> lock(token_mutex);
  13866. ASSERT_GE(received_tokens.size(), 2u);
  13867. // First connection uses original header
  13868. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13869. // Second connection uses updated header from set_headers
  13870. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13871. }
  13872. // Test: 401 allows reconnection (so on_error can refresh headers)
  13873. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13874. std::atomic<int> connection_count{0};
  13875. // Endpoint: returns 401 on first attempt, 200 on second
  13876. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13877. int conn = connection_count.fetch_add(1);
  13878. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13879. res.status = StatusCode::Unauthorized_401;
  13880. res.set_content("Unauthorized", "text/plain");
  13881. return;
  13882. }
  13883. res.set_chunked_content_provider(
  13884. "text/event-stream", [](size_t offset, DataSink &sink) {
  13885. if (offset == 0) {
  13886. std::string event = "data: authenticated\n\n";
  13887. sink.write(event.data(), event.size());
  13888. }
  13889. return false;
  13890. });
  13891. });
  13892. Client client("localhost", get_port());
  13893. Headers headers = {{"Authorization", "Bearer expired"}};
  13894. sse::SSEClient sse(client, "/auth-retry", headers);
  13895. std::atomic<bool> message_received{false};
  13896. // Refresh token on error
  13897. sse.on_error(
  13898. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13899. sse.on_message([&](const sse::SSEMessage &msg) {
  13900. if (msg.data == "authenticated") { message_received.store(true); }
  13901. });
  13902. sse.set_reconnect_interval(100);
  13903. sse.set_max_reconnect_attempts(3);
  13904. sse.start_async();
  13905. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13906. sse.stop();
  13907. // Should have reconnected after 401 and succeeded with new token
  13908. EXPECT_GE(connection_count.load(), 2);
  13909. EXPECT_TRUE(message_received.load());
  13910. }
  13911. TEST(Issue2318Test, EmptyHostString) {
  13912. {
  13913. httplib::Client cli_empty("", PORT);
  13914. auto res = cli_empty.Get("/");
  13915. ASSERT_FALSE(res);
  13916. EXPECT_EQ(httplib::Error::Connection, res.error());
  13917. }
  13918. {
  13919. httplib::Client cli(" ", PORT);
  13920. auto res = cli.Get("/");
  13921. ASSERT_FALSE(res);
  13922. EXPECT_EQ(httplib::Error::Connection, res.error());
  13923. }
  13924. }
  13925. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13926. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13927. Server svr;
  13928. // Set a small payload limit (1KB)
  13929. svr.set_payload_max_length(1024);
  13930. svr.Post("/test", [&](const Request &req, Response &res) {
  13931. res.set_content("Body size: " + std::to_string(req.body.size()),
  13932. "text/plain");
  13933. });
  13934. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13935. auto se = detail::scope_exit([&] {
  13936. svr.stop();
  13937. listen_thread.join();
  13938. });
  13939. svr.wait_until_ready();
  13940. // Create data that compresses well but exceeds limit when decompressed
  13941. // 8KB of repeated null bytes compresses to a very small size
  13942. std::string original_data(8 * 1024, '\0');
  13943. // Compress the data using gzip
  13944. std::string compressed_data;
  13945. detail::gzip_compressor compressor;
  13946. compressor.compress(original_data.data(), original_data.size(), true,
  13947. [&](const char *data, size_t size) {
  13948. compressed_data.append(data, size);
  13949. return true;
  13950. });
  13951. // Verify compression worked (compressed should be much smaller)
  13952. ASSERT_LT(compressed_data.size(), original_data.size());
  13953. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13954. // Send compressed data with Content-Encoding: gzip
  13955. Client cli(HOST, PORT);
  13956. Headers headers = {{"Content-Encoding", "gzip"}};
  13957. auto res =
  13958. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13959. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13960. ASSERT_TRUE(res);
  13961. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13962. }
  13963. #endif
  13964. // ============================================================================
  13965. // OpenSSL-Specific Tests
  13966. // ============================================================================
  13967. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13968. X509 *readCertificate(const std::string &strFileName) {
  13969. std::ifstream inStream(strFileName);
  13970. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13971. std::istreambuf_iterator<char>());
  13972. if (strCertPEM.empty()) return (nullptr);
  13973. BIO *pbCert = BIO_new(BIO_s_mem());
  13974. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13975. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13976. BIO_free(pbCert);
  13977. return (pCert);
  13978. }
  13979. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13980. std::ifstream inStream(strFileName);
  13981. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13982. std::istreambuf_iterator<char>());
  13983. if (strPrivateKeyPEM.empty()) return (nullptr);
  13984. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13985. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13986. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13987. BIO_free(pbPrivKey);
  13988. return (pPrivateKey);
  13989. }
  13990. TEST(BindServerTest, UpdateCerts) {
  13991. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13992. int port = svr.bind_to_any_port("0.0.0.0");
  13993. ASSERT_TRUE(svr.is_valid());
  13994. ASSERT_TRUE(port > 0);
  13995. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13996. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13997. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13998. ASSERT_TRUE(cert != nullptr);
  13999. ASSERT_TRUE(ca_cert != nullptr);
  14000. ASSERT_TRUE(key != nullptr);
  14001. X509_STORE *cert_store = X509_STORE_new();
  14002. X509_STORE_add_cert(cert_store, ca_cert);
  14003. // svr.update_certs(cert, key, cert_store); // deprecated
  14004. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14005. CLIENT_CA_CERT_FILE);
  14006. ASSERT_TRUE(svr.is_valid());
  14007. svr.stop();
  14008. X509_STORE_free(cert_store);
  14009. X509_free(cert);
  14010. X509_free(ca_cert);
  14011. EVP_PKEY_free(key);
  14012. }
  14013. // Test that update_certs() updates client CA list correctly
  14014. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  14015. // Start with file-based constructor
  14016. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14017. ASSERT_TRUE(svr.is_valid());
  14018. // Initially no client CA list should be set
  14019. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14020. ASSERT_TRUE(ssl_ctx != nullptr);
  14021. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  14022. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  14023. EXPECT_EQ(0, count_before);
  14024. // Now update with client CA (PEM string)
  14025. std::string cert_pem, key_pem, ca_pem;
  14026. read_file(SERVER_CERT_FILE, cert_pem);
  14027. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14028. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14029. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  14030. ASSERT_TRUE(svr.is_valid());
  14031. // Now client CA list should be set
  14032. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  14033. ASSERT_TRUE(ca_list_after != nullptr);
  14034. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  14035. }
  14036. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  14037. // Test that the file-path SSLServer constructor properly sets the client CA
  14038. // list that is sent to clients during the TLS handshake (CertificateRequest)
  14039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14040. ASSERT_TRUE(svr.is_valid());
  14041. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  14042. ASSERT_TRUE(ssl_ctx != nullptr);
  14043. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  14044. ASSERT_TRUE(ca_list != nullptr);
  14045. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  14046. }
  14047. #endif
  14048. // ============================================================================
  14049. // MbedTLS-Specific Tests
  14050. // ============================================================================
  14051. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  14052. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  14053. using namespace httplib::tls;
  14054. // Track if callback was invoked
  14055. bool callback_invoked = false;
  14056. // The callback receives void* ctx which is actually MbedTlsContext*
  14057. // We can access the mbedtls_ssl_config via the context
  14058. auto setup_callback = [&callback_invoked](void *ctx) {
  14059. callback_invoked = true;
  14060. // Cast to MbedTlsContext* to access the ssl config
  14061. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  14062. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  14063. // Use static variables to hold certificate data (simplified for test)
  14064. static mbedtls_x509_crt own_cert;
  14065. static mbedtls_pk_context own_key;
  14066. static mbedtls_x509_crt ca_chain;
  14067. static bool initialized = false;
  14068. if (!initialized) {
  14069. mbedtls_x509_crt_init(&own_cert);
  14070. mbedtls_pk_init(&own_key);
  14071. mbedtls_x509_crt_init(&ca_chain);
  14072. // Load server certificate
  14073. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  14074. return false;
  14075. }
  14076. // Load server private key
  14077. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  14078. #if MBEDTLS_VERSION_MAJOR >= 3
  14079. ,
  14080. mbedtls_ctr_drbg_random, nullptr
  14081. #endif
  14082. ) != 0) {
  14083. return false;
  14084. }
  14085. // Load CA chain for client verification
  14086. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  14087. return false;
  14088. }
  14089. initialized = true;
  14090. }
  14091. // Configure the SSL config
  14092. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  14093. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  14094. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  14095. // Set minimum TLS version using mbedTLS native API
  14096. #if MBEDTLS_VERSION_MAJOR >= 3
  14097. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  14098. #else
  14099. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  14100. MBEDTLS_SSL_MINOR_VERSION_3);
  14101. #endif
  14102. return true;
  14103. };
  14104. SSLServer svr(setup_callback);
  14105. ASSERT_TRUE(svr.is_valid());
  14106. ASSERT_TRUE(callback_invoked);
  14107. svr.Get("/test", [&](const Request &req, Response &res) {
  14108. res.set_content("test", "text/plain");
  14109. auto cert = req.peer_cert();
  14110. ASSERT_TRUE(static_cast<bool>(cert));
  14111. auto common_name = cert.subject_cn();
  14112. EXPECT_EQ("Common Name", common_name);
  14113. });
  14114. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14115. auto se = detail::scope_exit([&] {
  14116. svr.stop();
  14117. t.join();
  14118. ASSERT_FALSE(svr.is_running());
  14119. });
  14120. svr.wait_until_ready();
  14121. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14122. cli.enable_server_certificate_verification(false);
  14123. cli.set_connection_timeout(30);
  14124. auto res = cli.Get("/test");
  14125. ASSERT_TRUE(res);
  14126. ASSERT_EQ(StatusCode::OK_200, res->status);
  14127. }
  14128. #endif
  14129. // WebSocket Tests
  14130. TEST(WebSocketTest, RSVBitsMustBeZero) {
  14131. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  14132. // defining the meaning of these bits has been negotiated.
  14133. auto make_frame = [](uint8_t first_byte) {
  14134. std::string frame;
  14135. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  14136. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  14137. frame += "Hello";
  14138. return frame;
  14139. };
  14140. // RSV1 set (0x40)
  14141. {
  14142. detail::BufferStream strm;
  14143. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  14144. ws::Opcode opcode;
  14145. std::string payload;
  14146. bool fin;
  14147. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14148. false, 1024));
  14149. }
  14150. // RSV2 set (0x20)
  14151. {
  14152. detail::BufferStream strm;
  14153. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  14154. ws::Opcode opcode;
  14155. std::string payload;
  14156. bool fin;
  14157. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14158. false, 1024));
  14159. }
  14160. // RSV3 set (0x10)
  14161. {
  14162. detail::BufferStream strm;
  14163. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14164. ws::Opcode opcode;
  14165. std::string payload;
  14166. bool fin;
  14167. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14168. false, 1024));
  14169. }
  14170. // No RSV bits set - should succeed
  14171. {
  14172. detail::BufferStream strm;
  14173. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14174. ws::Opcode opcode;
  14175. std::string payload;
  14176. bool fin;
  14177. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14178. false, 1024));
  14179. EXPECT_EQ(ws::Opcode::Text, opcode);
  14180. EXPECT_EQ("Hello", payload);
  14181. EXPECT_TRUE(fin);
  14182. }
  14183. }
  14184. TEST(WebSocketTest, ControlFrameValidation) {
  14185. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14186. // payload length <= 125.
  14187. // Ping with FIN=0 - must be rejected
  14188. {
  14189. detail::BufferStream strm;
  14190. std::string frame;
  14191. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14192. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14193. strm.write(frame.data(), frame.size());
  14194. ws::Opcode opcode;
  14195. std::string payload;
  14196. bool fin;
  14197. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14198. false, 1024));
  14199. }
  14200. // Close with FIN=0 - must be rejected
  14201. {
  14202. detail::BufferStream strm;
  14203. std::string frame;
  14204. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14205. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14206. strm.write(frame.data(), frame.size());
  14207. ws::Opcode opcode;
  14208. std::string payload;
  14209. bool fin;
  14210. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14211. false, 1024));
  14212. }
  14213. // Ping with payload_len=126 (extended length) - must be rejected
  14214. {
  14215. detail::BufferStream strm;
  14216. std::string frame;
  14217. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14218. frame += static_cast<char>(126); // payload_len=126 (>125)
  14219. frame += static_cast<char>(0x00); // extended length high byte
  14220. frame += static_cast<char>(126); // extended length low byte
  14221. frame += std::string(126, 'x');
  14222. strm.write(frame.data(), frame.size());
  14223. ws::Opcode opcode;
  14224. std::string payload;
  14225. bool fin;
  14226. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14227. false, 1024));
  14228. }
  14229. // Ping with FIN=1 and payload_len=125 - should succeed
  14230. {
  14231. detail::BufferStream strm;
  14232. std::string frame;
  14233. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14234. frame += static_cast<char>(125); // payload_len=125
  14235. frame += std::string(125, 'x');
  14236. strm.write(frame.data(), frame.size());
  14237. ws::Opcode opcode;
  14238. std::string payload;
  14239. bool fin;
  14240. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14241. false, 1024));
  14242. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14243. EXPECT_EQ(125u, payload.size());
  14244. EXPECT_TRUE(fin);
  14245. }
  14246. }
  14247. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14248. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14249. // length MUST be 0.
  14250. // MSB set - must be rejected
  14251. {
  14252. detail::BufferStream strm;
  14253. std::string frame;
  14254. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14255. frame += static_cast<char>(127); // 64-bit extended length
  14256. frame += static_cast<char>(0x80); // MSB set (invalid)
  14257. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14258. strm.write(frame.data(), frame.size());
  14259. ws::Opcode opcode;
  14260. std::string payload;
  14261. bool fin;
  14262. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14263. false, 1024));
  14264. }
  14265. // MSB clear - should pass length parsing (will be rejected by max_len,
  14266. // but that's a different check; use a small length to verify)
  14267. {
  14268. detail::BufferStream strm;
  14269. std::string frame;
  14270. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14271. frame += static_cast<char>(127); // 64-bit extended length
  14272. frame += std::string(7, '\0'); // high bytes = 0
  14273. frame += static_cast<char>(0x03); // length = 3
  14274. frame += "abc";
  14275. strm.write(frame.data(), frame.size());
  14276. ws::Opcode opcode;
  14277. std::string payload;
  14278. bool fin;
  14279. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14280. false, 1024));
  14281. EXPECT_EQ(ws::Opcode::Text, opcode);
  14282. EXPECT_EQ("abc", payload);
  14283. }
  14284. }
  14285. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14286. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14287. // Valid UTF-8
  14288. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14289. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14290. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14291. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14292. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14293. // Invalid UTF-8
  14294. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14295. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14296. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14297. EXPECT_FALSE(
  14298. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14299. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14300. }
  14301. TEST(WebSocketTest, ConnectAndDisconnect) {
  14302. Server svr;
  14303. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14304. std::string msg;
  14305. while (ws.read(msg)) {}
  14306. });
  14307. auto port = svr.bind_to_any_port(HOST);
  14308. std::thread t([&]() { svr.listen_after_bind(); });
  14309. svr.wait_until_ready();
  14310. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14311. ASSERT_TRUE(client.connect());
  14312. EXPECT_TRUE(client.is_open());
  14313. client.close();
  14314. EXPECT_FALSE(client.is_open());
  14315. svr.stop();
  14316. t.join();
  14317. }
  14318. TEST(WebSocketTest, ValidURL) {
  14319. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14320. EXPECT_TRUE(ws1.is_valid());
  14321. ws::WebSocketClient ws2("ws://example.com/path");
  14322. EXPECT_TRUE(ws2.is_valid());
  14323. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14324. EXPECT_TRUE(ws3.is_valid());
  14325. #ifdef CPPHTTPLIB_SSL_ENABLED
  14326. ws::WebSocketClient wss1("wss://example.com/path");
  14327. EXPECT_TRUE(wss1.is_valid());
  14328. ws::WebSocketClient wss2("wss://example.com:443/path");
  14329. EXPECT_TRUE(wss2.is_valid());
  14330. #endif
  14331. }
  14332. TEST(WebSocketTest, InvalidURL) {
  14333. // No scheme
  14334. ws::WebSocketClient ws1("localhost:8080/path");
  14335. EXPECT_FALSE(ws1.is_valid());
  14336. // No path
  14337. ws::WebSocketClient ws2("ws://localhost:8080");
  14338. EXPECT_FALSE(ws2.is_valid());
  14339. // Empty string
  14340. ws::WebSocketClient ws3("");
  14341. EXPECT_FALSE(ws3.is_valid());
  14342. // Missing host
  14343. ws::WebSocketClient ws4("ws://:8080/path");
  14344. EXPECT_FALSE(ws4.is_valid());
  14345. // Port number overflow — should not crash
  14346. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14347. EXPECT_FALSE(ws5.is_valid());
  14348. // Port out of range
  14349. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14350. EXPECT_FALSE(ws6.is_valid());
  14351. }
  14352. TEST(WebSocketTest, UnsupportedScheme) {
  14353. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14354. ws::WebSocketClient ws1("http://localhost:8080/path");
  14355. EXPECT_FALSE(ws1.is_valid());
  14356. ws::WebSocketClient ws2("https://localhost:8080/path");
  14357. EXPECT_FALSE(ws2.is_valid());
  14358. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14359. EXPECT_FALSE(ws3.is_valid());
  14360. #else
  14361. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14362. std::invalid_argument);
  14363. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14364. std::invalid_argument);
  14365. #endif
  14366. }
  14367. TEST(WebSocketTest, ConnectWhenInvalid) {
  14368. ws::WebSocketClient ws("not a valid url");
  14369. EXPECT_FALSE(ws.is_valid());
  14370. EXPECT_FALSE(ws.connect());
  14371. }
  14372. TEST(WebSocketTest, DefaultPort) {
  14373. ws::WebSocketClient ws1("ws://example.com/path");
  14374. EXPECT_TRUE(ws1.is_valid());
  14375. // ws:// defaults to port 80 (verified by successful parse)
  14376. #ifdef CPPHTTPLIB_SSL_ENABLED
  14377. ws::WebSocketClient ws2("wss://example.com/path");
  14378. EXPECT_TRUE(ws2.is_valid());
  14379. // wss:// defaults to port 443 (verified by successful parse)
  14380. #endif
  14381. }
  14382. TEST(WebSocketTest, IPv6LiteralAddress) {
  14383. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14384. EXPECT_TRUE(ws1.is_valid());
  14385. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14386. EXPECT_TRUE(ws2.is_valid());
  14387. }
  14388. TEST(WebSocketTest, ComplexPath) {
  14389. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14390. EXPECT_TRUE(ws1.is_valid());
  14391. ws::WebSocketClient ws2("ws://localhost:8080/");
  14392. EXPECT_TRUE(ws2.is_valid());
  14393. }
  14394. class WebSocketIntegrationTest : public ::testing::Test {
  14395. protected:
  14396. void SetUp() override {
  14397. server_ = httplib::detail::make_unique<Server>();
  14398. setup_server();
  14399. start_server();
  14400. }
  14401. void TearDown() override {
  14402. server_->stop();
  14403. if (server_thread_.joinable()) { server_thread_.join(); }
  14404. }
  14405. void setup_server() {
  14406. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14407. std::string msg;
  14408. ws::ReadResult ret;
  14409. while ((ret = ws.read(msg))) {
  14410. if (ret == ws::Binary) {
  14411. ws.send(msg.data(), msg.size());
  14412. } else {
  14413. ws.send(msg);
  14414. }
  14415. }
  14416. });
  14417. server_->WebSocket("/ws-echo-string",
  14418. [](const Request &, ws::WebSocket &ws) {
  14419. std::string msg;
  14420. while (ws.read(msg)) {
  14421. ws.send("echo: " + msg);
  14422. }
  14423. });
  14424. server_->WebSocket(
  14425. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14426. // Echo back request metadata
  14427. ws.send("path:" + req.path);
  14428. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14429. std::string msg;
  14430. while (ws.read(msg)) {}
  14431. });
  14432. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14433. std::string msg;
  14434. ws.read(msg); // wait for a message
  14435. ws.close();
  14436. });
  14437. server_->WebSocket("/ws-close-status",
  14438. [](const Request &, ws::WebSocket &ws) {
  14439. std::string msg;
  14440. ws.read(msg); // wait for a message
  14441. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14442. });
  14443. server_->WebSocket(
  14444. "/ws-subprotocol",
  14445. [](const Request &, ws::WebSocket &ws) {
  14446. std::string msg;
  14447. while (ws.read(msg)) {
  14448. ws.send(msg);
  14449. }
  14450. },
  14451. [](const std::vector<std::string> &protocols) -> std::string {
  14452. for (const auto &p : protocols) {
  14453. if (p == "graphql-ws") { return p; }
  14454. }
  14455. return "";
  14456. });
  14457. }
  14458. void start_server() {
  14459. port_ = server_->bind_to_any_port(HOST);
  14460. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14461. server_->wait_until_ready();
  14462. }
  14463. std::unique_ptr<Server> server_;
  14464. std::thread server_thread_;
  14465. int port_ = 0;
  14466. };
  14467. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14468. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14469. "/ws-echo");
  14470. ASSERT_TRUE(client.connect());
  14471. ASSERT_TRUE(client.is_open());
  14472. ASSERT_TRUE(client.send("Hello WebSocket"));
  14473. std::string msg;
  14474. EXPECT_EQ(ws::Text, client.read(msg));
  14475. EXPECT_EQ("Hello WebSocket", msg);
  14476. client.close();
  14477. }
  14478. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14479. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14480. "/ws-echo");
  14481. ASSERT_TRUE(client.connect());
  14482. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14483. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14484. std::string msg;
  14485. EXPECT_EQ(ws::Binary, client.read(msg));
  14486. EXPECT_EQ(binary_data, msg);
  14487. client.close();
  14488. }
  14489. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14491. "/ws-echo");
  14492. ASSERT_TRUE(client.connect());
  14493. for (int i = 0; i < 10; i++) {
  14494. auto text = "message " + std::to_string(i);
  14495. ASSERT_TRUE(client.send(text));
  14496. std::string msg;
  14497. ASSERT_TRUE(client.read(msg));
  14498. EXPECT_EQ(text, msg);
  14499. }
  14500. client.close();
  14501. }
  14502. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14504. "/ws-close");
  14505. ASSERT_TRUE(client.connect());
  14506. // Send a message to trigger the server to close
  14507. ASSERT_TRUE(client.send("trigger close"));
  14508. // The server will close, so read should return false
  14509. std::string msg;
  14510. EXPECT_FALSE(client.read(msg));
  14511. EXPECT_FALSE(client.is_open());
  14512. }
  14513. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14514. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14515. "/ws-echo");
  14516. ASSERT_TRUE(client.connect());
  14517. // 128KB message
  14518. std::string large_data(128 * 1024, 'X');
  14519. ASSERT_TRUE(client.send(large_data));
  14520. std::string msg;
  14521. ASSERT_TRUE(client.read(msg));
  14522. EXPECT_EQ(large_data, msg);
  14523. client.close();
  14524. }
  14525. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14526. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14527. "/ws-echo");
  14528. ASSERT_TRUE(client.connect());
  14529. const int num_threads = 4;
  14530. std::vector<std::thread> threads;
  14531. std::atomic<int> send_count{0};
  14532. for (int t = 0; t < num_threads; t++) {
  14533. threads.emplace_back([&client, &send_count, t]() {
  14534. for (int i = 0; i < 5; i++) {
  14535. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14536. if (client.send(text)) { send_count++; }
  14537. }
  14538. });
  14539. }
  14540. for (auto &th : threads) {
  14541. th.join();
  14542. }
  14543. int received = 0;
  14544. std::string msg;
  14545. while (received < send_count.load()) {
  14546. if (!client.read(msg)) { break; }
  14547. received++;
  14548. }
  14549. EXPECT_EQ(send_count.load(), received);
  14550. client.close();
  14551. }
  14552. TEST_F(WebSocketIntegrationTest, ReadString) {
  14553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14554. "/ws-echo-string");
  14555. ASSERT_TRUE(client.connect());
  14556. ASSERT_TRUE(client.send("hello"));
  14557. std::string msg;
  14558. ASSERT_TRUE(client.read(msg));
  14559. EXPECT_EQ("echo: hello", msg);
  14560. ASSERT_TRUE(client.send("world"));
  14561. ASSERT_TRUE(client.read(msg));
  14562. EXPECT_EQ("echo: world", msg);
  14563. client.close();
  14564. }
  14565. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14566. Headers headers = {{"X-Test-Header", "test-value"}};
  14567. ws::WebSocketClient client(
  14568. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14569. ASSERT_TRUE(client.connect());
  14570. std::string msg;
  14571. ASSERT_TRUE(client.read(msg));
  14572. EXPECT_EQ("path:/ws-request-info", msg);
  14573. ASSERT_TRUE(client.read(msg));
  14574. EXPECT_EQ("header:test-value", msg);
  14575. client.close();
  14576. }
  14577. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14578. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14579. "/ws-echo");
  14580. client.set_read_timeout(1, 0); // 1 second
  14581. ASSERT_TRUE(client.connect());
  14582. // Don't send anything — server echo handler waits for a message,
  14583. // so read() should time out and return false.
  14584. std::string msg;
  14585. EXPECT_FALSE(client.read(msg));
  14586. }
  14587. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14588. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14589. "/ws-echo");
  14590. client.set_read_timeout(5, 0);
  14591. ASSERT_TRUE(client.connect());
  14592. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14593. // The server should reject it and close the connection.
  14594. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14595. client.send(oversized);
  14596. // The server's read() should have failed due to payload limit,
  14597. // so our read() should return false (connection closed).
  14598. std::string msg;
  14599. EXPECT_FALSE(client.read(msg));
  14600. }
  14601. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14602. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14603. "/ws-echo");
  14604. client.set_read_timeout(10, 0);
  14605. ASSERT_TRUE(client.connect());
  14606. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14607. // This should succeed.
  14608. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14609. ASSERT_TRUE(client.send(at_limit));
  14610. std::string msg;
  14611. ASSERT_TRUE(client.read(msg));
  14612. EXPECT_EQ(at_limit.size(), msg.size());
  14613. client.close();
  14614. }
  14615. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14616. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14617. "/nonexistent");
  14618. EXPECT_FALSE(client.connect());
  14619. EXPECT_FALSE(client.is_open());
  14620. }
  14621. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14622. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14623. "/ws-echo");
  14624. ASSERT_TRUE(client.connect());
  14625. ASSERT_TRUE(client.send(""));
  14626. std::string msg;
  14627. EXPECT_EQ(ws::Text, client.read(msg));
  14628. EXPECT_EQ("", msg);
  14629. client.close();
  14630. }
  14631. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14632. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14633. "/ws-echo");
  14634. // First connection
  14635. ASSERT_TRUE(client.connect());
  14636. ASSERT_TRUE(client.send("first"));
  14637. std::string msg;
  14638. ASSERT_TRUE(client.read(msg));
  14639. EXPECT_EQ("first", msg);
  14640. client.close();
  14641. EXPECT_FALSE(client.is_open());
  14642. // Reconnect using the same client object
  14643. ASSERT_TRUE(client.connect());
  14644. ASSERT_TRUE(client.is_open());
  14645. ASSERT_TRUE(client.send("second"));
  14646. ASSERT_TRUE(client.read(msg));
  14647. EXPECT_EQ("second", msg);
  14648. client.close();
  14649. }
  14650. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14651. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14652. "/ws-close-status");
  14653. ASSERT_TRUE(client.connect());
  14654. // Trigger the server to close with GoingAway status
  14655. ASSERT_TRUE(client.send("trigger"));
  14656. // read() should return false after receiving the close frame
  14657. std::string msg;
  14658. EXPECT_FALSE(client.read(msg));
  14659. EXPECT_FALSE(client.is_open());
  14660. }
  14661. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14662. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14663. "/ws-echo");
  14664. ASSERT_TRUE(client.connect());
  14665. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14666. EXPECT_FALSE(client.is_open());
  14667. }
  14668. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14669. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14670. ws::WebSocketClient client(
  14671. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14672. ASSERT_TRUE(client.connect());
  14673. // Server should have selected graphql-ws
  14674. EXPECT_EQ("graphql-ws", client.subprotocol());
  14675. client.close();
  14676. }
  14677. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14678. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14679. ws::WebSocketClient client(
  14680. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14681. ASSERT_TRUE(client.connect());
  14682. // Server should not have selected any subprotocol
  14683. EXPECT_TRUE(client.subprotocol().empty());
  14684. client.close();
  14685. }
  14686. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14687. // Connect without requesting any subprotocol
  14688. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14689. "/ws-subprotocol");
  14690. ASSERT_TRUE(client.connect());
  14691. EXPECT_TRUE(client.subprotocol().empty());
  14692. client.close();
  14693. }
  14694. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14695. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14696. "/ws-echo");
  14697. client.set_tcp_nodelay(true);
  14698. client.set_connection_timeout(3, 0);
  14699. bool socket_options_called = false;
  14700. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14701. ASSERT_TRUE(client.connect());
  14702. ASSERT_TRUE(client.is_open());
  14703. EXPECT_TRUE(socket_options_called);
  14704. ASSERT_TRUE(client.send("hello"));
  14705. std::string msg;
  14706. auto result = client.read(msg);
  14707. EXPECT_EQ(result, ws::ReadResult::Text);
  14708. EXPECT_EQ(msg, "hello");
  14709. client.close();
  14710. }
  14711. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14712. Server svr;
  14713. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14714. if (!req.has_header("Authorization")) {
  14715. res.status = StatusCode::Unauthorized_401;
  14716. res.set_content("Unauthorized", "text/plain");
  14717. return Server::HandlerResponse::Handled;
  14718. }
  14719. return Server::HandlerResponse::Unhandled;
  14720. });
  14721. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14722. std::string msg;
  14723. while (ws.read(msg)) {
  14724. ws.send(msg);
  14725. }
  14726. });
  14727. auto port = svr.bind_to_any_port("localhost");
  14728. std::thread t([&]() { svr.listen_after_bind(); });
  14729. svr.wait_until_ready();
  14730. // Without Authorization header - should be rejected before upgrade
  14731. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14732. EXPECT_FALSE(client1.connect());
  14733. // With Authorization header - should succeed
  14734. Headers headers = {{"Authorization", "Bearer token123"}};
  14735. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14736. headers);
  14737. ASSERT_TRUE(client2.connect());
  14738. ASSERT_TRUE(client2.send("hello"));
  14739. std::string msg;
  14740. ASSERT_TRUE(client2.read(msg));
  14741. EXPECT_EQ("hello", msg);
  14742. client2.close();
  14743. svr.stop();
  14744. t.join();
  14745. }
  14746. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14747. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14748. protected:
  14749. void SetUp() override {
  14750. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14751. SERVER_PRIVATE_KEY_FILE);
  14752. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14753. std::string msg;
  14754. ws::ReadResult ret;
  14755. while ((ret = ws.read(msg))) {
  14756. if (ret == ws::Binary) {
  14757. ws.send(msg.data(), msg.size());
  14758. } else {
  14759. ws.send(msg);
  14760. }
  14761. }
  14762. });
  14763. port_ = server_->bind_to_any_port(HOST);
  14764. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14765. server_->wait_until_ready();
  14766. }
  14767. void TearDown() override {
  14768. server_->stop();
  14769. if (server_thread_.joinable()) { server_thread_.join(); }
  14770. }
  14771. std::unique_ptr<SSLServer> server_;
  14772. std::thread server_thread_;
  14773. int port_ = 0;
  14774. };
  14775. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14776. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14777. "/ws-echo");
  14778. client.enable_server_certificate_verification(false);
  14779. ASSERT_TRUE(client.connect());
  14780. ASSERT_TRUE(client.is_open());
  14781. ASSERT_TRUE(client.send("Hello WSS"));
  14782. std::string msg;
  14783. EXPECT_EQ(ws::Text, client.read(msg));
  14784. EXPECT_EQ("Hello WSS", msg);
  14785. client.close();
  14786. }
  14787. #endif
  14788. #if !defined(_WIN32)
  14789. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14790. auto secret_dir = std::string("./symlink_test_secret");
  14791. auto served_dir = std::string("./symlink_test_served");
  14792. auto secret_file = secret_dir + "/secret.txt";
  14793. auto symlink_path = served_dir + "/escape";
  14794. // Setup: create directories and files
  14795. mkdir(secret_dir.c_str(), 0755);
  14796. mkdir(served_dir.c_str(), 0755);
  14797. {
  14798. std::ofstream ofs(secret_file);
  14799. ofs << "SECRET_DATA";
  14800. }
  14801. // Create symlink using absolute path so it resolves correctly
  14802. #ifdef PATH_MAX
  14803. char abs_secret[PATH_MAX];
  14804. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14805. #else
  14806. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  14807. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  14808. ASSERT_NE(nullptr, abs_secret);
  14809. #endif
  14810. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14811. auto se = detail::scope_exit([&] {
  14812. unlink(symlink_path.c_str());
  14813. unlink(secret_file.c_str());
  14814. rmdir(served_dir.c_str());
  14815. rmdir(secret_dir.c_str());
  14816. });
  14817. Server svr;
  14818. svr.set_mount_point("/", served_dir);
  14819. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14820. auto se2 = detail::scope_exit([&] {
  14821. svr.stop();
  14822. listen_thread.join();
  14823. });
  14824. svr.wait_until_ready();
  14825. Client cli("localhost", PORT);
  14826. // Symlink pointing outside base dir should be blocked
  14827. auto res = cli.Get("/escape/secret.txt");
  14828. ASSERT_TRUE(res);
  14829. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14830. }
  14831. #endif
  14832. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14833. // A GET request with Content-Length to a static file handler must have its
  14834. // body drained before the keep-alive connection is reused. Otherwise the
  14835. // unread body bytes are interpreted as the next HTTP request.
  14836. //
  14837. // The body is sent AFTER receiving the first response (as in the original
  14838. // PoC) so that the stream_line_reader cannot buffer it together with the
  14839. // headers of the first request.
  14840. Server svr;
  14841. svr.set_mount_point("/", "./www");
  14842. std::atomic<int> smuggled_count(0);
  14843. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14844. smuggled_count++;
  14845. res.set_content("oops", "text/plain");
  14846. });
  14847. auto port = svr.bind_to_any_port("localhost");
  14848. thread t = thread([&] { svr.listen_after_bind(); });
  14849. auto se = detail::scope_exit([&] {
  14850. svr.stop();
  14851. t.join();
  14852. });
  14853. svr.wait_until_ready();
  14854. auto error = Error::Success;
  14855. auto sock = detail::create_client_socket(
  14856. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14857. /*connection_timeout_sec=*/2, 0,
  14858. /*read_timeout_sec=*/2, 0,
  14859. /*write_timeout_sec=*/2, 0, std::string(), error);
  14860. ASSERT_NE(INVALID_SOCKET, sock);
  14861. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14862. // The "smuggled" request will be sent as the body of the outer GET
  14863. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14864. "Host: localhost\r\n"
  14865. "Connection: close\r\n"
  14866. "\r\n";
  14867. // Step 1: Send only the outer request headers (no body yet)
  14868. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14869. "Host: localhost\r\n"
  14870. "Content-Length: " +
  14871. std::to_string(smuggled.size()) +
  14872. "\r\n"
  14873. "\r\n";
  14874. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  14875. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14876. // Step 2: Read the first response (server serves file without reading body)
  14877. std::string first_response;
  14878. char buf[4096];
  14879. for (;;) {
  14880. auto n = recv(sock, buf, sizeof(buf), 0);
  14881. if (n <= 0) break;
  14882. first_response.append(buf, static_cast<size_t>(n));
  14883. // Stop once we have a complete response (headers + body)
  14884. auto hdr_end = first_response.find("\r\n\r\n");
  14885. if (hdr_end != std::string::npos) {
  14886. // Check for Content-Length to know when the body is complete
  14887. auto cl_pos = first_response.find("Content-Length:");
  14888. if (cl_pos != std::string::npos) {
  14889. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14890. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14891. auto cl = std::stoul(
  14892. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14893. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14894. } else {
  14895. break; // No Content-Length, assume headers-only response
  14896. }
  14897. }
  14898. }
  14899. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14900. // Step 3: Now send the body, which looks like a new HTTP request.
  14901. // On a vulnerable server the keep-alive loop reads this as a second request.
  14902. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  14903. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14904. // Step 4: Try to read a second response (should NOT exist after fix)
  14905. std::string second_response;
  14906. for (;;) {
  14907. auto n = recv(sock, buf, sizeof(buf), 0);
  14908. if (n <= 0) break;
  14909. second_response.append(buf, static_cast<size_t>(n));
  14910. }
  14911. // The smuggled request must NOT have been processed
  14912. EXPECT_EQ(0, smuggled_count.load());
  14913. }
  14914. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14915. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14916. // must be rejected with 400 Bad Request.
  14917. Server svr;
  14918. svr.Post("/test", [&](const Request &, Response &res) {
  14919. res.set_content("ok", "text/plain");
  14920. });
  14921. thread t = thread([&] { svr.listen(HOST, PORT); });
  14922. auto se = detail::scope_exit([&] {
  14923. svr.stop();
  14924. t.join();
  14925. ASSERT_FALSE(svr.is_running());
  14926. });
  14927. svr.wait_until_ready();
  14928. // Exact "chunked"
  14929. {
  14930. auto req = "POST /test HTTP/1.1\r\n"
  14931. "Host: localhost\r\n"
  14932. "Content-Length: 5\r\n"
  14933. "Transfer-Encoding: chunked\r\n"
  14934. "Connection: close\r\n"
  14935. "\r\n"
  14936. "hello";
  14937. std::string response;
  14938. ASSERT_TRUE(send_request(1, req, &response));
  14939. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14940. response.substr(0, response.find("\r\n")));
  14941. }
  14942. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  14943. {
  14944. auto req = "POST /test HTTP/1.1\r\n"
  14945. "Host: localhost\r\n"
  14946. "Content-Length: 5\r\n"
  14947. "Transfer-Encoding: gzip, chunked\r\n"
  14948. "Connection: close\r\n"
  14949. "\r\n"
  14950. "hello";
  14951. std::string response;
  14952. ASSERT_TRUE(send_request(1, req, &response));
  14953. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14954. response.substr(0, response.find("\r\n")));
  14955. }
  14956. }