test.cc 543 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748
  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. TEST(ConnectionErrorTest, InvalidHost) {
  1273. auto host = "-abcde.com";
  1274. #ifdef CPPHTTPLIB_SSL_ENABLED
  1275. auto port = 443;
  1276. SSLClient cli(host, port);
  1277. #else
  1278. auto port = 80;
  1279. Client cli(host, port);
  1280. #endif
  1281. cli.set_connection_timeout(std::chrono::seconds(2));
  1282. auto res = cli.Get("/");
  1283. ASSERT_TRUE(!res);
  1284. EXPECT_EQ(Error::Connection, res.error());
  1285. }
  1286. TEST(ConnectionErrorTest, InvalidHost2) {
  1287. auto host = "httpcan.org/";
  1288. #ifdef CPPHTTPLIB_SSL_ENABLED
  1289. SSLClient cli(host);
  1290. #else
  1291. Client cli(host);
  1292. #endif
  1293. cli.set_connection_timeout(std::chrono::seconds(2));
  1294. auto res = cli.Get("/");
  1295. ASSERT_TRUE(!res);
  1296. EXPECT_EQ(Error::Connection, res.error());
  1297. }
  1298. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1299. auto host = "httpcan.org/";
  1300. #ifdef CPPHTTPLIB_SSL_ENABLED
  1301. SSLClient cli(host);
  1302. #else
  1303. Client cli(host);
  1304. #endif
  1305. cli.set_connection_timeout(std::chrono::seconds(2));
  1306. auto res = cli.Get("/");
  1307. ASSERT_TRUE(!res);
  1308. stringstream s;
  1309. s << "error code: " << res.error();
  1310. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1311. }
  1312. TEST(ConnectionErrorTest, InvalidPort) {
  1313. auto host = "localhost";
  1314. auto port = 44380;
  1315. #ifdef CPPHTTPLIB_SSL_ENABLED
  1316. SSLClient cli(host, port);
  1317. #else
  1318. Client cli(host, port);
  1319. #endif
  1320. cli.set_connection_timeout(std::chrono::seconds(2));
  1321. auto res = cli.Get("/");
  1322. ASSERT_TRUE(!res);
  1323. EXPECT_TRUE(Error::Connection == res.error() ||
  1324. Error::ConnectionTimeout == res.error());
  1325. }
  1326. TEST(ConnectionErrorTest, Timeout_Online) {
  1327. auto host = "google.com";
  1328. #ifdef CPPHTTPLIB_SSL_ENABLED
  1329. auto port = 44380;
  1330. SSLClient cli(host, port);
  1331. #else
  1332. auto port = 8080;
  1333. Client cli(host, port);
  1334. #endif
  1335. cli.set_connection_timeout(std::chrono::seconds(2));
  1336. // only probe one address type so that the error reason
  1337. // correlates to the timed-out IPv4, not the unsupported
  1338. // IPv6 connection attempt
  1339. cli.set_address_family(AF_INET);
  1340. auto res = cli.Get("/");
  1341. ASSERT_TRUE(!res);
  1342. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1343. }
  1344. TEST(CancelTest, NoCancel_Online) {
  1345. auto host = "httpbingo.org";
  1346. auto path = std::string{"/range/32"};
  1347. #ifdef CPPHTTPLIB_SSL_ENABLED
  1348. auto port = 443;
  1349. SSLClient cli(host, port);
  1350. #else
  1351. auto port = 80;
  1352. Client cli(host, port);
  1353. #endif
  1354. cli.set_connection_timeout(std::chrono::seconds(5));
  1355. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1356. ASSERT_TRUE(res);
  1357. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1358. EXPECT_EQ(StatusCode::OK_200, res->status);
  1359. }
  1360. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1361. // Use /bytes with a large payload so that the DownloadProgress callback
  1362. // (which only fires for Content-Length responses) is invoked before the
  1363. // entire body is received, giving cancellation a chance to fire.
  1364. auto host = "httpbingo.org";
  1365. auto path = std::string{"/bytes/524288"};
  1366. #ifdef CPPHTTPLIB_SSL_ENABLED
  1367. auto port = 443;
  1368. SSLClient cli(host, port);
  1369. #else
  1370. auto port = 80;
  1371. Client cli(host, port);
  1372. #endif
  1373. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1374. cli.set_connection_timeout(std::chrono::seconds(5));
  1375. ASSERT_TRUE(!res);
  1376. EXPECT_EQ(Error::Canceled, res.error());
  1377. }
  1378. TEST(CancelTest, WithCancelLargePayload_Online) {
  1379. auto host = "httpbingo.org";
  1380. auto path = std::string{"/bytes/524288"};
  1381. #ifdef CPPHTTPLIB_SSL_ENABLED
  1382. auto port = 443;
  1383. SSLClient cli(host, port);
  1384. #else
  1385. auto port = 80;
  1386. Client cli(host, port);
  1387. #endif
  1388. cli.set_connection_timeout(std::chrono::seconds(5));
  1389. uint32_t count = 0;
  1390. auto res =
  1391. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1392. ASSERT_TRUE(!res);
  1393. EXPECT_EQ(Error::Canceled, res.error());
  1394. }
  1395. TEST(CancelTest, NoCancelPost) {
  1396. Server svr;
  1397. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1398. res.set_content("Hello World!", "text/plain");
  1399. });
  1400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1401. auto se = detail::scope_exit([&] {
  1402. svr.stop();
  1403. thread.join();
  1404. ASSERT_FALSE(svr.is_running());
  1405. });
  1406. svr.wait_until_ready();
  1407. Client cli(HOST, PORT);
  1408. cli.set_connection_timeout(std::chrono::seconds(5));
  1409. auto res =
  1410. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1411. "application/json", [](uint64_t, uint64_t) { return true; });
  1412. ASSERT_TRUE(res);
  1413. EXPECT_EQ("Hello World!", res->body);
  1414. EXPECT_EQ(StatusCode::OK_200, res->status);
  1415. }
  1416. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1417. Server svr;
  1418. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1419. res.set_content("Hello World!", "text/plain");
  1420. });
  1421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1422. auto se = detail::scope_exit([&] {
  1423. svr.stop();
  1424. thread.join();
  1425. ASSERT_FALSE(svr.is_running());
  1426. });
  1427. svr.wait_until_ready();
  1428. Client cli(HOST, PORT);
  1429. cli.set_connection_timeout(std::chrono::seconds(5));
  1430. auto res =
  1431. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1432. "application/json", [](uint64_t, uint64_t) { return false; });
  1433. ASSERT_TRUE(!res);
  1434. EXPECT_EQ(Error::Canceled, res.error());
  1435. }
  1436. TEST(CancelTest, WithCancelLargePayloadPost) {
  1437. Server svr;
  1438. svr.set_payload_max_length(200 * 1024 * 1024);
  1439. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1440. res.set_content(LARGE_DATA, "text/plain");
  1441. });
  1442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. thread.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. Client cli(HOST, PORT);
  1450. cli.set_payload_max_length(200 * 1024 * 1024);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, NoCancelPut) {
  1459. Server svr;
  1460. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content("Hello World!", "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return true; });
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("Hello World!", res->body);
  1477. EXPECT_EQ(StatusCode::OK_200, res->status);
  1478. }
  1479. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1480. Server svr;
  1481. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1482. res.set_content("Hello World!", "text/plain");
  1483. });
  1484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1485. auto se = detail::scope_exit([&] {
  1486. svr.stop();
  1487. thread.join();
  1488. ASSERT_FALSE(svr.is_running());
  1489. });
  1490. svr.wait_until_ready();
  1491. Client cli(HOST, PORT);
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. auto res =
  1494. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1495. "application/json", [](uint64_t, uint64_t) { return false; });
  1496. ASSERT_TRUE(!res);
  1497. EXPECT_EQ(Error::Canceled, res.error());
  1498. }
  1499. TEST(CancelTest, WithCancelLargePayloadPut) {
  1500. Server svr;
  1501. svr.set_payload_max_length(200 * 1024 * 1024);
  1502. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1503. res.set_content(LARGE_DATA, "text/plain");
  1504. });
  1505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1506. auto se = detail::scope_exit([&] {
  1507. svr.stop();
  1508. thread.join();
  1509. ASSERT_FALSE(svr.is_running());
  1510. });
  1511. svr.wait_until_ready();
  1512. Client cli(HOST, PORT);
  1513. cli.set_payload_max_length(200 * 1024 * 1024);
  1514. cli.set_connection_timeout(std::chrono::seconds(5));
  1515. auto res =
  1516. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1517. "application/json", [](uint64_t, uint64_t) { return false; });
  1518. ASSERT_TRUE(!res);
  1519. EXPECT_EQ(Error::Canceled, res.error());
  1520. }
  1521. TEST(CancelTest, NoCancelPatch) {
  1522. Server svr;
  1523. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1524. res.set_content("Hello World!", "text/plain");
  1525. });
  1526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1527. auto se = detail::scope_exit([&] {
  1528. svr.stop();
  1529. thread.join();
  1530. ASSERT_FALSE(svr.is_running());
  1531. });
  1532. svr.wait_until_ready();
  1533. Client cli(HOST, PORT);
  1534. cli.set_connection_timeout(std::chrono::seconds(5));
  1535. auto res =
  1536. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1537. "application/json", [](uint64_t, uint64_t) { return true; });
  1538. ASSERT_TRUE(res);
  1539. EXPECT_EQ("Hello World!", res->body);
  1540. EXPECT_EQ(StatusCode::OK_200, res->status);
  1541. }
  1542. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1543. Server svr;
  1544. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1545. res.set_content("Hello World!", "text/plain");
  1546. });
  1547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1548. auto se = detail::scope_exit([&] {
  1549. svr.stop();
  1550. thread.join();
  1551. ASSERT_FALSE(svr.is_running());
  1552. });
  1553. svr.wait_until_ready();
  1554. Client cli(HOST, PORT);
  1555. cli.set_connection_timeout(std::chrono::seconds(5));
  1556. auto res =
  1557. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1558. "application/json", [](uint64_t, uint64_t) { return false; });
  1559. ASSERT_TRUE(!res);
  1560. EXPECT_EQ(Error::Canceled, res.error());
  1561. }
  1562. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1563. Server svr;
  1564. svr.set_payload_max_length(200 * 1024 * 1024);
  1565. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1566. res.set_content(LARGE_DATA, "text/plain");
  1567. });
  1568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. thread.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. Client cli(HOST, PORT);
  1576. cli.set_payload_max_length(200 * 1024 * 1024);
  1577. cli.set_connection_timeout(std::chrono::seconds(5));
  1578. auto res =
  1579. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1580. "application/json", [](uint64_t, uint64_t) { return false; });
  1581. ASSERT_TRUE(!res);
  1582. EXPECT_EQ(Error::Canceled, res.error());
  1583. }
  1584. TEST(CancelTest, NoCancelDelete) {
  1585. Server svr;
  1586. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1587. res.set_content("Hello World!", "text/plain");
  1588. });
  1589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1590. auto se = detail::scope_exit([&] {
  1591. svr.stop();
  1592. thread.join();
  1593. ASSERT_FALSE(svr.is_running());
  1594. });
  1595. svr.wait_until_ready();
  1596. Client cli(HOST, PORT);
  1597. cli.set_connection_timeout(std::chrono::seconds(5));
  1598. auto res =
  1599. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1600. "application/json", [](uint64_t, uint64_t) { return true; });
  1601. ASSERT_TRUE(res);
  1602. EXPECT_EQ("Hello World!", res->body);
  1603. EXPECT_EQ(StatusCode::OK_200, res->status);
  1604. }
  1605. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1606. Server svr;
  1607. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. thread.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. Client cli(HOST, PORT);
  1618. cli.set_connection_timeout(std::chrono::seconds(5));
  1619. auto res =
  1620. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1621. "application/json", [](uint64_t, uint64_t) { return false; });
  1622. ASSERT_TRUE(!res);
  1623. EXPECT_EQ(Error::Canceled, res.error());
  1624. }
  1625. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1626. Server svr;
  1627. svr.set_payload_max_length(200 * 1024 * 1024);
  1628. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1629. res.set_content(LARGE_DATA, "text/plain");
  1630. });
  1631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. thread.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. Client cli(HOST, PORT);
  1639. cli.set_payload_max_length(200 * 1024 * 1024);
  1640. cli.set_connection_timeout(std::chrono::seconds(5));
  1641. auto res =
  1642. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1643. "application/json", [](uint64_t, uint64_t) { return false; });
  1644. ASSERT_TRUE(!res);
  1645. EXPECT_EQ(Error::Canceled, res.error());
  1646. }
  1647. static std::string remove_whitespace(const std::string &input) {
  1648. std::string output;
  1649. output.reserve(input.size());
  1650. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1651. [](unsigned char c) { return !std::isspace(c); });
  1652. return output;
  1653. }
  1654. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1655. auto host = "httpbingo.org";
  1656. auto path = std::string{"/basic-auth/hello/world"};
  1657. #ifdef CPPHTTPLIB_SSL_ENABLED
  1658. auto port = 443;
  1659. SSLClient cli(host, port);
  1660. #else
  1661. auto port = 80;
  1662. Client cli(host, port);
  1663. #endif
  1664. {
  1665. auto res = cli.Get(path);
  1666. ASSERT_TRUE(res);
  1667. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1668. }
  1669. {
  1670. auto res =
  1671. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1672. ASSERT_TRUE(res);
  1673. auto body = remove_whitespace(res->body);
  1674. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1675. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1676. EXPECT_EQ(StatusCode::OK_200, res->status);
  1677. }
  1678. {
  1679. cli.set_basic_auth("hello", "world");
  1680. auto res = cli.Get(path);
  1681. ASSERT_TRUE(res);
  1682. auto body = remove_whitespace(res->body);
  1683. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1684. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1685. EXPECT_EQ(StatusCode::OK_200, res->status);
  1686. }
  1687. {
  1688. cli.set_basic_auth("hello", "bad");
  1689. auto res = cli.Get(path);
  1690. ASSERT_TRUE(res);
  1691. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1692. }
  1693. {
  1694. cli.set_basic_auth("bad", "world");
  1695. auto res = cli.Get(path);
  1696. ASSERT_TRUE(res);
  1697. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1698. }
  1699. }
  1700. #ifdef CPPHTTPLIB_SSL_ENABLED
  1701. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1702. auto host = "httpbingo.org";
  1703. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1704. auto paths = std::vector<std::string>{
  1705. "/digest-auth/auth/hello/world/MD5",
  1706. "/digest-auth/auth/hello/world/SHA-256",
  1707. };
  1708. auto port = 443;
  1709. SSLClient cli(host, port);
  1710. {
  1711. auto res = cli.Get(unauth_path);
  1712. ASSERT_TRUE(res);
  1713. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1714. }
  1715. {
  1716. cli.set_digest_auth("hello", "world");
  1717. for (const auto &path : paths) {
  1718. auto res = cli.Get(path.c_str());
  1719. ASSERT_TRUE(res);
  1720. auto body = remove_whitespace(res->body);
  1721. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1722. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1723. EXPECT_EQ(StatusCode::OK_200, res->status);
  1724. }
  1725. cli.set_digest_auth("hello", "bad");
  1726. for (const auto &path : paths) {
  1727. auto res = cli.Get(path.c_str());
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1730. }
  1731. }
  1732. }
  1733. #endif
  1734. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1735. auto host = "google.com";
  1736. auto another_host = "example.com";
  1737. auto wrong_ip = "0.0.0.0";
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1744. auto res = cli.Get("/");
  1745. ASSERT_TRUE(res);
  1746. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1747. }
  1748. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1749. auto host = "google.com";
  1750. auto wrong_ip = "0.0.0.0";
  1751. #ifdef CPPHTTPLIB_SSL_ENABLED
  1752. SSLClient cli(host);
  1753. #else
  1754. Client cli(host);
  1755. #endif
  1756. cli.set_hostname_addr_map({{host, wrong_ip}});
  1757. auto res = cli.Get("/");
  1758. ASSERT_TRUE(!res);
  1759. EXPECT_EQ(Error::Connection, res.error());
  1760. }
  1761. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1762. auto host = "httpbingo.org";
  1763. auto path = std::string{"/absolute-redirect/3"};
  1764. #ifdef CPPHTTPLIB_SSL_ENABLED
  1765. SSLClient cli(host);
  1766. #else
  1767. Client cli(host);
  1768. #endif
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get(path);
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. }
  1774. TEST(RedirectTest, Redirect_Online) {
  1775. auto host = "httpbingo.org";
  1776. auto path = std::string{"/redirect/3"};
  1777. #ifdef CPPHTTPLIB_SSL_ENABLED
  1778. SSLClient cli(host);
  1779. #else
  1780. Client cli(host);
  1781. #endif
  1782. cli.set_follow_location(true);
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::OK_200, res->status);
  1786. }
  1787. TEST(RelativeRedirectTest, Redirect_Online) {
  1788. auto host = "httpbingo.org";
  1789. auto path = std::string{"/relative-redirect/3"};
  1790. #ifdef CPPHTTPLIB_SSL_ENABLED
  1791. SSLClient cli(host);
  1792. #else
  1793. Client cli(host);
  1794. #endif
  1795. cli.set_follow_location(true);
  1796. auto res = cli.Get(path);
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ(StatusCode::OK_200, res->status);
  1799. }
  1800. TEST(TooManyRedirectTest, Redirect_Online) {
  1801. auto host = "httpbingo.org";
  1802. auto path = std::string{"/redirect/21"};
  1803. #ifdef CPPHTTPLIB_SSL_ENABLED
  1804. SSLClient cli(host);
  1805. #else
  1806. Client cli(host);
  1807. #endif
  1808. cli.set_follow_location(true);
  1809. auto res = cli.Get(path);
  1810. ASSERT_TRUE(!res);
  1811. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1812. }
  1813. #ifdef CPPHTTPLIB_SSL_ENABLED
  1814. TEST(YahooRedirectTest, Redirect_Online) {
  1815. Client cli("yahoo.com");
  1816. auto res = cli.Get("/");
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1819. cli.set_follow_location(true);
  1820. res = cli.Get("/");
  1821. ASSERT_TRUE(res);
  1822. EXPECT_EQ(StatusCode::OK_200, res->status);
  1823. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1824. }
  1825. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1826. #define REDIR_HOST "httpbingo.org"
  1827. #define REDIR_PATH "/redirect-to"
  1828. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1829. SSLClient cli(REDIR_HOST);
  1830. cli.set_follow_location(true);
  1831. auto res =
  1832. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1833. ASSERT_TRUE(res);
  1834. EXPECT_EQ(StatusCode::OK_200, res->status);
  1835. }
  1836. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1837. SSLClient cli(REDIR_HOST);
  1838. cli.set_follow_location(true);
  1839. Params params;
  1840. params.emplace("url", "http://example.com");
  1841. params.emplace("status_code", "302");
  1842. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ(StatusCode::OK_200, res->status);
  1845. }
  1846. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1847. SSLClient cli(REDIR_HOST);
  1848. cli.set_follow_location(true);
  1849. Params params;
  1850. params.emplace("url", "http://example.com");
  1851. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(UrlWithSpace, Redirect_Online) {
  1856. SSLClient cli("edge.forgecdn.net");
  1857. cli.set_follow_location(true);
  1858. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1859. ASSERT_TRUE(res);
  1860. EXPECT_EQ(StatusCode::OK_200, res->status);
  1861. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1862. }
  1863. #endif
  1864. #if !defined(_WIN32) && !defined(_WIN64)
  1865. TEST(ReceiveSignals, Signal) {
  1866. auto setupSignalHandlers = []() {
  1867. struct sigaction act;
  1868. sigemptyset(&act.sa_mask);
  1869. act.sa_flags = SA_SIGINFO;
  1870. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1871. switch (sig) {
  1872. case SIGINT:
  1873. default: break;
  1874. }
  1875. };
  1876. ::sigaction(SIGINT, &act, nullptr);
  1877. };
  1878. Server svr;
  1879. int port = 0;
  1880. auto thread = std::thread([&]() {
  1881. setupSignalHandlers();
  1882. port = svr.bind_to_any_port(HOST);
  1883. svr.listen_after_bind();
  1884. });
  1885. auto se = detail::scope_exit([&] {
  1886. svr.stop();
  1887. thread.join();
  1888. ASSERT_FALSE(svr.is_running());
  1889. });
  1890. svr.wait_until_ready();
  1891. ASSERT_TRUE(svr.is_running());
  1892. pthread_kill(thread.native_handle(), SIGINT);
  1893. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1894. ASSERT_TRUE(svr.is_running());
  1895. }
  1896. #endif
  1897. TEST(RedirectToDifferentPort, Redirect) {
  1898. Server svr1;
  1899. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1900. res.set_content("Hello World!", "text/plain");
  1901. });
  1902. int svr1_port = 0;
  1903. auto thread1 = std::thread([&]() {
  1904. svr1_port = svr1.bind_to_any_port(HOST);
  1905. svr1.listen_after_bind();
  1906. });
  1907. Server svr2;
  1908. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1909. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1910. });
  1911. int svr2_port = 0;
  1912. auto thread2 = std::thread([&]() {
  1913. svr2_port = svr2.bind_to_any_port(HOST);
  1914. svr2.listen_after_bind();
  1915. });
  1916. auto se = detail::scope_exit([&] {
  1917. svr2.stop();
  1918. thread2.join();
  1919. svr1.stop();
  1920. thread1.join();
  1921. ASSERT_FALSE(svr2.is_running());
  1922. ASSERT_FALSE(svr1.is_running());
  1923. });
  1924. svr1.wait_until_ready();
  1925. svr2.wait_until_ready();
  1926. Client cli("localhost", svr2_port);
  1927. cli.set_follow_location(true);
  1928. auto res = cli.Get("/2");
  1929. ASSERT_TRUE(res);
  1930. EXPECT_EQ(StatusCode::OK_200, res->status);
  1931. EXPECT_EQ("Hello World!", res->body);
  1932. }
  1933. static void
  1934. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  1935. Server svr1;
  1936. std::string captured_authorization;
  1937. svr1.Get("/target", [&](const Request &req, Response &res) {
  1938. captured_authorization = req.get_header_value("Authorization");
  1939. res.set_content("OK", "text/plain");
  1940. });
  1941. int svr1_port = 0;
  1942. auto thread1 = std::thread([&]() {
  1943. svr1_port = svr1.bind_to_any_port(HOST);
  1944. svr1.listen_after_bind();
  1945. });
  1946. Server svr2;
  1947. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1948. res.set_redirect(
  1949. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  1950. });
  1951. int svr2_port = 0;
  1952. auto thread2 = std::thread([&]() {
  1953. svr2_port = svr2.bind_to_any_port(HOST);
  1954. svr2.listen_after_bind();
  1955. });
  1956. auto se = detail::scope_exit([&] {
  1957. svr2.stop();
  1958. thread2.join();
  1959. svr1.stop();
  1960. thread1.join();
  1961. ASSERT_FALSE(svr2.is_running());
  1962. ASSERT_FALSE(svr1.is_running());
  1963. });
  1964. svr1.wait_until_ready();
  1965. svr2.wait_until_ready();
  1966. Client cli("localhost", svr2_port);
  1967. cli.set_follow_location(true);
  1968. set_auth(cli);
  1969. auto res = cli.Get("/redir");
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. // RFC 9110: credentials MUST NOT be forwarded to a different host
  1973. EXPECT_TRUE(captured_authorization.empty());
  1974. }
  1975. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  1976. TestDoNotForwardCredentialsOnRedirect(
  1977. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  1978. }
  1979. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  1980. TestDoNotForwardCredentialsOnRedirect(
  1981. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  1982. }
  1983. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1984. Server svr;
  1985. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1986. // Port number that overflows int — should not crash
  1987. res.set_redirect("http://localhost:99999999999999999999/target");
  1988. });
  1989. auto port = svr.bind_to_any_port(HOST);
  1990. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. Client cli(HOST, port);
  1998. cli.set_follow_location(true);
  1999. auto res = cli.Get("/redir");
  2000. // Should fail gracefully, not crash (no valid response due to bad port)
  2001. EXPECT_FALSE(res);
  2002. }
  2003. TEST(RedirectFromPageWithContent, Redirect) {
  2004. Server svr;
  2005. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2006. res.set_content("___", "text/plain");
  2007. res.set_redirect("/2");
  2008. });
  2009. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2010. res.set_content("Hello World!", "text/plain");
  2011. });
  2012. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. th.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. svr.wait_until_ready();
  2019. {
  2020. Client cli("localhost", PORT);
  2021. cli.set_follow_location(true);
  2022. std::string body;
  2023. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2024. body.append(data, data_length);
  2025. return true;
  2026. });
  2027. ASSERT_TRUE(res);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. EXPECT_EQ("Hello World!", body);
  2030. }
  2031. {
  2032. Client cli("localhost", PORT);
  2033. std::string body;
  2034. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2035. body.append(data, data_length);
  2036. return true;
  2037. });
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::Found_302, res->status);
  2040. EXPECT_EQ("___", body);
  2041. }
  2042. }
  2043. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2044. Server svr;
  2045. auto port_str = std::to_string(PORT);
  2046. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2047. auto expected_host = "[::1]:" + port_str;
  2048. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2049. res.set_content("___", "text/plain");
  2050. // res.set_redirect("/2");
  2051. res.set_redirect(redirect_url);
  2052. });
  2053. svr.Get("/2", [&](const Request &req, Response &res) {
  2054. auto host_header = req.headers.find("Host");
  2055. ASSERT_TRUE(host_header != req.headers.end());
  2056. EXPECT_EQ(expected_host, host_header->second);
  2057. res.set_content("Hello World!", "text/plain");
  2058. });
  2059. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2060. auto se = detail::scope_exit([&] {
  2061. svr.stop();
  2062. th.join();
  2063. ASSERT_FALSE(svr.is_running());
  2064. });
  2065. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2066. // actually starts anything, so the condition !svr.is_running() will
  2067. // always remain true, and the loop never stops.
  2068. // This basically counts how many milliseconds have passed since the
  2069. // call to svr.listen(), and if after 5 seconds nothing started yet
  2070. // aborts the test.
  2071. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2072. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2073. ASSERT_LT(milliseconds, 5000U);
  2074. }
  2075. {
  2076. Client cli("::1", PORT);
  2077. cli.set_follow_location(true);
  2078. std::string body;
  2079. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2080. body.append(data, data_length);
  2081. return true;
  2082. });
  2083. ASSERT_TRUE(res);
  2084. EXPECT_EQ(StatusCode::OK_200, res->status);
  2085. EXPECT_EQ("Hello World!", body);
  2086. }
  2087. {
  2088. Client cli("::1", PORT);
  2089. std::string body;
  2090. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2091. body.append(data, data_length);
  2092. return true;
  2093. });
  2094. ASSERT_TRUE(res);
  2095. EXPECT_EQ(StatusCode::Found_302, res->status);
  2096. EXPECT_EQ("___", body);
  2097. }
  2098. }
  2099. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2100. Server svr;
  2101. svr.Get("/foo", [](const Request &req, Response &res) {
  2102. auto a = req.params.find("a");
  2103. if (a != req.params.end()) {
  2104. res.set_content((*a).second, "text/plain");
  2105. res.status = StatusCode::OK_200;
  2106. } else {
  2107. res.status = StatusCode::BadRequest_400;
  2108. }
  2109. });
  2110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2111. auto se = detail::scope_exit([&] {
  2112. svr.stop();
  2113. thread.join();
  2114. ASSERT_FALSE(svr.is_running());
  2115. });
  2116. svr.wait_until_ready();
  2117. {
  2118. Client cli(HOST, PORT);
  2119. cli.set_path_encode(false);
  2120. auto res = cli.Get("/foo?a=explicitly+encoded");
  2121. ASSERT_TRUE(res);
  2122. EXPECT_EQ(StatusCode::OK_200, res->status);
  2123. // This expects it back with a space, as the `+` won't have been
  2124. // url-encoded, and server-side the params get decoded turning `+`
  2125. // into spaces.
  2126. EXPECT_EQ("explicitly encoded", res->body);
  2127. }
  2128. }
  2129. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2130. Server svr;
  2131. svr.Get("/", [](const Request &req, Response &) {
  2132. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2133. });
  2134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2135. auto se = detail::scope_exit([&] {
  2136. svr.stop();
  2137. thread.join();
  2138. ASSERT_FALSE(svr.is_running());
  2139. });
  2140. svr.wait_until_ready();
  2141. {
  2142. Client cli(HOST, PORT);
  2143. cli.set_path_encode(false);
  2144. auto res = cli.Get("/?something=%0A");
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. }
  2148. }
  2149. TEST(BindServerTest, BindDualStack) {
  2150. Server svr;
  2151. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2152. res.set_content("Hello World!", "text/plain");
  2153. });
  2154. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2155. auto se = detail::scope_exit([&] {
  2156. svr.stop();
  2157. thread.join();
  2158. ASSERT_FALSE(svr.is_running());
  2159. });
  2160. svr.wait_until_ready();
  2161. {
  2162. Client cli("127.0.0.1", PORT);
  2163. auto res = cli.Get("/1");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. EXPECT_EQ("Hello World!", res->body);
  2167. }
  2168. {
  2169. Client cli("::1", PORT);
  2170. auto res = cli.Get("/1");
  2171. ASSERT_TRUE(res);
  2172. EXPECT_EQ(StatusCode::OK_200, res->status);
  2173. EXPECT_EQ("Hello World!", res->body);
  2174. }
  2175. }
  2176. TEST(BindServerTest, BindAndListenSeparately) {
  2177. Server svr;
  2178. int port = svr.bind_to_any_port("0.0.0.0");
  2179. ASSERT_TRUE(svr.is_valid());
  2180. ASSERT_TRUE(port > 0);
  2181. svr.stop();
  2182. }
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2186. CLIENT_CA_CERT_DIR);
  2187. int port = svr.bind_to_any_port("0.0.0.0");
  2188. ASSERT_TRUE(svr.is_valid());
  2189. ASSERT_TRUE(port > 0);
  2190. svr.stop();
  2191. }
  2192. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2193. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2194. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2195. int port = svr.bind_to_any_port("0.0.0.0");
  2196. ASSERT_TRUE(svr.is_valid());
  2197. ASSERT_TRUE(port > 0);
  2198. svr.stop();
  2199. }
  2200. TEST(BindServerTest, UpdateCertsPem) {
  2201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2202. int port = svr.bind_to_any_port("0.0.0.0");
  2203. ASSERT_TRUE(svr.is_valid());
  2204. ASSERT_TRUE(port > 0);
  2205. // Read PEM files
  2206. std::string cert_pem, key_pem, ca_pem;
  2207. read_file(SERVER_CERT_FILE, cert_pem);
  2208. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2209. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2210. // Update server certificates using PEM API
  2211. ASSERT_TRUE(
  2212. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2213. ASSERT_TRUE(svr.is_valid());
  2214. svr.stop();
  2215. }
  2216. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2217. // Start server with client CA (enables client auth)
  2218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2219. ASSERT_TRUE(svr.is_valid());
  2220. bool handler_called = false;
  2221. svr.Get("/test", [&](const Request &req, Response &res) {
  2222. handler_called = true;
  2223. // Verify client certificate is present
  2224. auto cert = req.peer_cert();
  2225. EXPECT_TRUE(static_cast<bool>(cert));
  2226. res.set_content("ok", "text/plain");
  2227. });
  2228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. t.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. // Read PEM files
  2236. std::string cert_pem, key_pem, ca_pem;
  2237. read_file(SERVER_CERT_FILE, cert_pem);
  2238. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2239. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2240. // Update server certificates and client CA using PEM API while server running
  2241. ASSERT_TRUE(
  2242. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2243. // Connect with client certificate
  2244. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2245. cli.enable_server_certificate_verification(false);
  2246. cli.set_connection_timeout(30);
  2247. auto res = cli.Get("/test");
  2248. ASSERT_TRUE(res);
  2249. ASSERT_EQ(StatusCode::OK_200, res->status);
  2250. ASSERT_TRUE(handler_called);
  2251. EXPECT_EQ("ok", res->body);
  2252. }
  2253. #endif
  2254. TEST(ErrorHandlerTest, ContentLength) {
  2255. Server svr;
  2256. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2257. res.status = StatusCode::OK_200;
  2258. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2259. "text/html"); // <= Content-Length still 13
  2260. });
  2261. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2262. res.set_content("Hello World!\n", "text/plain");
  2263. res.status = 524;
  2264. });
  2265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2266. auto se = detail::scope_exit([&] {
  2267. svr.stop();
  2268. thread.join();
  2269. ASSERT_FALSE(svr.is_running());
  2270. });
  2271. svr.wait_until_ready();
  2272. {
  2273. Client cli(HOST, PORT);
  2274. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(StatusCode::OK_200, res->status);
  2277. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2278. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2280. }
  2281. }
  2282. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2283. TEST(ExceptionTest, WithoutExceptionHandler) {
  2284. Server svr;
  2285. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2286. throw std::runtime_error("exception...");
  2287. });
  2288. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2289. throw std::runtime_error("exception\r\n...");
  2290. });
  2291. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2292. auto se = detail::scope_exit([&] {
  2293. svr.stop();
  2294. listen_thread.join();
  2295. ASSERT_FALSE(svr.is_running());
  2296. });
  2297. svr.wait_until_ready();
  2298. Client cli("localhost", PORT);
  2299. {
  2300. auto res = cli.Get("/exception");
  2301. ASSERT_TRUE(res);
  2302. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2303. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2304. }
  2305. {
  2306. auto res = cli.Get("/unknown");
  2307. ASSERT_TRUE(res);
  2308. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2309. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2310. }
  2311. }
  2312. TEST(ExceptionTest, WithExceptionHandler) {
  2313. Server svr;
  2314. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2315. std::exception_ptr ep) {
  2316. EXPECT_FALSE(ep == nullptr);
  2317. try {
  2318. std::rethrow_exception(ep);
  2319. } catch (std::exception &e) {
  2320. EXPECT_EQ("abc", std::string(e.what()));
  2321. } catch (...) {}
  2322. res.status = StatusCode::InternalServerError_500;
  2323. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2324. "text/html"); // <= Content-Length still 13 at this point
  2325. });
  2326. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2327. res.set_content("Hello World!\n", "text/plain");
  2328. throw std::runtime_error("abc");
  2329. });
  2330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. thread.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. for (size_t i = 0; i < 10; i++) {
  2338. Client cli(HOST, PORT);
  2339. for (size_t j = 0; j < 100; j++) {
  2340. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2341. ASSERT_TRUE(res);
  2342. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2343. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2344. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2345. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2346. }
  2347. cli.set_keep_alive(true);
  2348. for (size_t j = 0; j < 100; j++) {
  2349. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2350. ASSERT_TRUE(res);
  2351. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2353. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2354. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2355. }
  2356. }
  2357. }
  2358. TEST(ExceptionTest, AndErrorHandler) {
  2359. Server svr;
  2360. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2361. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2362. });
  2363. svr.set_exception_handler(
  2364. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2365. EXPECT_FALSE(ep == nullptr);
  2366. try {
  2367. std::rethrow_exception(ep);
  2368. } catch (std::exception &e) {
  2369. res.set_content(e.what(), "text/html");
  2370. } catch (...) {}
  2371. res.status = StatusCode::InternalServerError_500;
  2372. });
  2373. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2374. throw std::runtime_error("EXCEPTION");
  2375. });
  2376. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2377. res.set_content("ERROR", "text/html");
  2378. res.status = StatusCode::InternalServerError_500;
  2379. });
  2380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2381. auto se = detail::scope_exit([&] {
  2382. svr.stop();
  2383. thread.join();
  2384. ASSERT_FALSE(svr.is_running());
  2385. });
  2386. svr.wait_until_ready();
  2387. Client cli(HOST, PORT);
  2388. {
  2389. auto res = cli.Get("/exception");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2392. EXPECT_EQ("EXCEPTION", res->body);
  2393. }
  2394. {
  2395. auto res = cli.Get("/error");
  2396. ASSERT_TRUE(res);
  2397. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2398. EXPECT_EQ("ERROR", res->body);
  2399. }
  2400. {
  2401. auto res = cli.Get("/invalid");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2404. EXPECT_EQ("NOT_FOUND", res->body);
  2405. }
  2406. }
  2407. #endif
  2408. TEST(NoContentTest, ContentLength) {
  2409. Server svr;
  2410. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2411. res.status = StatusCode::NoContent_204;
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. {
  2421. Client cli(HOST, PORT);
  2422. auto res = cli.Get("/hi");
  2423. ASSERT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2425. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2426. }
  2427. }
  2428. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2429. #ifdef CPPHTTPLIB_SSL_ENABLED
  2430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2431. ASSERT_TRUE(svr.is_valid());
  2432. #else
  2433. Server svr;
  2434. #endif
  2435. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2436. if (req.path == "/routing_handler") {
  2437. res.set_header("PRE_ROUTING", "on");
  2438. res.set_content("Routing Handler", "text/plain");
  2439. return httplib::Server::HandlerResponse::Handled;
  2440. }
  2441. return httplib::Server::HandlerResponse::Unhandled;
  2442. });
  2443. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2444. res.set_content("Error", "text/html");
  2445. });
  2446. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2447. if (req.path == "/routing_handler") {
  2448. res.set_header("POST_ROUTING", "on");
  2449. }
  2450. });
  2451. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2452. res.set_content("Hello World!\n", "text/plain");
  2453. });
  2454. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2455. auto se = detail::scope_exit([&] {
  2456. svr.stop();
  2457. thread.join();
  2458. ASSERT_FALSE(svr.is_running());
  2459. });
  2460. svr.wait_until_ready();
  2461. {
  2462. #ifdef CPPHTTPLIB_SSL_ENABLED
  2463. SSLClient cli(HOST, PORT);
  2464. cli.enable_server_certificate_verification(false);
  2465. #else
  2466. Client cli(HOST, PORT);
  2467. #endif
  2468. auto res = cli.Get("/routing_handler");
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. EXPECT_EQ("Routing Handler", res->body);
  2472. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2473. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2474. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2475. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2476. }
  2477. {
  2478. #ifdef CPPHTTPLIB_SSL_ENABLED
  2479. SSLClient cli(HOST, PORT);
  2480. cli.enable_server_certificate_verification(false);
  2481. #else
  2482. Client cli(HOST, PORT);
  2483. #endif
  2484. auto res = cli.Get("/hi");
  2485. ASSERT_TRUE(res);
  2486. EXPECT_EQ(StatusCode::OK_200, res->status);
  2487. EXPECT_EQ("Hello World!\n", res->body);
  2488. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2489. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2490. }
  2491. {
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(HOST, PORT);
  2494. cli.enable_server_certificate_verification(false);
  2495. #else
  2496. Client cli(HOST, PORT);
  2497. #endif
  2498. auto res = cli.Get("/aaa");
  2499. ASSERT_TRUE(res);
  2500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2501. EXPECT_EQ("Error", res->body);
  2502. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2503. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2504. }
  2505. }
  2506. TEST(RequestHandlerTest, PreRequestHandler) {
  2507. auto route_path = "/user/:user";
  2508. Server svr;
  2509. svr.Get("/hi", [](const Request &, Response &res) {
  2510. res.set_content("hi", "text/plain");
  2511. });
  2512. svr.Get(route_path, [](const Request &req, Response &res) {
  2513. res.set_content(req.path_params.at("user"), "text/plain");
  2514. });
  2515. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2516. if (req.matched_route == route_path) {
  2517. auto user = req.path_params.at("user");
  2518. if (user != "john") {
  2519. res.status = StatusCode::Forbidden_403;
  2520. res.set_content("error", "text/html");
  2521. return Server::HandlerResponse::Handled;
  2522. }
  2523. }
  2524. return Server::HandlerResponse::Unhandled;
  2525. });
  2526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(HOST, PORT);
  2534. {
  2535. auto res = cli.Get("/hi");
  2536. ASSERT_TRUE(res);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. EXPECT_EQ("hi", res->body);
  2539. }
  2540. {
  2541. auto res = cli.Get("/user/john");
  2542. ASSERT_TRUE(res);
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. EXPECT_EQ("john", res->body);
  2545. }
  2546. {
  2547. auto res = cli.Get("/user/invalid-user");
  2548. ASSERT_TRUE(res);
  2549. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2550. EXPECT_EQ("error", res->body);
  2551. }
  2552. }
  2553. TEST(UserDataTest, BasicOperations) {
  2554. httplib::UserData ud;
  2555. // Initially empty
  2556. EXPECT_FALSE(ud.has("key"));
  2557. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2558. // set and get
  2559. ud.set("key", 42);
  2560. EXPECT_TRUE(ud.has("key"));
  2561. auto *p = ud.get<int>("key");
  2562. ASSERT_NE(nullptr, p);
  2563. EXPECT_EQ(42, *p);
  2564. // Type mismatch → nullptr
  2565. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2566. // Overwrite with different type
  2567. ud.set("key", std::string("hello"));
  2568. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2569. auto *s = ud.get<std::string>("key");
  2570. ASSERT_NE(nullptr, s);
  2571. EXPECT_EQ("hello", *s);
  2572. // erase
  2573. ud.erase("key");
  2574. EXPECT_FALSE(ud.has("key"));
  2575. // clear
  2576. ud.set("a", 1);
  2577. ud.set("b", 2);
  2578. ud.clear();
  2579. EXPECT_FALSE(ud.has("a"));
  2580. EXPECT_FALSE(ud.has("b"));
  2581. }
  2582. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2583. struct AuthCtx {
  2584. std::string user_id;
  2585. };
  2586. Server svr;
  2587. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2588. res.user_data.set("auth", AuthCtx{"alice"});
  2589. return Server::HandlerResponse::Unhandled;
  2590. });
  2591. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2592. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2593. ASSERT_NE(nullptr, ctx);
  2594. res.set_content("Hello " + ctx->user_id, "text/plain");
  2595. });
  2596. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2597. auto se = detail::scope_exit([&] {
  2598. svr.stop();
  2599. thread.join();
  2600. ASSERT_FALSE(svr.is_running());
  2601. });
  2602. svr.wait_until_ready();
  2603. Client cli(HOST, PORT);
  2604. auto res = cli.Get("/me");
  2605. ASSERT_TRUE(res);
  2606. EXPECT_EQ(StatusCode::OK_200, res->status);
  2607. EXPECT_EQ("Hello alice", res->body);
  2608. }
  2609. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2610. struct RoleCtx {
  2611. std::string role;
  2612. };
  2613. Server svr;
  2614. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2615. res.user_data.set("role", RoleCtx{"admin"});
  2616. return Server::HandlerResponse::Unhandled;
  2617. });
  2618. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2619. auto *ctx = res.user_data.get<RoleCtx>("role");
  2620. ASSERT_NE(nullptr, ctx);
  2621. res.set_content(ctx->role, "text/plain");
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, PORT);
  2631. auto res = cli.Get("/role");
  2632. ASSERT_TRUE(res);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. EXPECT_EQ("admin", res->body);
  2635. }
  2636. TEST(InvalidFormatTest, StatusCode) {
  2637. Server svr;
  2638. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2639. res.set_content("Hello World!\n", "text/plain");
  2640. res.status = 9999; // Status should be a three-digit code...
  2641. });
  2642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2643. auto se = detail::scope_exit([&] {
  2644. svr.stop();
  2645. thread.join();
  2646. ASSERT_FALSE(svr.is_running());
  2647. });
  2648. svr.wait_until_ready();
  2649. {
  2650. Client cli(HOST, PORT);
  2651. auto res = cli.Get("/hi");
  2652. ASSERT_FALSE(res);
  2653. }
  2654. }
  2655. TEST(URLFragmentTest, WithFragment) {
  2656. Server svr;
  2657. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2658. EXPECT_TRUE(req.target == "/hi");
  2659. });
  2660. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2661. auto se = detail::scope_exit([&] {
  2662. svr.stop();
  2663. thread.join();
  2664. ASSERT_FALSE(svr.is_running());
  2665. });
  2666. svr.wait_until_ready();
  2667. {
  2668. Client cli(HOST, PORT);
  2669. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2670. EXPECT_TRUE(res);
  2671. EXPECT_EQ(StatusCode::OK_200, res->status);
  2672. res = cli.Get("/hi%23key1=val1=key2=val2");
  2673. EXPECT_TRUE(res);
  2674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2675. }
  2676. }
  2677. TEST(HeaderWriter, SetHeaderWriter) {
  2678. Server svr;
  2679. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2680. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2681. return detail::write_headers(strm, hdrs);
  2682. });
  2683. svr.Get("/hi", [](const Request &req, Response &res) {
  2684. auto it = req.headers.find("CustomClientHeader");
  2685. EXPECT_TRUE(it != req.headers.end());
  2686. EXPECT_EQ(it->second, "CustomClientValue");
  2687. res.set_content("Hello World!\n", "text/plain");
  2688. });
  2689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2690. auto se = detail::scope_exit([&] {
  2691. svr.stop();
  2692. thread.join();
  2693. ASSERT_FALSE(svr.is_running());
  2694. });
  2695. svr.wait_until_ready();
  2696. {
  2697. Client cli(HOST, PORT);
  2698. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2699. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2700. return detail::write_headers(strm, hdrs);
  2701. });
  2702. auto res = cli.Get("/hi");
  2703. EXPECT_TRUE(res);
  2704. EXPECT_EQ(StatusCode::OK_200, res->status);
  2705. auto it = res->headers.find("CustomServerHeader");
  2706. EXPECT_TRUE(it != res->headers.end());
  2707. EXPECT_EQ(it->second, "CustomServerValue");
  2708. }
  2709. }
  2710. class ServerTest : public ::testing::Test {
  2711. protected:
  2712. ServerTest()
  2713. : cli_(HOST, PORT)
  2714. #ifdef CPPHTTPLIB_SSL_ENABLED
  2715. ,
  2716. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2717. #endif
  2718. {
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. cli_.enable_server_certificate_verification(false);
  2721. #endif
  2722. // Allow LARGE_DATA (100MB) responses
  2723. cli_.set_payload_max_length(200 * 1024 * 1024);
  2724. }
  2725. virtual void SetUp() {
  2726. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2727. svr_.set_payload_max_length(200 * 1024 * 1024);
  2728. svr_.set_mount_point("/", "./www");
  2729. svr_.set_mount_point("/mount", "./www2");
  2730. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2731. svr_.Get("/hi",
  2732. [&](const Request & /*req*/, Response &res) {
  2733. res.set_content("Hello World!", "text/plain");
  2734. })
  2735. .Get("/file_content",
  2736. [&](const Request & /*req*/, Response &res) {
  2737. res.set_file_content("./www/dir/test.html");
  2738. })
  2739. .Get("/file_content_with_content_type",
  2740. [&](const Request & /*req*/, Response &res) {
  2741. res.set_file_content("./www/file", "text/plain");
  2742. })
  2743. .Get("/invalid_file_content",
  2744. [&](const Request & /*req*/, Response &res) {
  2745. res.set_file_content("./www/dir/invalid_file_path");
  2746. })
  2747. .Get("/http_response_splitting",
  2748. [&](const Request & /*req*/, Response &res) {
  2749. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2750. EXPECT_EQ(0U, res.headers.size());
  2751. EXPECT_FALSE(res.has_header("a"));
  2752. res.set_header("a", "1\nSet-Cookie: a=1");
  2753. EXPECT_EQ(0U, res.headers.size());
  2754. EXPECT_FALSE(res.has_header("a"));
  2755. res.set_header("a", "1\rSet-Cookie: a=1");
  2756. EXPECT_EQ(0U, res.headers.size());
  2757. EXPECT_FALSE(res.has_header("a"));
  2758. res.set_header("a\r\nb", "0");
  2759. EXPECT_EQ(0U, res.headers.size());
  2760. EXPECT_FALSE(res.has_header("a"));
  2761. res.set_header("a\rb", "0");
  2762. EXPECT_EQ(0U, res.headers.size());
  2763. EXPECT_FALSE(res.has_header("a"));
  2764. res.set_header("a\nb", "0");
  2765. EXPECT_EQ(0U, res.headers.size());
  2766. EXPECT_FALSE(res.has_header("a"));
  2767. res.set_redirect("1\r\nSet-Cookie: a=1");
  2768. EXPECT_EQ(0U, res.headers.size());
  2769. EXPECT_FALSE(res.has_header("Location"));
  2770. })
  2771. .Get("/slow",
  2772. [&](const Request & /*req*/, Response &res) {
  2773. std::this_thread::sleep_for(std::chrono::seconds(2));
  2774. res.set_content("slow", "text/plain");
  2775. })
  2776. #if 0
  2777. .Post("/slowpost",
  2778. [&](const Request & /*req*/, Response &res) {
  2779. std::this_thread::sleep_for(std::chrono::seconds(2));
  2780. res.set_content("slow", "text/plain");
  2781. })
  2782. #endif
  2783. .Get("/remote_addr",
  2784. [&](const Request &req, Response &res) {
  2785. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2786. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2787. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2788. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2789. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2790. #endif
  2791. res.set_content(req.remote_addr, "text/plain");
  2792. })
  2793. .Get("/local_addr",
  2794. [&](const Request &req, Response &res) {
  2795. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2796. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2797. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2798. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2799. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2800. #endif
  2801. auto local_addr = req.local_addr;
  2802. auto local_port = std::to_string(req.local_port);
  2803. res.set_content(local_addr.append(":").append(local_port),
  2804. "text/plain");
  2805. })
  2806. .Get("/endwith%",
  2807. [&](const Request & /*req*/, Response &res) {
  2808. res.set_content("Hello World!", "text/plain");
  2809. })
  2810. .Get("/a\\+\\+b",
  2811. [&](const Request &req, Response &res) {
  2812. ASSERT_TRUE(req.has_param("a +b"));
  2813. auto val = req.get_param_value("a +b");
  2814. res.set_content(val, "text/plain");
  2815. })
  2816. .Get("/", [&](const Request & /*req*/,
  2817. Response &res) { res.set_redirect("/hi"); })
  2818. .Post("/1",
  2819. [](const Request & /*req*/, Response &res) {
  2820. res.set_redirect("/2", StatusCode::SeeOther_303);
  2821. })
  2822. .Get("/2",
  2823. [](const Request & /*req*/, Response &res) {
  2824. res.set_content("redirected.", "text/plain");
  2825. res.status = StatusCode::OK_200;
  2826. })
  2827. .Post("/person",
  2828. [&](const Request &req, Response &res) {
  2829. if (req.has_param("name") && req.has_param("note")) {
  2830. persons_[req.get_param_value("name")] =
  2831. req.get_param_value("note");
  2832. } else {
  2833. res.status = StatusCode::BadRequest_400;
  2834. }
  2835. })
  2836. .Put("/person",
  2837. [&](const Request &req, Response &res) {
  2838. if (req.has_param("name") && req.has_param("note")) {
  2839. persons_[req.get_param_value("name")] =
  2840. req.get_param_value("note");
  2841. } else {
  2842. res.status = StatusCode::BadRequest_400;
  2843. }
  2844. })
  2845. .Get("/person/(.*)",
  2846. [&](const Request &req, Response &res) {
  2847. string name = req.matches[1];
  2848. if (persons_.find(name) != persons_.end()) {
  2849. auto note = persons_[name];
  2850. res.set_content(note, "text/plain");
  2851. } else {
  2852. res.status = StatusCode::NotFound_404;
  2853. }
  2854. })
  2855. .Delete("/person",
  2856. [&](const Request &req, Response &res) {
  2857. if (req.has_param("name")) {
  2858. string name = req.get_param_value("name");
  2859. if (persons_.find(name) != persons_.end()) {
  2860. persons_.erase(name);
  2861. res.set_content("DELETED", "text/plain");
  2862. } else {
  2863. res.status = StatusCode::NotFound_404;
  2864. }
  2865. } else {
  2866. res.status = StatusCode::BadRequest_400;
  2867. }
  2868. })
  2869. .Post("/x-www-form-urlencoded-json",
  2870. [&](const Request &req, Response &res) {
  2871. auto json = req.get_param_value("json");
  2872. ASSERT_EQ(JSON_DATA, json);
  2873. res.set_content(json, "appliation/json");
  2874. res.status = StatusCode::OK_200;
  2875. })
  2876. .Get("/streamed-chunked",
  2877. [&](const Request & /*req*/, Response &res) {
  2878. res.set_chunked_content_provider(
  2879. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2880. sink.os << "123";
  2881. sink.os << "456";
  2882. sink.os << "789";
  2883. sink.done();
  2884. return true;
  2885. });
  2886. })
  2887. .Get("/streamed-chunked-with-prohibited-trailer",
  2888. [&](const Request & /*req*/, Response &res) {
  2889. auto i = new int(0);
  2890. // Declare both a prohibited trailer (Content-Length) and an
  2891. // allowed one
  2892. res.set_header("Trailer", "Content-Length, X-Allowed");
  2893. res.set_chunked_content_provider(
  2894. "text/plain",
  2895. [i](size_t /*offset*/, DataSink &sink) {
  2896. switch (*i) {
  2897. case 0: sink.os << "123"; break;
  2898. case 1: sink.os << "456"; break;
  2899. case 2: sink.os << "789"; break;
  2900. case 3: {
  2901. sink.done_with_trailer(
  2902. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2903. } break;
  2904. }
  2905. (*i)++;
  2906. return true;
  2907. },
  2908. [i](bool success) {
  2909. EXPECT_TRUE(success);
  2910. delete i;
  2911. });
  2912. })
  2913. .Get("/streamed-chunked2",
  2914. [&](const Request & /*req*/, Response &res) {
  2915. auto i = new int(0);
  2916. res.set_chunked_content_provider(
  2917. "text/plain",
  2918. [i](size_t /*offset*/, DataSink &sink) {
  2919. switch (*i) {
  2920. case 0: sink.os << "123"; break;
  2921. case 1: sink.os << "456"; break;
  2922. case 2: sink.os << "789"; break;
  2923. case 3: sink.done(); break;
  2924. }
  2925. (*i)++;
  2926. return true;
  2927. },
  2928. [i](bool success) {
  2929. EXPECT_TRUE(success);
  2930. delete i;
  2931. });
  2932. })
  2933. .Get("/streamed-chunked-with-trailer",
  2934. [&](const Request & /*req*/, Response &res) {
  2935. auto i = new int(0);
  2936. res.set_header("Trailer", "Dummy1, Dummy2");
  2937. res.set_chunked_content_provider(
  2938. "text/plain",
  2939. [i](size_t /*offset*/, DataSink &sink) {
  2940. switch (*i) {
  2941. case 0: sink.os << "123"; break;
  2942. case 1: sink.os << "456"; break;
  2943. case 2: sink.os << "789"; break;
  2944. case 3: {
  2945. sink.done_with_trailer(
  2946. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2947. } break;
  2948. }
  2949. (*i)++;
  2950. return true;
  2951. },
  2952. [i](bool success) {
  2953. EXPECT_TRUE(success);
  2954. delete i;
  2955. });
  2956. })
  2957. .Get("/streamed",
  2958. [&](const Request & /*req*/, Response &res) {
  2959. res.set_content_provider(
  2960. 6, "text/plain",
  2961. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2962. sink.os << (offset < 3 ? "a" : "b");
  2963. return true;
  2964. });
  2965. })
  2966. .Get("/streamed-with-range",
  2967. [&](const Request &req, Response &res) {
  2968. auto data = new std::string("abcdefg");
  2969. res.set_content_provider(
  2970. data->size(), "text/plain",
  2971. [data](size_t offset, size_t length, DataSink &sink) {
  2972. size_t DATA_CHUNK_SIZE = 4;
  2973. const auto &d = *data;
  2974. auto out_len =
  2975. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2976. auto ret =
  2977. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2978. EXPECT_TRUE(ret);
  2979. return true;
  2980. },
  2981. [data, &req](bool success) {
  2982. EXPECT_EQ(success, !req.has_param("error"));
  2983. delete data;
  2984. });
  2985. })
  2986. .Get("/streamed-cancel",
  2987. [&](const Request & /*req*/, Response &res) {
  2988. res.set_content_provider(
  2989. size_t(-1), "text/plain",
  2990. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2991. sink.os << "data_chunk";
  2992. return true;
  2993. });
  2994. })
  2995. .Get("/regex-with-delimiter",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. ASSERT_TRUE(req.has_param("key"));
  2998. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2999. })
  3000. .Get("/with-range",
  3001. [&](const Request & /*req*/, Response &res) {
  3002. res.set_content("abcdefg", "text/plain");
  3003. })
  3004. .Get("/test-start-time",
  3005. [&](const Request &req, Response & /*res*/) {
  3006. EXPECT_NE(req.start_time_,
  3007. std::chrono::steady_clock::time_point::min());
  3008. })
  3009. .Get("/with-range-customized-response",
  3010. [&](const Request & /*req*/, Response &res) {
  3011. res.status = StatusCode::BadRequest_400;
  3012. res.set_content(JSON_DATA, "application/json");
  3013. })
  3014. .Post("/chunked",
  3015. [&](const Request &req, Response & /*res*/) {
  3016. EXPECT_EQ(req.body, "dechunked post body");
  3017. })
  3018. .Post("/large-chunked",
  3019. [&](const Request &req, Response & /*res*/) {
  3020. std::string expected(6 * 30 * 1024u, 'a');
  3021. EXPECT_EQ(req.body, expected);
  3022. })
  3023. .Post("/multipart",
  3024. [&](const Request &req, Response & /*res*/) {
  3025. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3026. req.form.get_field_count("text2") +
  3027. req.form.get_field_count("file3") +
  3028. req.form.get_field_count("file4"));
  3029. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3030. req.form.get_file_count("file2"));
  3031. ASSERT_TRUE(!req.form.has_file("???"));
  3032. ASSERT_TRUE(!req.form.has_field("???"));
  3033. ASSERT_TRUE(req.body.empty());
  3034. {
  3035. const auto &text = req.form.get_field("text1");
  3036. EXPECT_EQ("text default", text);
  3037. }
  3038. {
  3039. const auto &text = req.form.get_field("text2");
  3040. EXPECT_EQ("aωb", text);
  3041. }
  3042. {
  3043. const auto &file = req.form.get_file("file1");
  3044. EXPECT_EQ("hello.txt", file.filename);
  3045. EXPECT_EQ("text/plain", file.content_type);
  3046. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3047. }
  3048. {
  3049. const auto &file = req.form.get_file("file2");
  3050. EXPECT_EQ("world.json", file.filename);
  3051. EXPECT_EQ("application/json", file.content_type);
  3052. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3053. }
  3054. {
  3055. const auto &text = req.form.get_field("file3");
  3056. EXPECT_EQ(0u, text.size());
  3057. }
  3058. {
  3059. const auto &text = req.form.get_field("file4");
  3060. EXPECT_EQ(0u, text.size());
  3061. }
  3062. })
  3063. .Post("/multipart/multi_file_values",
  3064. [&](const Request &req, Response & /*res*/) {
  3065. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3066. req.form.get_field_count("multi_text1"));
  3067. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3068. ASSERT_TRUE(!req.form.has_file("???"));
  3069. ASSERT_TRUE(!req.form.has_field("???"));
  3070. ASSERT_TRUE(req.body.empty());
  3071. {
  3072. const auto &text = req.form.get_field("text");
  3073. EXPECT_EQ("default text", text);
  3074. }
  3075. {
  3076. const auto &text1_values = req.form.get_fields("multi_text1");
  3077. EXPECT_EQ(2u, text1_values.size());
  3078. EXPECT_EQ("aaaaa", text1_values[0]);
  3079. EXPECT_EQ("bbbbb", text1_values[1]);
  3080. }
  3081. {
  3082. const auto &file1_values = req.form.get_files("multi_file1");
  3083. EXPECT_EQ(2u, file1_values.size());
  3084. auto file1 = file1_values[0];
  3085. EXPECT_EQ(file1.filename, "hello.txt");
  3086. EXPECT_EQ(file1.content_type, "text/plain");
  3087. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3088. auto file2 = file1_values[1];
  3089. EXPECT_EQ(file2.filename, "world.json");
  3090. EXPECT_EQ(file2.content_type, "application/json");
  3091. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3092. }
  3093. })
  3094. .Post("/empty",
  3095. [&](const Request &req, Response &res) {
  3096. EXPECT_EQ(req.body, "");
  3097. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3098. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3099. res.set_content("empty", "text/plain");
  3100. })
  3101. .Post("/empty-no-content-type",
  3102. [&](const Request &req, Response &res) {
  3103. EXPECT_EQ(req.body, "");
  3104. EXPECT_FALSE(req.has_header("Content-Type"));
  3105. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3106. res.set_content("empty-no-content-type", "text/plain");
  3107. })
  3108. .Post("/path-only",
  3109. [&](const Request &req, Response &res) {
  3110. EXPECT_EQ(req.body, "");
  3111. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3112. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3113. res.set_content("path-only", "text/plain");
  3114. })
  3115. .Post("/path-headers-only",
  3116. [&](const Request &req, Response &res) {
  3117. EXPECT_EQ(req.body, "");
  3118. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3120. EXPECT_EQ("world", req.get_header_value("hello"));
  3121. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3122. res.set_content("path-headers-only", "text/plain");
  3123. })
  3124. .Post("/post-large",
  3125. [&](const Request &req, Response &res) {
  3126. EXPECT_EQ(req.body, LARGE_DATA);
  3127. res.set_content(req.body, "text/plain");
  3128. })
  3129. .Post("/post-loopback",
  3130. [&](const Request &, Response &res,
  3131. ContentReader const &content_reader) {
  3132. std::string body;
  3133. content_reader([&](const char *data, size_t data_length) {
  3134. body.append(data, data_length);
  3135. return true;
  3136. });
  3137. res.set_content(body, "text/plain");
  3138. })
  3139. .Put("/put-loopback",
  3140. [&](const Request &, Response &res,
  3141. ContentReader const &content_reader) {
  3142. std::string body;
  3143. content_reader([&](const char *data, size_t data_length) {
  3144. body.append(data, data_length);
  3145. return true;
  3146. });
  3147. res.set_content(body, "text/plain");
  3148. })
  3149. .Patch("/patch-loopback",
  3150. [&](const Request &, Response &res,
  3151. ContentReader const &content_reader) {
  3152. std::string body;
  3153. content_reader([&](const char *data, size_t data_length) {
  3154. body.append(data, data_length);
  3155. return true;
  3156. });
  3157. res.set_content(body, "text/plain");
  3158. })
  3159. .Put("/empty-no-content-type",
  3160. [&](const Request &req, Response &res) {
  3161. EXPECT_EQ(req.body, "");
  3162. EXPECT_FALSE(req.has_header("Content-Type"));
  3163. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3164. res.set_content("empty-no-content-type", "text/plain");
  3165. })
  3166. .Put("/put",
  3167. [&](const Request &req, Response &res) {
  3168. EXPECT_EQ(req.body, "PUT");
  3169. res.set_content(req.body, "text/plain");
  3170. })
  3171. .Put("/put-large",
  3172. [&](const Request &req, Response &res) {
  3173. EXPECT_EQ(req.body, LARGE_DATA);
  3174. res.set_content(req.body, "text/plain");
  3175. })
  3176. .Patch("/patch",
  3177. [&](const Request &req, Response &res) {
  3178. EXPECT_EQ(req.body, "PATCH");
  3179. res.set_content(req.body, "text/plain");
  3180. })
  3181. .Delete("/delete",
  3182. [&](const Request & /*req*/, Response &res) {
  3183. res.set_content("DELETE", "text/plain");
  3184. })
  3185. .Delete("/delete-body",
  3186. [&](const Request &req, Response &res) {
  3187. EXPECT_EQ(req.body, "content");
  3188. res.set_content(req.body, "text/plain");
  3189. })
  3190. .Options(R"(\*)",
  3191. [&](const Request & /*req*/, Response &res) {
  3192. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3193. })
  3194. .Get("/request-target",
  3195. [&](const Request &req, Response & /*res*/) {
  3196. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3197. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3198. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3199. })
  3200. .Get("/long-query-value",
  3201. [&](const Request &req, Response & /*res*/) {
  3202. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3203. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3204. })
  3205. .Get("/too-long-query-value",
  3206. [&](const Request &req, Response & /*res*/) {
  3207. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3208. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3209. })
  3210. .Get("/array-param",
  3211. [&](const Request &req, Response & /*res*/) {
  3212. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3213. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3214. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3215. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3216. })
  3217. .Get("/array-param-values",
  3218. [&](const Request &req, Response & /*res*/) {
  3219. auto values = req.get_param_values("array");
  3220. EXPECT_EQ(3u, values.size());
  3221. EXPECT_EQ("value1", values[0]);
  3222. EXPECT_EQ("value2", values[1]);
  3223. EXPECT_EQ("value3", values[2]);
  3224. auto empty = req.get_param_values("nonexistent");
  3225. EXPECT_TRUE(empty.empty());
  3226. })
  3227. .Post("/validate-no-multiple-headers",
  3228. [&](const Request &req, Response & /*res*/) {
  3229. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3230. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3231. })
  3232. .Post("/content_receiver",
  3233. [&](const Request &req, Response &res,
  3234. const ContentReader &content_reader) {
  3235. if (req.is_multipart_form_data()) {
  3236. std::vector<FormData> items;
  3237. content_reader(
  3238. [&](const FormData &file) {
  3239. items.push_back(file);
  3240. return true;
  3241. },
  3242. [&](const char *data, size_t data_length) {
  3243. items.back().content.append(data, data_length);
  3244. return true;
  3245. });
  3246. EXPECT_EQ(5u, items.size());
  3247. {
  3248. const auto &file = get_file_value(items, "text1");
  3249. EXPECT_TRUE(file.filename.empty());
  3250. EXPECT_EQ("text default", file.content);
  3251. }
  3252. {
  3253. const auto &file = get_file_value(items, "text2");
  3254. EXPECT_TRUE(file.filename.empty());
  3255. EXPECT_EQ("aωb", file.content);
  3256. }
  3257. {
  3258. const auto &file = get_file_value(items, "file1");
  3259. EXPECT_EQ("hello.txt", file.filename);
  3260. EXPECT_EQ("text/plain", file.content_type);
  3261. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3262. }
  3263. {
  3264. const auto &file = get_file_value(items, "file2");
  3265. EXPECT_EQ("world.json", file.filename);
  3266. EXPECT_EQ("application/json", file.content_type);
  3267. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3268. }
  3269. {
  3270. const auto &file = get_file_value(items, "file3");
  3271. EXPECT_TRUE(file.filename.empty());
  3272. EXPECT_EQ("application/octet-stream", file.content_type);
  3273. EXPECT_EQ(0u, file.content.size());
  3274. }
  3275. } else {
  3276. std::string body;
  3277. content_reader([&](const char *data, size_t data_length) {
  3278. EXPECT_EQ(7U, data_length);
  3279. body.append(data, data_length);
  3280. return true;
  3281. });
  3282. EXPECT_EQ(body, "content");
  3283. res.set_content(body, "text/plain");
  3284. }
  3285. })
  3286. .Put("/content_receiver",
  3287. [&](const Request & /*req*/, Response &res,
  3288. const ContentReader &content_reader) {
  3289. std::string body;
  3290. content_reader([&](const char *data, size_t data_length) {
  3291. body.append(data, data_length);
  3292. return true;
  3293. });
  3294. EXPECT_EQ(body, "content");
  3295. res.set_content(body, "text/plain");
  3296. })
  3297. .Patch("/content_receiver",
  3298. [&](const Request & /*req*/, Response &res,
  3299. const ContentReader &content_reader) {
  3300. std::string body;
  3301. content_reader([&](const char *data, size_t data_length) {
  3302. body.append(data, data_length);
  3303. return true;
  3304. });
  3305. EXPECT_EQ(body, "content");
  3306. res.set_content(body, "text/plain");
  3307. })
  3308. .Post("/query-string-and-body",
  3309. [&](const Request &req, Response & /*res*/) {
  3310. ASSERT_TRUE(req.has_param("key"));
  3311. EXPECT_EQ(req.get_param_value("key"), "value");
  3312. EXPECT_EQ(req.body, "content");
  3313. })
  3314. .Get("/last-request",
  3315. [&](const Request &req, Response & /*res*/) {
  3316. EXPECT_EQ("close", req.get_header_value("Connection"));
  3317. })
  3318. .Get(R"(/redirect/(\d+))",
  3319. [&](const Request &req, Response &res) {
  3320. auto num = std::stoi(req.matches[1]) + 1;
  3321. std::string url = "/redirect/" + std::to_string(num);
  3322. res.set_redirect(url);
  3323. })
  3324. .Post("/binary",
  3325. [&](const Request &req, Response &res) {
  3326. EXPECT_EQ(4U, req.body.size());
  3327. EXPECT_EQ("application/octet-stream",
  3328. req.get_header_value("Content-Type"));
  3329. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3330. res.set_content(req.body, "application/octet-stream");
  3331. })
  3332. .Put("/binary",
  3333. [&](const Request &req, Response &res) {
  3334. EXPECT_EQ(4U, req.body.size());
  3335. EXPECT_EQ("application/octet-stream",
  3336. req.get_header_value("Content-Type"));
  3337. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3338. res.set_content(req.body, "application/octet-stream");
  3339. })
  3340. .Patch("/binary",
  3341. [&](const Request &req, Response &res) {
  3342. EXPECT_EQ(4U, req.body.size());
  3343. EXPECT_EQ("application/octet-stream",
  3344. req.get_header_value("Content-Type"));
  3345. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3346. res.set_content(req.body, "application/octet-stream");
  3347. })
  3348. .Delete("/binary",
  3349. [&](const Request &req, Response &res) {
  3350. EXPECT_EQ(4U, req.body.size());
  3351. EXPECT_EQ("application/octet-stream",
  3352. req.get_header_value("Content-Type"));
  3353. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3354. res.set_content(req.body, "application/octet-stream");
  3355. })
  3356. .Get("/issue1772",
  3357. [&](const Request & /*req*/, Response &res) {
  3358. res.status = 401;
  3359. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3360. })
  3361. .Delete("/issue609",
  3362. [](const httplib::Request &, httplib::Response &res,
  3363. const httplib::ContentReader &) {
  3364. res.set_content("ok", "text/plain");
  3365. })
  3366. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3367. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3368. .Get("/compress",
  3369. [&](const Request & /*req*/, Response &res) {
  3370. res.set_content(
  3371. "12345678901234567890123456789012345678901234567890123456789"
  3372. "01234567890123456789012345678901234567890",
  3373. "text/plain");
  3374. })
  3375. .Get("/compress-with-charset",
  3376. [&](const Request & /*req*/, Response &res) {
  3377. res.set_content(
  3378. "12345678901234567890123456789012345678901234567890123456789"
  3379. "01234567890123456789012345678901234567890",
  3380. "application/json; charset=utf-8");
  3381. })
  3382. .Get("/nocompress",
  3383. [&](const Request & /*req*/, Response &res) {
  3384. res.set_content(
  3385. "12345678901234567890123456789012345678901234567890123456789"
  3386. "01234567890123456789012345678901234567890",
  3387. "application/octet-stream");
  3388. })
  3389. .Post("/compress-multipart",
  3390. [&](const Request &req, Response & /*res*/) {
  3391. EXPECT_EQ(2u, req.form.fields.size());
  3392. ASSERT_TRUE(!req.form.has_field("???"));
  3393. {
  3394. const auto &text = req.form.get_field("key1");
  3395. EXPECT_EQ("test", text);
  3396. }
  3397. {
  3398. const auto &text = req.form.get_field("key2");
  3399. EXPECT_EQ("--abcdefg123", text);
  3400. }
  3401. })
  3402. #endif
  3403. ;
  3404. persons_["john"] = "programmer";
  3405. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3406. svr_.wait_until_ready();
  3407. }
  3408. virtual void TearDown() {
  3409. svr_.stop();
  3410. if (!request_threads_.empty()) {
  3411. std::this_thread::sleep_for(std::chrono::seconds(1));
  3412. for (auto &t : request_threads_) {
  3413. t.join();
  3414. }
  3415. }
  3416. t_.join();
  3417. }
  3418. map<string, string> persons_;
  3419. #ifdef CPPHTTPLIB_SSL_ENABLED
  3420. SSLClient cli_;
  3421. SSLServer svr_;
  3422. #else
  3423. Client cli_;
  3424. Server svr_;
  3425. #endif
  3426. thread t_;
  3427. std::vector<thread> request_threads_;
  3428. };
  3429. TEST_F(ServerTest, GetMethod200) {
  3430. auto res = cli_.Get("/hi");
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ("HTTP/1.1", res->version);
  3433. EXPECT_EQ(StatusCode::OK_200, res->status);
  3434. EXPECT_EQ("OK", res->reason);
  3435. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3436. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3437. EXPECT_EQ("Hello World!", res->body);
  3438. }
  3439. TEST_F(ServerTest, GetEmptyFile) {
  3440. auto res = cli_.Get("/empty_file");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3444. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3445. EXPECT_EQ("", res->body);
  3446. }
  3447. TEST_F(ServerTest, GetFileContent) {
  3448. auto res = cli_.Get("/file_content");
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3452. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3453. EXPECT_EQ("test.html", res->body);
  3454. }
  3455. TEST_F(ServerTest, GetFileContentWithRange) {
  3456. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3457. ASSERT_TRUE(res);
  3458. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3459. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3460. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3461. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3462. EXPECT_EQ("est", res->body);
  3463. }
  3464. TEST_F(ServerTest, GetFileContentWithContentType) {
  3465. auto res = cli_.Get("/file_content_with_content_type");
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3469. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3470. EXPECT_EQ("file\n", res->body);
  3471. }
  3472. TEST_F(ServerTest, GetInvalidFileContent) {
  3473. auto res = cli_.Get("/invalid_file_content");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3476. }
  3477. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3478. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3479. ASSERT_TRUE(res);
  3480. EXPECT_EQ("HTTP/1.1", res->version);
  3481. EXPECT_EQ(StatusCode::OK_200, res->status);
  3482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3483. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3484. EXPECT_EQ("Hello World!", res->body);
  3485. }
  3486. TEST_F(ServerTest, GetMethod302) {
  3487. auto res = cli_.Get("/");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::Found_302, res->status);
  3490. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3491. }
  3492. TEST_F(ServerTest, GetMethod302Redirect) {
  3493. cli_.set_follow_location(true);
  3494. auto res = cli_.Get("/");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("Hello World!", res->body);
  3498. EXPECT_EQ("/hi", res->location);
  3499. }
  3500. TEST_F(ServerTest, GetMethod404) {
  3501. auto res = cli_.Get("/invalid");
  3502. ASSERT_TRUE(res);
  3503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3504. }
  3505. TEST_F(ServerTest, HeadMethod200) {
  3506. auto res = cli_.Head("/hi");
  3507. ASSERT_TRUE(res);
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3510. EXPECT_TRUE(res->body.empty());
  3511. }
  3512. TEST_F(ServerTest, HeadMethod200Static) {
  3513. auto res = cli_.Head("/mount/dir/index.html");
  3514. ASSERT_TRUE(res);
  3515. EXPECT_EQ(StatusCode::OK_200, res->status);
  3516. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3517. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3518. EXPECT_TRUE(res->body.empty());
  3519. }
  3520. TEST_F(ServerTest, HeadMethod404) {
  3521. auto res = cli_.Head("/invalid");
  3522. ASSERT_TRUE(res);
  3523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3524. EXPECT_TRUE(res->body.empty());
  3525. }
  3526. TEST_F(ServerTest, GetMethodPersonJohn) {
  3527. auto res = cli_.Get("/person/john");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3531. EXPECT_EQ("programmer", res->body);
  3532. }
  3533. TEST_F(ServerTest, PostMethod1) {
  3534. auto res = cli_.Get("/person/john1");
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3537. res = cli_.Post("/person", "name=john1&note=coder",
  3538. "application/x-www-form-urlencoded");
  3539. ASSERT_TRUE(res);
  3540. ASSERT_EQ(StatusCode::OK_200, res->status);
  3541. res = cli_.Get("/person/john1");
  3542. ASSERT_TRUE(res);
  3543. ASSERT_EQ(StatusCode::OK_200, res->status);
  3544. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3545. ASSERT_EQ("coder", res->body);
  3546. }
  3547. TEST_F(ServerTest, PostMethod2) {
  3548. auto res = cli_.Get("/person/john2");
  3549. ASSERT_TRUE(res);
  3550. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3551. Params params;
  3552. params.emplace("name", "john2");
  3553. params.emplace("note", "coder");
  3554. res = cli_.Post("/person", params);
  3555. ASSERT_TRUE(res);
  3556. ASSERT_EQ(StatusCode::OK_200, res->status);
  3557. res = cli_.Get("/person/john2");
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3561. ASSERT_EQ("coder", res->body);
  3562. }
  3563. TEST_F(ServerTest, PutMethod3) {
  3564. auto res = cli_.Get("/person/john3");
  3565. ASSERT_TRUE(res);
  3566. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3567. Params params;
  3568. params.emplace("name", "john3");
  3569. params.emplace("note", "coder");
  3570. res = cli_.Put("/person", params);
  3571. ASSERT_TRUE(res);
  3572. ASSERT_EQ(StatusCode::OK_200, res->status);
  3573. res = cli_.Get("/person/john3");
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::OK_200, res->status);
  3576. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3577. ASSERT_EQ("coder", res->body);
  3578. }
  3579. TEST_F(ServerTest, DeleteMethod1) {
  3580. auto res = cli_.Get("/person/john4");
  3581. ASSERT_TRUE(res);
  3582. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3583. Params params;
  3584. params.emplace("name", "john4");
  3585. params.emplace("note", "coder");
  3586. res = cli_.Post("/person", params);
  3587. ASSERT_TRUE(res);
  3588. ASSERT_EQ(StatusCode::OK_200, res->status);
  3589. res = cli_.Get("/person/john4");
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::OK_200, res->status);
  3592. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3593. ASSERT_EQ("coder", res->body);
  3594. Params delete_params;
  3595. delete_params.emplace("name", "john4");
  3596. res = cli_.Delete("/person", delete_params);
  3597. ASSERT_TRUE(res);
  3598. ASSERT_EQ(StatusCode::OK_200, res->status);
  3599. ASSERT_EQ("DELETED", res->body);
  3600. res = cli_.Get("/person/john4");
  3601. ASSERT_TRUE(res);
  3602. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3603. }
  3604. TEST_F(ServerTest, DeleteMethod2) {
  3605. auto res = cli_.Get("/person/john5");
  3606. ASSERT_TRUE(res);
  3607. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3608. Params params;
  3609. params.emplace("name", "john5");
  3610. params.emplace("note", "developer");
  3611. res = cli_.Post("/person", params);
  3612. ASSERT_TRUE(res);
  3613. ASSERT_EQ(StatusCode::OK_200, res->status);
  3614. res = cli_.Get("/person/john5");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::OK_200, res->status);
  3617. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3618. ASSERT_EQ("developer", res->body);
  3619. Params delete_params;
  3620. delete_params.emplace("name", "john5");
  3621. Headers headers;
  3622. headers.emplace("Custom-Header", "test-value");
  3623. res = cli_.Delete("/person", headers, delete_params);
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ("DELETED", res->body);
  3627. res = cli_.Get("/person/john5");
  3628. ASSERT_TRUE(res);
  3629. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3630. }
  3631. TEST_F(ServerTest, DeleteMethod3) {
  3632. auto res = cli_.Get("/person/john6");
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3635. Params params;
  3636. params.emplace("name", "john6");
  3637. params.emplace("note", "tester");
  3638. res = cli_.Post("/person", params);
  3639. ASSERT_TRUE(res);
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. res = cli_.Get("/person/john6");
  3642. ASSERT_TRUE(res);
  3643. ASSERT_EQ(StatusCode::OK_200, res->status);
  3644. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3645. ASSERT_EQ("tester", res->body);
  3646. Params delete_params;
  3647. delete_params.emplace("name", "john6");
  3648. Headers headers;
  3649. headers.emplace("Custom-Header", "test-value");
  3650. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3651. ASSERT_TRUE(res);
  3652. ASSERT_EQ(StatusCode::OK_200, res->status);
  3653. ASSERT_EQ("DELETED", res->body);
  3654. res = cli_.Get("/person/john6");
  3655. ASSERT_TRUE(res);
  3656. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3657. }
  3658. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3659. Params params;
  3660. params.emplace("json", JSON_DATA);
  3661. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3662. ASSERT_TRUE(res);
  3663. ASSERT_EQ(StatusCode::OK_200, res->status);
  3664. ASSERT_EQ(JSON_DATA, res->body);
  3665. }
  3666. TEST_F(ServerTest, PostEmptyContent) {
  3667. auto res = cli_.Post("/empty", "", "text/plain");
  3668. ASSERT_TRUE(res);
  3669. ASSERT_EQ(StatusCode::OK_200, res->status);
  3670. ASSERT_EQ("empty", res->body);
  3671. }
  3672. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3673. auto res = cli_.Post("/empty-no-content-type");
  3674. ASSERT_TRUE(res);
  3675. ASSERT_EQ(StatusCode::OK_200, res->status);
  3676. ASSERT_EQ("empty-no-content-type", res->body);
  3677. }
  3678. TEST_F(ServerTest, PostPathOnly) {
  3679. auto res = cli_.Post("/path-only");
  3680. ASSERT_TRUE(res);
  3681. ASSERT_EQ(StatusCode::OK_200, res->status);
  3682. ASSERT_EQ("path-only", res->body);
  3683. }
  3684. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3685. auto res = cli_.Post("/path-headers-only",
  3686. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3687. ASSERT_TRUE(res);
  3688. ASSERT_EQ(StatusCode::OK_200, res->status);
  3689. ASSERT_EQ("path-headers-only", res->body);
  3690. }
  3691. TEST_F(ServerTest, PostLarge) {
  3692. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3693. ASSERT_TRUE(res);
  3694. ASSERT_EQ(StatusCode::OK_200, res->status);
  3695. EXPECT_EQ(LARGE_DATA, res->body);
  3696. }
  3697. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3698. auto res = cli_.Put("/empty-no-content-type");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::OK_200, res->status);
  3701. ASSERT_EQ("empty-no-content-type", res->body);
  3702. }
  3703. TEST_F(ServerTest, GetMethodDir) {
  3704. auto res = cli_.Get("/dir/");
  3705. ASSERT_TRUE(res);
  3706. EXPECT_EQ(StatusCode::OK_200, res->status);
  3707. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3708. auto body = R"(<html>
  3709. <head>
  3710. </head>
  3711. <body>
  3712. <a href="/dir/test.html">Test</a>
  3713. <a href="/hi">hi</a>
  3714. </body>
  3715. </html>
  3716. )";
  3717. EXPECT_EQ(body, res->body);
  3718. }
  3719. TEST_F(ServerTest, GetMethodDirTest) {
  3720. auto res = cli_.Get("/dir/test.html");
  3721. ASSERT_TRUE(res);
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3724. EXPECT_EQ("test.html", res->body);
  3725. }
  3726. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3727. auto res = cli_.Get("/dir/../dir/test.html");
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::OK_200, res->status);
  3730. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3731. EXPECT_EQ("test.html", res->body);
  3732. }
  3733. TEST_F(ServerTest, GetMethodInvalidPath) {
  3734. auto res = cli_.Get("/dir/../test.html");
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3737. }
  3738. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3739. auto res = cli_.Get("/../www/dir/test.html");
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3742. }
  3743. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3744. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3745. ASSERT_TRUE(res);
  3746. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3747. }
  3748. TEST_F(ServerTest, GetMethodDirMountTest) {
  3749. auto res = cli_.Get("/mount/dir/test.html");
  3750. ASSERT_TRUE(res);
  3751. EXPECT_EQ(StatusCode::OK_200, res->status);
  3752. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3753. EXPECT_EQ("test.html", res->body);
  3754. }
  3755. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3756. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3760. EXPECT_EQ("test.html", res->body);
  3761. }
  3762. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3763. auto res = cli_.Get("/mount/dir/../test.html");
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3766. }
  3767. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3768. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3769. ASSERT_TRUE(res);
  3770. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3771. }
  3772. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3773. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3774. ASSERT_TRUE(res);
  3775. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3776. }
  3777. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3778. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3779. ASSERT_TRUE(res);
  3780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3781. }
  3782. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3783. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3784. ASSERT_TRUE(res);
  3785. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3786. }
  3787. TEST_F(ServerTest, PostMethod303) {
  3788. auto res = cli_.Post("/1", "body", "text/plain");
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3791. EXPECT_EQ("/2", res->get_header_value("Location"));
  3792. }
  3793. TEST_F(ServerTest, PostMethod303Redirect) {
  3794. cli_.set_follow_location(true);
  3795. auto res = cli_.Post("/1", "body", "text/plain");
  3796. ASSERT_TRUE(res);
  3797. EXPECT_EQ(StatusCode::OK_200, res->status);
  3798. EXPECT_EQ("redirected.", res->body);
  3799. EXPECT_EQ("/2", res->location);
  3800. }
  3801. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3802. auto res = cli_.Get("/dir/test.abcde");
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::OK_200, res->status);
  3805. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3806. EXPECT_EQ("abcde", res->body);
  3807. }
  3808. TEST_F(ServerTest, StaticFileRange) {
  3809. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3810. ASSERT_TRUE(res);
  3811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3812. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3813. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3814. EXPECT_EQ(true, res->has_header("Content-Range"));
  3815. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3816. EXPECT_EQ(std::string("cd"), res->body);
  3817. }
  3818. TEST_F(ServerTest, StaticFileRanges) {
  3819. auto res =
  3820. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3821. ASSERT_TRUE(res);
  3822. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3823. EXPECT_TRUE(
  3824. res->get_header_value("Content-Type")
  3825. .find(
  3826. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3827. 0);
  3828. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3829. }
  3830. TEST_F(ServerTest, StaticFileRangeHead) {
  3831. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3832. ASSERT_TRUE(res);
  3833. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3834. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3835. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3836. EXPECT_EQ(true, res->has_header("Content-Range"));
  3837. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3838. }
  3839. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3840. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3841. ASSERT_TRUE(res);
  3842. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3843. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3844. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3845. EXPECT_EQ(true, res->has_header("Content-Range"));
  3846. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3847. res->get_header_value("Content-Range"));
  3848. EXPECT_EQ("LAST\n", res->body);
  3849. }
  3850. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3851. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3855. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3856. EXPECT_EQ(true, res->has_header("Content-Range"));
  3857. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3858. }
  3859. TEST_F(ServerTest, StaticFileBigFile) {
  3860. auto res = cli_.Get("/dir/1MB.txt");
  3861. ASSERT_TRUE(res);
  3862. EXPECT_EQ(StatusCode::OK_200, res->status);
  3863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3864. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3865. }
  3866. TEST_F(ServerTest, InvalidBaseDirMount) {
  3867. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3868. }
  3869. TEST_F(ServerTest, Binary) {
  3870. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3871. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3872. "application/octet-stream");
  3873. ASSERT_TRUE(res);
  3874. ASSERT_EQ(StatusCode::OK_200, res->status);
  3875. ASSERT_EQ(4U, res->body.size());
  3876. res = cli_.Put("/binary", binary.data(), binary.size(),
  3877. "application/octet-stream");
  3878. ASSERT_TRUE(res);
  3879. ASSERT_EQ(StatusCode::OK_200, res->status);
  3880. ASSERT_EQ(4U, res->body.size());
  3881. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3882. "application/octet-stream");
  3883. ASSERT_TRUE(res);
  3884. ASSERT_EQ(StatusCode::OK_200, res->status);
  3885. ASSERT_EQ(4U, res->body.size());
  3886. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3887. "application/octet-stream");
  3888. ASSERT_TRUE(res);
  3889. ASSERT_EQ(StatusCode::OK_200, res->status);
  3890. ASSERT_EQ(4U, res->body.size());
  3891. }
  3892. TEST_F(ServerTest, BinaryString) {
  3893. auto binary = std::string("\x00\x01\x02\x03", 4);
  3894. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3895. ASSERT_TRUE(res);
  3896. ASSERT_EQ(StatusCode::OK_200, res->status);
  3897. ASSERT_EQ(4U, res->body.size());
  3898. res = cli_.Put("/binary", binary, "application/octet-stream");
  3899. ASSERT_TRUE(res);
  3900. ASSERT_EQ(StatusCode::OK_200, res->status);
  3901. ASSERT_EQ(4U, res->body.size());
  3902. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3903. ASSERT_TRUE(res);
  3904. ASSERT_EQ(StatusCode::OK_200, res->status);
  3905. ASSERT_EQ(4U, res->body.size());
  3906. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3907. ASSERT_TRUE(res);
  3908. ASSERT_EQ(StatusCode::OK_200, res->status);
  3909. ASSERT_EQ(4U, res->body.size());
  3910. }
  3911. TEST_F(ServerTest, EmptyRequest) {
  3912. auto res = cli_.Get("");
  3913. ASSERT_TRUE(!res);
  3914. EXPECT_EQ(Error::Connection, res.error());
  3915. }
  3916. TEST_F(ServerTest, LongRequest) {
  3917. std::string request;
  3918. for (size_t i = 0; i < 545; i++) {
  3919. request += "/TooLongRequest";
  3920. }
  3921. request += "OK";
  3922. auto res = cli_.Get(request.c_str());
  3923. ASSERT_TRUE(res);
  3924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3925. }
  3926. TEST_F(ServerTest, TooLongRequest) {
  3927. std::string request;
  3928. for (size_t i = 0; i < 546; i++) {
  3929. request += "/TooLongRequest";
  3930. }
  3931. request += "_NG";
  3932. auto start = std::chrono::high_resolution_clock::now();
  3933. cli_.set_keep_alive(true);
  3934. auto res = cli_.Get(request.c_str());
  3935. auto end = std::chrono::high_resolution_clock::now();
  3936. auto elapsed =
  3937. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3938. .count();
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3941. EXPECT_LE(elapsed, 1000);
  3942. EXPECT_EQ("close", res->get_header_value("Connection"));
  3943. EXPECT_FALSE(cli_.is_socket_open());
  3944. }
  3945. TEST_F(ServerTest, AlmostTooLongRequest) {
  3946. // test for #2046 - URI length check shouldn't include other content on req
  3947. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3948. // leading /, space, HTTP/1.1)
  3949. std::string request =
  3950. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3951. auto res = cli_.Get(request.c_str());
  3952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3953. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3954. }
  3955. TEST_F(ServerTest, LongHeader) {
  3956. Request req;
  3957. req.method = "GET";
  3958. req.path = "/hi";
  3959. std::string host_and_port;
  3960. host_and_port += HOST;
  3961. host_and_port += ":";
  3962. host_and_port += std::to_string(PORT);
  3963. req.headers.emplace("Host", host_and_port.c_str());
  3964. req.headers.emplace("Accept", "*/*");
  3965. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3966. req.headers.emplace(
  3967. "Header-Name",
  3968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@");
  3997. auto res = std::make_shared<Response>();
  3998. auto error = Error::Success;
  3999. auto ret = cli_.send(req, *res, error);
  4000. ASSERT_TRUE(ret);
  4001. EXPECT_EQ(StatusCode::OK_200, res->status);
  4002. }
  4003. TEST_F(ServerTest, LongQueryValue) {
  4004. auto start = std::chrono::high_resolution_clock::now();
  4005. cli_.set_keep_alive(true);
  4006. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4007. auto end = std::chrono::high_resolution_clock::now();
  4008. auto elapsed =
  4009. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4010. .count();
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4013. EXPECT_LE(elapsed, 1000);
  4014. EXPECT_EQ("close", res->get_header_value("Connection"));
  4015. EXPECT_FALSE(cli_.is_socket_open());
  4016. }
  4017. TEST_F(ServerTest, TooLongQueryValue) {
  4018. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4019. ASSERT_FALSE(res);
  4020. EXPECT_EQ(Error::Read, res.error());
  4021. }
  4022. TEST_F(ServerTest, TooLongHeader) {
  4023. Request req;
  4024. req.method = "GET";
  4025. req.path = "/hi";
  4026. std::string host_and_port;
  4027. host_and_port += HOST;
  4028. host_and_port += ":";
  4029. host_and_port += std::to_string(PORT);
  4030. req.headers.emplace("Host", host_and_port.c_str());
  4031. req.headers.emplace("Accept", "*/*");
  4032. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4033. req.headers.emplace(
  4034. "Header-Name",
  4035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4063. "@@@@@@@@@@@@@@@@@");
  4064. auto res = std::make_shared<Response>();
  4065. auto error = Error::Success;
  4066. auto ret = cli_.send(req, *res, error);
  4067. ASSERT_TRUE(ret);
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. }
  4070. TEST_F(ServerTest, HeaderCountAtLimit) {
  4071. // Test with headers just under the 100 limit
  4072. httplib::Headers headers;
  4073. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4074. // This should keep us just under the 100 header limit
  4075. for (int i = 0; i < 95; i++) {
  4076. std::string name = "X-Test-Header-" + std::to_string(i);
  4077. std::string value = "value" + std::to_string(i);
  4078. headers.emplace(name, value);
  4079. }
  4080. // This should work fine as we're under the limit
  4081. auto res = cli_.Get("/hi", headers);
  4082. EXPECT_TRUE(res);
  4083. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4084. }
  4085. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4086. // Test with many headers to exceed the 100 limit
  4087. httplib::Headers headers;
  4088. // Add 150 headers to definitely exceed the 100 limit
  4089. for (int i = 0; i < 150; i++) {
  4090. std::string name = "X-Test-Header-" + std::to_string(i);
  4091. std::string value = "value" + std::to_string(i);
  4092. headers.emplace(name, value);
  4093. }
  4094. // This should fail due to exceeding header count limit
  4095. cli_.set_keep_alive(true);
  4096. auto res = cli_.Get("/hi", headers);
  4097. // The server should respond with 400 Bad Request
  4098. ASSERT_TRUE(res);
  4099. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4100. EXPECT_EQ("close", res->get_header_value("Connection"));
  4101. EXPECT_FALSE(cli_.is_socket_open());
  4102. }
  4103. TEST_F(ServerTest, PercentEncoding) {
  4104. auto res = cli_.Get("/e%6edwith%");
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::OK_200, res->status);
  4107. }
  4108. TEST_F(ServerTest, PercentEncodingUnicode) {
  4109. auto res = cli_.Get("/e%u006edwith%");
  4110. ASSERT_TRUE(res);
  4111. EXPECT_EQ(StatusCode::OK_200, res->status);
  4112. }
  4113. TEST_F(ServerTest, InvalidPercentEncoding) {
  4114. auto res = cli_.Get("/%endwith%");
  4115. ASSERT_TRUE(res);
  4116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4117. }
  4118. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4119. auto res = cli_.Get("/%uendwith%");
  4120. ASSERT_TRUE(res);
  4121. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4122. }
  4123. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4124. auto res = cli_.Get("/hello?aaa=bbb%");
  4125. ASSERT_TRUE(res);
  4126. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4127. }
  4128. TEST_F(ServerTest, PlusSignEncoding) {
  4129. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4130. ASSERT_TRUE(res);
  4131. EXPECT_EQ(StatusCode::OK_200, res->status);
  4132. EXPECT_EQ("a +b", res->body);
  4133. }
  4134. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4135. // This test simulates a potential DoS attack using many headers
  4136. // to verify our security fix prevents memory exhaustion
  4137. httplib::Headers attack_headers;
  4138. // Attempt to add many headers like an attacker would (200 headers to far
  4139. // exceed limit)
  4140. for (int i = 0; i < 200; i++) {
  4141. std::string name = "X-Attack-Header-" + std::to_string(i);
  4142. std::string value = "attack_payload_" + std::to_string(i);
  4143. attack_headers.emplace(name, value);
  4144. }
  4145. // Try to POST with excessive headers
  4146. cli_.set_keep_alive(true);
  4147. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4148. // Should either fail or return 400 Bad Request due to security limit
  4149. if (res) {
  4150. // If we get a response, it should be 400 Bad Request
  4151. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4152. EXPECT_EQ("close", res->get_header_value("Connection"));
  4153. }
  4154. EXPECT_FALSE(cli_.is_socket_open());
  4155. }
  4156. TEST_F(ServerTest, MultipartFormData) {
  4157. UploadFormDataItems items = {
  4158. {"text1", "text default", "", ""},
  4159. {"text2", "aωb", "", ""},
  4160. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4161. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4162. {"file3", "", "", "application/octet-stream"},
  4163. {"file4", "", "", " application/json tmp-string "}};
  4164. auto res = cli_.Post("/multipart", items);
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::OK_200, res->status);
  4167. }
  4168. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4169. UploadFormDataItems items = {
  4170. {"text", "default text", "", ""},
  4171. {"multi_text1", "aaaaa", "", ""},
  4172. {"multi_text1", "bbbbb", "", ""},
  4173. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4174. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4175. "application/json"},
  4176. };
  4177. auto res = cli_.Post("/multipart/multi_file_values", items);
  4178. ASSERT_TRUE(res);
  4179. EXPECT_EQ(StatusCode::OK_200, res->status);
  4180. }
  4181. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4182. auto res = cli_.Get("/hi");
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::OK_200, res->status);
  4185. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4186. EXPECT_EQ("Hello World!", res->body);
  4187. }
  4188. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4189. Request req;
  4190. req.method = "POST";
  4191. req.path = "/chunked";
  4192. std::string host_and_port;
  4193. host_and_port += HOST;
  4194. host_and_port += ":";
  4195. host_and_port += std::to_string(PORT);
  4196. req.headers.emplace("Host", host_and_port.c_str());
  4197. req.headers.emplace("Accept", "*/*");
  4198. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4199. req.headers.emplace("Content-Type", "text/plain");
  4200. req.headers.emplace("Content-Length", "0");
  4201. req.headers.emplace(
  4202. "Transfer-Encoding",
  4203. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4204. // Client does not chunk, so make a chunked body manually.
  4205. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4206. auto res = std::make_shared<Response>();
  4207. auto error = Error::Success;
  4208. auto ret = cli_.send(req, *res, error);
  4209. ASSERT_TRUE(ret);
  4210. EXPECT_EQ(StatusCode::OK_200, res->status);
  4211. }
  4212. TEST_F(ServerTest, GetStreamed2) {
  4213. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4216. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4217. EXPECT_EQ(true, res->has_header("Content-Range"));
  4218. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4219. EXPECT_EQ(std::string("ab"), res->body);
  4220. }
  4221. TEST_F(ServerTest, GetStreamed) {
  4222. auto res = cli_.Get("/streamed");
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::OK_200, res->status);
  4225. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4226. EXPECT_EQ(std::string("aaabbb"), res->body);
  4227. }
  4228. TEST_F(ServerTest, GetStreamedWithRange1) {
  4229. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4232. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4233. EXPECT_EQ(true, res->has_header("Content-Range"));
  4234. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4235. EXPECT_EQ(std::string("def"), res->body);
  4236. }
  4237. TEST_F(ServerTest, GetStreamedWithRange2) {
  4238. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("bcdefg"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4247. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4250. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4251. EXPECT_EQ(true, res->has_header("Content-Range"));
  4252. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4253. EXPECT_EQ(std::string("efg"), res->body);
  4254. }
  4255. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4256. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4257. ASSERT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4259. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4260. EXPECT_EQ(false, res->has_header("Content-Range"));
  4261. EXPECT_EQ(0U, res->body.size());
  4262. }
  4263. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4264. auto res = cli_.Get("/streamed-with-range",
  4265. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4266. "92233720368547758079223372036854775807"}});
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4269. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4270. EXPECT_EQ(false, res->has_header("Content-Range"));
  4271. EXPECT_EQ(0U, res->body.size());
  4272. }
  4273. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4274. auto res = cli_.Get(
  4275. "/with-range",
  4276. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4277. {"Accept-Encoding", ""}});
  4278. ASSERT_TRUE(res);
  4279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4280. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4281. EXPECT_EQ(true, res->has_header("Content-Range"));
  4282. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4283. EXPECT_EQ(std::string("abcdefg"), res->body);
  4284. }
  4285. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4286. auto res = cli_.Get("/with-range", {
  4287. {"Range", "bytes=0-"},
  4288. {"Accept-Encoding", ""},
  4289. });
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4292. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4293. EXPECT_EQ(true, res->has_header("Content-Range"));
  4294. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4295. EXPECT_EQ(std::string("abcdefg"), res->body);
  4296. }
  4297. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4298. auto res =
  4299. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4300. ASSERT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4302. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4303. EXPECT_EQ(false, res->has_header("Content-Range"));
  4304. EXPECT_EQ(267U, res->body.size());
  4305. // Check that both range contents are present
  4306. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4307. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4308. // Check that Content-Range headers are present for both ranges
  4309. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4310. std::string::npos);
  4311. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4312. std::string::npos);
  4313. }
  4314. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4315. Ranges ranges;
  4316. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4317. ranges.emplace_back(0, -1);
  4318. }
  4319. auto res =
  4320. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4321. ASSERT_TRUE(res);
  4322. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4323. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4324. EXPECT_EQ(false, res->has_header("Content-Range"));
  4325. EXPECT_EQ(0U, res->body.size());
  4326. }
  4327. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4328. auto res =
  4329. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4330. ASSERT_TRUE(res);
  4331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4332. EXPECT_EQ(5U, res->body.size());
  4333. // Check that overlapping ranges are coalesced into a single range
  4334. EXPECT_EQ("bcdef", res->body);
  4335. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4336. // Should be single range, not multipart
  4337. EXPECT_TRUE(res->has_header("Content-Range"));
  4338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4339. }
  4340. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4341. auto res =
  4342. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4343. ASSERT_TRUE(res);
  4344. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4345. EXPECT_EQ(268U, res->body.size());
  4346. // Check that both range contents are present
  4347. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4348. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4349. // Check that Content-Range headers are present for both ranges
  4350. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4351. std::string::npos);
  4352. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4353. std::string::npos);
  4354. }
  4355. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4356. auto res =
  4357. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4358. ASSERT_TRUE(res);
  4359. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4360. EXPECT_EQ(269U, res->body.size());
  4361. // Check that both duplicate range contents are present
  4362. size_t first_abc = res->body.find("abc\r\n");
  4363. EXPECT_TRUE(first_abc != std::string::npos);
  4364. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4365. EXPECT_TRUE(second_abc != std::string::npos);
  4366. // Check that Content-Range headers are present for both ranges
  4367. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4368. EXPECT_TRUE(first_range != std::string::npos);
  4369. size_t second_range =
  4370. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4371. EXPECT_TRUE(second_range != std::string::npos);
  4372. }
  4373. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4374. auto res = cli_.Get("/streamed-with-range?error",
  4375. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4376. ASSERT_TRUE(res);
  4377. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4378. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4379. EXPECT_EQ(false, res->has_header("Content-Range"));
  4380. EXPECT_EQ(0U, res->body.size());
  4381. }
  4382. TEST_F(ServerTest, GetStreamedEndless) {
  4383. uint64_t offset = 0;
  4384. auto res = cli_.Get("/streamed-cancel",
  4385. [&](const char * /*data*/, uint64_t data_length) {
  4386. if (offset < 100) {
  4387. offset += data_length;
  4388. return true;
  4389. }
  4390. return false;
  4391. });
  4392. ASSERT_TRUE(!res);
  4393. EXPECT_EQ(Error::Canceled, res.error());
  4394. }
  4395. TEST_F(ServerTest, ClientStop) {
  4396. std::atomic_size_t count{4};
  4397. std::vector<std::thread> threads;
  4398. for (auto i = count.load(); i != 0; --i) {
  4399. threads.emplace_back([&]() {
  4400. auto res = cli_.Get("/streamed-cancel",
  4401. [&](const char *, uint64_t) { return true; });
  4402. --count;
  4403. ASSERT_TRUE(!res);
  4404. EXPECT_TRUE(res.error() == Error::Canceled ||
  4405. res.error() == Error::Read || res.error() == Error::Write);
  4406. });
  4407. }
  4408. std::this_thread::sleep_for(std::chrono::seconds(2));
  4409. while (count != 0) {
  4410. cli_.stop();
  4411. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4412. }
  4413. for (auto &t : threads) {
  4414. t.join();
  4415. }
  4416. }
  4417. TEST_F(ServerTest, GetWithRange1) {
  4418. auto res = cli_.Get("/with-range", {
  4419. make_range_header({{3, 5}}),
  4420. {"Accept-Encoding", ""},
  4421. });
  4422. ASSERT_TRUE(res);
  4423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4424. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4425. EXPECT_EQ(true, res->has_header("Content-Range"));
  4426. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4427. EXPECT_EQ(std::string("def"), res->body);
  4428. }
  4429. TEST_F(ServerTest, GetWithRange2) {
  4430. auto res = cli_.Get("/with-range", {
  4431. make_range_header({{1, -1}}),
  4432. {"Accept-Encoding", ""},
  4433. });
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4436. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4437. EXPECT_EQ(true, res->has_header("Content-Range"));
  4438. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4439. EXPECT_EQ(std::string("bcdefg"), res->body);
  4440. }
  4441. TEST_F(ServerTest, GetWithRange3) {
  4442. auto res = cli_.Get("/with-range", {
  4443. make_range_header({{0, 0}}),
  4444. {"Accept-Encoding", ""},
  4445. });
  4446. ASSERT_TRUE(res);
  4447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4448. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4449. EXPECT_EQ(true, res->has_header("Content-Range"));
  4450. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4451. EXPECT_EQ(std::string("a"), res->body);
  4452. }
  4453. TEST_F(ServerTest, GetWithRange4) {
  4454. auto res = cli_.Get("/with-range", {
  4455. make_range_header({{-1, 2}}),
  4456. {"Accept-Encoding", ""},
  4457. });
  4458. ASSERT_TRUE(res);
  4459. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4460. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4461. EXPECT_EQ(true, res->has_header("Content-Range"));
  4462. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4463. EXPECT_EQ(std::string("fg"), res->body);
  4464. }
  4465. TEST_F(ServerTest, GetWithRange5) {
  4466. auto res = cli_.Get("/with-range", {
  4467. make_range_header({{0, 5}}),
  4468. {"Accept-Encoding", ""},
  4469. });
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4472. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4473. EXPECT_EQ(true, res->has_header("Content-Range"));
  4474. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4475. EXPECT_EQ(std::string("abcdef"), res->body);
  4476. }
  4477. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4478. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4481. }
  4482. TEST_F(ServerTest, GetWithRangeMultipart) {
  4483. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4484. ASSERT_TRUE(res);
  4485. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4486. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4487. EXPECT_EQ(false, res->has_header("Content-Range"));
  4488. EXPECT_EQ(267U, res->body.size());
  4489. }
  4490. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4491. auto res =
  4492. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4493. ASSERT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4495. }
  4496. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4497. auto res = cli_.Get("/with-range-customized-response",
  4498. {{make_range_header({{1, 2}})}});
  4499. ASSERT_TRUE(res);
  4500. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4501. EXPECT_EQ(true, res->has_header("Content-Length"));
  4502. EXPECT_EQ(false, res->has_header("Content-Range"));
  4503. EXPECT_EQ(JSON_DATA, res->body);
  4504. }
  4505. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4506. auto res = cli_.Get("/with-range-customized-response",
  4507. {{make_range_header({{1, 2}, {4, 5}})}});
  4508. ASSERT_TRUE(res);
  4509. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4510. EXPECT_EQ(true, res->has_header("Content-Length"));
  4511. EXPECT_EQ(false, res->has_header("Content-Range"));
  4512. EXPECT_EQ(JSON_DATA, res->body);
  4513. }
  4514. TEST_F(ServerTest, Issue1772) {
  4515. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4516. ASSERT_TRUE(res);
  4517. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4518. }
  4519. TEST_F(ServerTest, Issue609) {
  4520. auto res = cli_.Delete("/issue609");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ(std::string("ok"), res->body);
  4524. }
  4525. TEST_F(ServerTest, GetStreamedChunked) {
  4526. auto res = cli_.Get("/streamed-chunked");
  4527. ASSERT_TRUE(res);
  4528. EXPECT_EQ(StatusCode::OK_200, res->status);
  4529. EXPECT_EQ(std::string("123456789"), res->body);
  4530. }
  4531. TEST_F(ServerTest, GetStreamedChunked2) {
  4532. auto res = cli_.Get("/streamed-chunked2");
  4533. ASSERT_TRUE(res);
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. EXPECT_EQ(std::string("123456789"), res->body);
  4536. }
  4537. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4538. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(StatusCode::OK_200, res->status);
  4541. EXPECT_EQ(std::string("123456789"), res->body);
  4542. EXPECT_TRUE(res->has_header("Trailer"));
  4543. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4544. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4545. // Trailers are now stored separately from headers (security fix)
  4546. EXPECT_EQ(2U, res->trailers.size());
  4547. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4548. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4549. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4550. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4551. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4552. // Verify trailers are NOT in headers (security verification)
  4553. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4554. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4555. }
  4556. TEST_F(ServerTest, LargeChunkedPost) {
  4557. Request req;
  4558. req.method = "POST";
  4559. req.path = "/large-chunked";
  4560. std::string host_and_port;
  4561. host_and_port += HOST;
  4562. host_and_port += ":";
  4563. host_and_port += std::to_string(PORT);
  4564. req.headers.emplace("Host", host_and_port.c_str());
  4565. req.headers.emplace("Accept", "*/*");
  4566. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4567. req.headers.emplace("Content-Type", "text/plain");
  4568. req.headers.emplace("Content-Length", "0");
  4569. req.headers.emplace("Transfer-Encoding", "chunked");
  4570. std::string long_string(30 * 1024u, 'a');
  4571. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4572. // Attempt to make a large enough post to exceed OS buffers, to test that
  4573. // the server handles short reads if the full chunk data isn't available.
  4574. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4575. auto res = std::make_shared<Response>();
  4576. auto error = Error::Success;
  4577. auto ret = cli_.send(req, *res, error);
  4578. ASSERT_TRUE(ret);
  4579. EXPECT_EQ(StatusCode::OK_200, res->status);
  4580. }
  4581. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4582. auto res = cli_.Get("/remote_addr");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4586. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4587. }
  4588. TEST_F(ServerTest, GetMethodLocalAddr) {
  4589. auto res = cli_.Get("/local_addr");
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4593. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4594. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4595. }
  4596. TEST_F(ServerTest, HTTPResponseSplitting) {
  4597. auto res = cli_.Get("/http_response_splitting");
  4598. ASSERT_TRUE(res);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. }
  4601. TEST_F(ServerTest, SlowRequest) {
  4602. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4603. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4604. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4605. }
  4606. #if 0
  4607. TEST_F(ServerTest, SlowPost) {
  4608. char buffer[64 * 1024];
  4609. memset(buffer, 0x42, sizeof(buffer));
  4610. auto res = cli_.Post(
  4611. "/slowpost", 64 * 1024 * 1024,
  4612. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4613. auto ret = sink.write(buffer, sizeof(buffer));
  4614. EXPECT_TRUE(ret);
  4615. return true;
  4616. },
  4617. "text/plain");
  4618. ASSERT_TRUE(res);
  4619. EXPECT_EQ(StatusCode::OK_200, res->status);
  4620. }
  4621. TEST_F(ServerTest, SlowPostFail) {
  4622. char buffer[64 * 1024];
  4623. memset(buffer, 0x42, sizeof(buffer));
  4624. cli_.set_write_timeout(std::chrono::seconds(0));
  4625. auto res = cli_.Post(
  4626. "/slowpost", 64 * 1024 * 1024,
  4627. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4628. sink.write(buffer, sizeof(buffer));
  4629. return true;
  4630. },
  4631. "text/plain");
  4632. ASSERT_TRUE(!res);
  4633. EXPECT_EQ(Error::Write, res.error());
  4634. }
  4635. #endif
  4636. TEST_F(ServerTest, Put) {
  4637. auto res = cli_.Put("/put", "PUT", "text/plain");
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::OK_200, res->status);
  4640. EXPECT_EQ("PUT", res->body);
  4641. }
  4642. TEST_F(ServerTest, PutWithContentProvider) {
  4643. auto res = cli_.Put(
  4644. "/put", 3,
  4645. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4646. sink.os << "PUT";
  4647. return true;
  4648. },
  4649. "text/plain");
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::OK_200, res->status);
  4652. EXPECT_EQ("PUT", res->body);
  4653. }
  4654. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4655. auto res = cli_.Post(
  4656. "/post", 42,
  4657. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4658. return false;
  4659. },
  4660. "text/plain");
  4661. ASSERT_TRUE(!res);
  4662. EXPECT_EQ(Error::Canceled, res.error());
  4663. }
  4664. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4665. auto res = cli_.Put(
  4666. "/put",
  4667. [](size_t /*offset*/, DataSink &sink) {
  4668. sink.os << "PUT";
  4669. sink.done();
  4670. return true;
  4671. },
  4672. "text/plain");
  4673. ASSERT_TRUE(res);
  4674. EXPECT_EQ(StatusCode::OK_200, res->status);
  4675. EXPECT_EQ("PUT", res->body);
  4676. }
  4677. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4678. auto res = cli_.Post(
  4679. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4680. "text/plain");
  4681. ASSERT_TRUE(!res);
  4682. EXPECT_EQ(Error::Canceled, res.error());
  4683. }
  4684. TEST_F(ServerTest, PostLoopBack) {
  4685. std::string body;
  4686. auto res = cli_.Post(
  4687. "/post-loopback", 9,
  4688. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4689. EXPECT_EQ(9u, length);
  4690. sink.write("123", 3);
  4691. sink.write("456", 3);
  4692. sink.write("789", 3);
  4693. return true;
  4694. },
  4695. "text/plain",
  4696. [&body](const char *data, size_t data_length) {
  4697. body.append(data, data_length);
  4698. return true;
  4699. });
  4700. ASSERT_TRUE(res);
  4701. EXPECT_EQ(StatusCode::OK_200, res->status);
  4702. EXPECT_EQ("123456789", body);
  4703. }
  4704. TEST_F(ServerTest, PutLoopBack) {
  4705. std::string body;
  4706. auto res = cli_.Put(
  4707. "/put-loopback", 9,
  4708. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4709. EXPECT_EQ(9u, length);
  4710. sink.write("123", 3);
  4711. sink.write("456", 3);
  4712. sink.write("789", 3);
  4713. return true;
  4714. },
  4715. "text/plain",
  4716. [&body](const char *data, size_t data_length) {
  4717. body.append(data, data_length);
  4718. return true;
  4719. });
  4720. ASSERT_TRUE(res);
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ("123456789", body);
  4723. }
  4724. TEST_F(ServerTest, PatchLoopBack) {
  4725. std::string body;
  4726. auto res = cli_.Patch(
  4727. "/patch-loopback", 9,
  4728. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4729. EXPECT_EQ(9u, length);
  4730. sink.write("123", 3);
  4731. sink.write("456", 3);
  4732. sink.write("789", 3);
  4733. return true;
  4734. },
  4735. "text/plain",
  4736. [&body](const char *data, size_t data_length) {
  4737. body.append(data, data_length);
  4738. return true;
  4739. });
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ(StatusCode::OK_200, res->status);
  4742. EXPECT_EQ("123456789", body);
  4743. }
  4744. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4745. std::string body;
  4746. auto res = cli_.Post(
  4747. "/post-loopback",
  4748. [](size_t /*offset*/, DataSink &sink) {
  4749. sink.write("123", 3);
  4750. sink.write("456", 3);
  4751. sink.write("789", 3);
  4752. sink.done();
  4753. return true;
  4754. },
  4755. "text/plain",
  4756. [&body](const char *data, size_t data_length) {
  4757. body.append(data, data_length);
  4758. return true;
  4759. });
  4760. ASSERT_TRUE(res);
  4761. EXPECT_EQ(StatusCode::OK_200, res->status);
  4762. EXPECT_EQ("123456789", body);
  4763. }
  4764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4765. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4766. cli_.set_compress(true);
  4767. auto res = cli_.Put(
  4768. "/put", 3,
  4769. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4770. sink.os << "PUT";
  4771. return true;
  4772. },
  4773. "text/plain");
  4774. ASSERT_TRUE(res);
  4775. EXPECT_EQ(StatusCode::OK_200, res->status);
  4776. EXPECT_EQ("PUT", res->body);
  4777. }
  4778. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4779. cli_.set_compress(true);
  4780. auto res = cli_.Post(
  4781. "/post", 42,
  4782. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4783. return false;
  4784. },
  4785. "text/plain");
  4786. ASSERT_TRUE(!res);
  4787. EXPECT_EQ(Error::Canceled, res.error());
  4788. }
  4789. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4790. cli_.set_compress(true);
  4791. auto res = cli_.Put(
  4792. "/put",
  4793. [](size_t /*offset*/, DataSink &sink) {
  4794. sink.os << "PUT";
  4795. sink.done();
  4796. return true;
  4797. },
  4798. "text/plain");
  4799. ASSERT_TRUE(res);
  4800. EXPECT_EQ(StatusCode::OK_200, res->status);
  4801. EXPECT_EQ("PUT", res->body);
  4802. }
  4803. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4804. cli_.set_compress(true);
  4805. auto res = cli_.Post(
  4806. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4807. "text/plain");
  4808. ASSERT_TRUE(!res);
  4809. EXPECT_EQ(Error::Canceled, res.error());
  4810. }
  4811. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4812. cli_.set_compress(true);
  4813. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4814. ASSERT_TRUE(res);
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. EXPECT_EQ(LARGE_DATA, res->body);
  4817. }
  4818. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4819. #ifdef CPPHTTPLIB_SSL_ENABLED
  4820. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4821. Client cli(s.c_str());
  4822. cli.enable_server_certificate_verification(false);
  4823. #else
  4824. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4825. Client cli(s.c_str());
  4826. #endif
  4827. cli.set_compress(true);
  4828. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4829. ASSERT_TRUE(res);
  4830. EXPECT_EQ(StatusCode::OK_200, res->status);
  4831. EXPECT_EQ(LARGE_DATA, res->body);
  4832. // The compressed size should be less than a 10th of the original. May vary
  4833. // depending on the zlib library.
  4834. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4835. static_cast<uint64_t>(10 * 1024 * 1024));
  4836. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4837. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4838. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4839. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4840. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4841. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4842. #endif
  4843. }
  4844. TEST_F(ServerTest, PutContentWithDeflate) {
  4845. cli_.set_compress(false);
  4846. Headers headers;
  4847. headers.emplace("Content-Encoding", "deflate");
  4848. // PUT in deflate format:
  4849. auto res = cli_.Put("/put", headers,
  4850. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4851. ASSERT_TRUE(res);
  4852. EXPECT_EQ(StatusCode::OK_200, res->status);
  4853. EXPECT_EQ("PUT", res->body);
  4854. }
  4855. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4856. Headers headers;
  4857. headers.emplace("Accept-Encoding", "gzip, deflate");
  4858. auto res = cli_.Get("/streamed-chunked", headers);
  4859. ASSERT_TRUE(res);
  4860. EXPECT_EQ(StatusCode::OK_200, res->status);
  4861. EXPECT_EQ(std::string("123456789"), res->body);
  4862. }
  4863. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4864. Headers headers;
  4865. headers.emplace("Accept-Encoding", "gzip, deflate");
  4866. auto res = cli_.Get("/streamed-chunked2", headers);
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. EXPECT_EQ(std::string("123456789"), res->body);
  4870. }
  4871. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4872. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::OK_200, res->status);
  4875. }
  4876. TEST(GzipDecompressor, ChunkedDecompression) {
  4877. std::string data;
  4878. for (size_t i = 0; i < 32 * 1024; ++i) {
  4879. data.push_back(static_cast<char>('a' + i % 26));
  4880. }
  4881. std::string compressed_data;
  4882. {
  4883. httplib::detail::gzip_compressor compressor;
  4884. bool result = compressor.compress(
  4885. data.data(), data.size(),
  4886. /*last=*/true,
  4887. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4888. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4889. compressed_data_size);
  4890. return true;
  4891. });
  4892. ASSERT_TRUE(result);
  4893. }
  4894. std::string decompressed_data;
  4895. {
  4896. httplib::detail::gzip_decompressor decompressor;
  4897. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4898. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4899. size_t chunk_size = 130;
  4900. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4901. chunk_begin += chunk_size) {
  4902. size_t current_chunk_size =
  4903. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4904. bool result = decompressor.decompress(
  4905. compressed_data.data() + chunk_begin, current_chunk_size,
  4906. [&](const char *decompressed_data_chunk,
  4907. size_t decompressed_data_chunk_size) {
  4908. decompressed_data.insert(decompressed_data.size(),
  4909. decompressed_data_chunk,
  4910. decompressed_data_chunk_size);
  4911. return true;
  4912. });
  4913. ASSERT_TRUE(result);
  4914. }
  4915. }
  4916. ASSERT_EQ(data, decompressed_data);
  4917. }
  4918. TEST(GzipDecompressor, DeflateDecompression) {
  4919. std::string original_text = "Raw deflate without gzip";
  4920. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4921. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4922. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4923. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4924. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4925. std::string decompressed_data;
  4926. {
  4927. httplib::detail::gzip_decompressor decompressor;
  4928. bool result = decompressor.decompress(
  4929. compressed_data.data(), compressed_data.size(),
  4930. [&](const char *decompressed_data_chunk,
  4931. size_t decompressed_data_chunk_size) {
  4932. decompressed_data.insert(decompressed_data.size(),
  4933. decompressed_data_chunk,
  4934. decompressed_data_chunk_size);
  4935. return true;
  4936. });
  4937. ASSERT_TRUE(result);
  4938. }
  4939. ASSERT_EQ(original_text, decompressed_data);
  4940. }
  4941. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4942. std::string original_text = "Raw deflate without gzip";
  4943. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4944. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4945. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4946. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4947. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4948. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4949. std::string decompressed_data;
  4950. {
  4951. httplib::detail::gzip_decompressor decompressor;
  4952. bool result = decompressor.decompress(
  4953. compressed_data.data(), compressed_data.size(),
  4954. [&](const char *decompressed_data_chunk,
  4955. size_t decompressed_data_chunk_size) {
  4956. decompressed_data.insert(decompressed_data.size(),
  4957. decompressed_data_chunk,
  4958. decompressed_data_chunk_size);
  4959. return true;
  4960. });
  4961. ASSERT_TRUE(result);
  4962. }
  4963. ASSERT_EQ(original_text, decompressed_data);
  4964. }
  4965. #endif
  4966. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4967. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4968. Headers headers;
  4969. headers.emplace("Accept-Encoding", "br");
  4970. auto res = cli_.Get("/streamed-chunked", headers);
  4971. ASSERT_TRUE(res);
  4972. EXPECT_EQ(StatusCode::OK_200, res->status);
  4973. EXPECT_EQ(std::string("123456789"), res->body);
  4974. }
  4975. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4976. Headers headers;
  4977. headers.emplace("Accept-Encoding", "br");
  4978. auto res = cli_.Get("/streamed-chunked2", headers);
  4979. ASSERT_TRUE(res);
  4980. EXPECT_EQ(StatusCode::OK_200, res->status);
  4981. EXPECT_EQ(std::string("123456789"), res->body);
  4982. }
  4983. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4984. cli_.set_compress(true);
  4985. auto res = cli_.Put(
  4986. "/put", 3,
  4987. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4988. sink.os << "PUT";
  4989. return true;
  4990. },
  4991. "text/plain");
  4992. ASSERT_TRUE(res);
  4993. EXPECT_EQ(StatusCode::OK_200, res->status);
  4994. EXPECT_EQ("PUT", res->body);
  4995. }
  4996. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4997. cli_.set_compress(true);
  4998. auto res = cli_.Put(
  4999. "/put",
  5000. [](size_t /*offset*/, DataSink &sink) {
  5001. sink.os << "PUT";
  5002. sink.done();
  5003. return true;
  5004. },
  5005. "text/plain");
  5006. ASSERT_TRUE(res);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. EXPECT_EQ("PUT", res->body);
  5009. }
  5010. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5011. cli_.set_compress(true);
  5012. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5013. ASSERT_TRUE(res);
  5014. EXPECT_EQ(StatusCode::OK_200, res->status);
  5015. EXPECT_EQ(LARGE_DATA, res->body);
  5016. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5017. }
  5018. #endif
  5019. TEST_F(ServerTest, Patch) {
  5020. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5021. ASSERT_TRUE(res);
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. EXPECT_EQ("PATCH", res->body);
  5024. }
  5025. TEST_F(ServerTest, Delete) {
  5026. auto res = cli_.Delete("/delete");
  5027. ASSERT_TRUE(res);
  5028. EXPECT_EQ(StatusCode::OK_200, res->status);
  5029. EXPECT_EQ("DELETE", res->body);
  5030. }
  5031. TEST_F(ServerTest, DeleteContentReceiver) {
  5032. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("content", res->body);
  5036. }
  5037. TEST_F(ServerTest, Options) {
  5038. auto res = cli_.Options("*");
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5042. EXPECT_TRUE(res->body.empty());
  5043. }
  5044. TEST_F(ServerTest, URL) {
  5045. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5046. ASSERT_TRUE(res);
  5047. EXPECT_EQ(StatusCode::OK_200, res->status);
  5048. }
  5049. TEST_F(ServerTest, ArrayParam) {
  5050. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5051. ASSERT_TRUE(res);
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. }
  5054. TEST_F(ServerTest, ArrayParamValues) {
  5055. auto res =
  5056. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5057. ASSERT_TRUE(res);
  5058. EXPECT_EQ(StatusCode::OK_200, res->status);
  5059. }
  5060. TEST_F(ServerTest, NoMultipleHeaders) {
  5061. Headers headers = {{"Content-Length", "5"}};
  5062. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5063. "text/plain");
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ(StatusCode::OK_200, res->status);
  5066. }
  5067. TEST_F(ServerTest, PostContentReceiver) {
  5068. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5069. ASSERT_TRUE(res);
  5070. ASSERT_EQ(StatusCode::OK_200, res->status);
  5071. ASSERT_EQ("content", res->body);
  5072. }
  5073. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5074. UploadFormDataItems items = {
  5075. {"text1", "text default", "", ""},
  5076. {"text2", "aωb", "", ""},
  5077. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5078. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5079. {"file3", "", "", "application/octet-stream"},
  5080. };
  5081. auto res = cli_.Post("/content_receiver", items);
  5082. ASSERT_TRUE(res);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. }
  5085. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5086. UploadFormDataItems items = {
  5087. {"text1", "text default", "", ""},
  5088. {"text2", "aωb", "", ""},
  5089. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5090. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5091. {"file3", "", "", "application/octet-stream"},
  5092. };
  5093. auto boundary = std::string("+++++");
  5094. std::string body;
  5095. for (const auto &item : items) {
  5096. body += "--" + boundary + "\r\n";
  5097. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5098. if (!item.filename.empty()) {
  5099. body += "; filename=\"" + item.filename + "\"";
  5100. }
  5101. body += "\r\n";
  5102. if (!item.content_type.empty()) {
  5103. body += "Content-Type: " + item.content_type + "\r\n";
  5104. }
  5105. body += "\r\n";
  5106. body += item.content + "\r\n";
  5107. }
  5108. body += "--" + boundary + "--\r\n";
  5109. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5110. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5111. ASSERT_TRUE(res);
  5112. EXPECT_EQ(StatusCode::OK_200, res->status);
  5113. }
  5114. TEST_F(ServerTest, PostContentReceiverGzip) {
  5115. cli_.set_compress(true);
  5116. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5117. ASSERT_TRUE(res);
  5118. ASSERT_EQ(StatusCode::OK_200, res->status);
  5119. ASSERT_EQ("content", res->body);
  5120. }
  5121. TEST_F(ServerTest, PutContentReceiver) {
  5122. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5123. ASSERT_TRUE(res);
  5124. ASSERT_EQ(StatusCode::OK_200, res->status);
  5125. ASSERT_EQ("content", res->body);
  5126. }
  5127. TEST_F(ServerTest, PatchContentReceiver) {
  5128. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5129. ASSERT_TRUE(res);
  5130. ASSERT_EQ(StatusCode::OK_200, res->status);
  5131. ASSERT_EQ("content", res->body);
  5132. }
  5133. template <typename ClientType>
  5134. void TestWithHeadersAndContentReceiver(
  5135. ClientType &cli,
  5136. std::function<Result(ClientType &, const std::string &, const Headers &,
  5137. const std::string &, const std::string &,
  5138. ContentReceiver, DownloadProgress)>
  5139. request_func) {
  5140. Headers headers;
  5141. headers.emplace("X-Custom-Header", "test-value");
  5142. std::string received_body;
  5143. auto res = request_func(
  5144. cli, "/content_receiver", headers, "content", "application/json",
  5145. [&](const char *data, size_t data_length) {
  5146. received_body.append(data, data_length);
  5147. return true;
  5148. },
  5149. nullptr);
  5150. ASSERT_TRUE(res);
  5151. EXPECT_EQ(StatusCode::OK_200, res->status);
  5152. EXPECT_EQ("content", received_body);
  5153. }
  5154. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5155. #ifdef CPPHTTPLIB_SSL_ENABLED
  5156. using ClientT = SSLClient;
  5157. #else
  5158. using ClientT = Client;
  5159. #endif
  5160. TestWithHeadersAndContentReceiver<ClientT>(
  5161. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5162. const std::string &body, const std::string &content_type,
  5163. ContentReceiver receiver, DownloadProgress progress) {
  5164. return cli.Post(path, headers, body, content_type, receiver, progress);
  5165. });
  5166. }
  5167. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5168. #ifdef CPPHTTPLIB_SSL_ENABLED
  5169. using ClientT = SSLClient;
  5170. #else
  5171. using ClientT = Client;
  5172. #endif
  5173. TestWithHeadersAndContentReceiver<ClientT>(
  5174. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5175. const std::string &body, const std::string &content_type,
  5176. ContentReceiver receiver, DownloadProgress progress) {
  5177. return cli.Put(path, headers, body, content_type, receiver, progress);
  5178. });
  5179. }
  5180. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5181. #ifdef CPPHTTPLIB_SSL_ENABLED
  5182. using ClientT = SSLClient;
  5183. #else
  5184. using ClientT = Client;
  5185. #endif
  5186. TestWithHeadersAndContentReceiver<ClientT>(
  5187. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5188. const std::string &body, const std::string &content_type,
  5189. ContentReceiver receiver, DownloadProgress progress) {
  5190. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5191. });
  5192. }
  5193. template <typename ClientType>
  5194. void TestWithHeadersAndContentReceiverWithProgress(
  5195. ClientType &cli,
  5196. std::function<Result(ClientType &, const std::string &, const Headers &,
  5197. const std::string &, const std::string &,
  5198. ContentReceiver, DownloadProgress)>
  5199. request_func) {
  5200. Headers headers;
  5201. headers.emplace("X-Test-Header", "progress-test");
  5202. std::string received_body;
  5203. auto progress_called = false;
  5204. auto res = request_func(
  5205. cli, "/content_receiver", headers, "content", "text/plain",
  5206. [&](const char *data, size_t data_length) {
  5207. received_body.append(data, data_length);
  5208. return true;
  5209. },
  5210. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5211. progress_called = true;
  5212. return true;
  5213. });
  5214. ASSERT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. EXPECT_EQ("content", received_body);
  5217. EXPECT_TRUE(progress_called);
  5218. }
  5219. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5220. #ifdef CPPHTTPLIB_SSL_ENABLED
  5221. using ClientT = SSLClient;
  5222. #else
  5223. using ClientT = Client;
  5224. #endif
  5225. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5226. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5227. const std::string &body, const std::string &content_type,
  5228. ContentReceiver receiver, DownloadProgress progress) {
  5229. return cli.Post(path, headers, body, content_type, receiver, progress);
  5230. });
  5231. }
  5232. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5233. #ifdef CPPHTTPLIB_SSL_ENABLED
  5234. using ClientT = SSLClient;
  5235. #else
  5236. using ClientT = Client;
  5237. #endif
  5238. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5239. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5240. const std::string &body, const std::string &content_type,
  5241. ContentReceiver receiver, DownloadProgress progress) {
  5242. return cli.Put(path, headers, body, content_type, receiver, progress);
  5243. });
  5244. }
  5245. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5246. #ifdef CPPHTTPLIB_SSL_ENABLED
  5247. using ClientT = SSLClient;
  5248. #else
  5249. using ClientT = Client;
  5250. #endif
  5251. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5252. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5253. const std::string &body, const std::string &content_type,
  5254. ContentReceiver receiver, DownloadProgress progress) {
  5255. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5256. });
  5257. }
  5258. template <typename ClientType>
  5259. void TestWithHeadersAndContentReceiverError(
  5260. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5261. const Headers &, const std::string &,
  5262. const std::string &, ContentReceiver)>
  5263. request_func) {
  5264. Headers headers;
  5265. headers.emplace("X-Error-Test", "true");
  5266. std::string received_body;
  5267. auto receiver_failed = false;
  5268. auto res =
  5269. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5270. [&](const char *data, size_t data_length) {
  5271. received_body.append(data, data_length);
  5272. receiver_failed = true;
  5273. return false;
  5274. });
  5275. ASSERT_FALSE(res);
  5276. EXPECT_TRUE(receiver_failed);
  5277. }
  5278. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5279. #ifdef CPPHTTPLIB_SSL_ENABLED
  5280. using ClientT = SSLClient;
  5281. #else
  5282. using ClientT = Client;
  5283. #endif
  5284. TestWithHeadersAndContentReceiverError<ClientT>(
  5285. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5286. const std::string &body, const std::string &content_type,
  5287. ContentReceiver receiver) {
  5288. return cli.Post(path, headers, body, content_type, receiver);
  5289. });
  5290. }
  5291. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5292. #ifdef CPPHTTPLIB_SSL_ENABLED
  5293. using ClientT = SSLClient;
  5294. #else
  5295. using ClientT = Client;
  5296. #endif
  5297. TestWithHeadersAndContentReceiverError<ClientT>(
  5298. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5299. const std::string &body, const std::string &content_type,
  5300. ContentReceiver receiver) {
  5301. return cli.Put(path, headers, body, content_type, receiver);
  5302. });
  5303. }
  5304. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5305. #ifdef CPPHTTPLIB_SSL_ENABLED
  5306. using ClientT = SSLClient;
  5307. #else
  5308. using ClientT = Client;
  5309. #endif
  5310. TestWithHeadersAndContentReceiverError<ClientT>(
  5311. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5312. const std::string &body, const std::string &content_type,
  5313. ContentReceiver receiver) {
  5314. return cli.Patch(path, headers, body, content_type, receiver);
  5315. });
  5316. }
  5317. TEST_F(ServerTest, PostQueryStringAndBody) {
  5318. auto res =
  5319. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5320. ASSERT_TRUE(res);
  5321. ASSERT_EQ(StatusCode::OK_200, res->status);
  5322. }
  5323. TEST_F(ServerTest, HTTP2Magic) {
  5324. Request req;
  5325. req.method = "PRI";
  5326. req.path = "*";
  5327. req.body = "SM";
  5328. auto res = std::make_shared<Response>();
  5329. auto error = Error::Success;
  5330. auto ret = cli_.send(req, *res, error);
  5331. ASSERT_TRUE(ret);
  5332. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5333. }
  5334. TEST_F(ServerTest, KeepAlive) {
  5335. auto res = cli_.Get("/hi");
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ(StatusCode::OK_200, res->status);
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("Hello World!", res->body);
  5340. res = cli_.Get("/hi");
  5341. ASSERT_TRUE(res);
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5344. EXPECT_EQ("Hello World!", res->body);
  5345. res = cli_.Get("/hi");
  5346. ASSERT_TRUE(res);
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5349. EXPECT_EQ("Hello World!", res->body);
  5350. res = cli_.Get("/not-exist");
  5351. ASSERT_TRUE(res);
  5352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5353. res = cli_.Post("/empty", "", "text/plain");
  5354. ASSERT_TRUE(res);
  5355. EXPECT_EQ(StatusCode::OK_200, res->status);
  5356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5357. EXPECT_EQ("empty", res->body);
  5358. EXPECT_EQ("close", res->get_header_value("Connection"));
  5359. res = cli_.Post(
  5360. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5361. "text/plain");
  5362. ASSERT_TRUE(res);
  5363. EXPECT_EQ(StatusCode::OK_200, res->status);
  5364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ("empty", res->body);
  5366. cli_.set_keep_alive(false);
  5367. res = cli_.Get("/last-request");
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. EXPECT_EQ("close", res->get_header_value("Connection"));
  5371. }
  5372. TEST_F(ServerTest, TooManyRedirect) {
  5373. cli_.set_follow_location(true);
  5374. auto res = cli_.Get("/redirect/0");
  5375. ASSERT_TRUE(!res);
  5376. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5377. }
  5378. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5379. Request req;
  5380. req.method = "FOOBAR";
  5381. req.path = "/hi";
  5382. cli_.set_keep_alive(true);
  5383. auto res = cli_.send(req);
  5384. ASSERT_TRUE(res);
  5385. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5386. EXPECT_EQ("close", res->get_header_value("Connection"));
  5387. EXPECT_FALSE(cli_.is_socket_open());
  5388. }
  5389. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5391. TEST_F(ServerTest, Gzip) {
  5392. Headers headers;
  5393. headers.emplace("Accept-Encoding", "gzip, deflate");
  5394. auto res = cli_.Get("/compress", headers);
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5400. "7890123456789012345678901234567890",
  5401. res->body);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5405. Headers headers;
  5406. headers.emplace("Accept-Encoding", "gzip, deflate");
  5407. auto res = cli_.Get("/compress-with-charset", headers);
  5408. ASSERT_TRUE(res);
  5409. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5410. EXPECT_EQ("application/json; charset=utf-8",
  5411. res->get_header_value("Content-Type"));
  5412. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5413. "7890123456789012345678901234567890",
  5414. res->body);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "");
  5420. auto res = cli_.Get("/compress", headers);
  5421. ASSERT_TRUE(res);
  5422. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5423. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5424. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5425. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5426. "7890123456789012345678901234567890",
  5427. res->body);
  5428. EXPECT_EQ(StatusCode::OK_200, res->status);
  5429. }
  5430. TEST_F(ServerTest, GzipWithContentReceiver) {
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "gzip, deflate");
  5433. std::string body;
  5434. auto res = cli_.Get("/compress", headers,
  5435. [&](const char *data, uint64_t data_length) {
  5436. EXPECT_EQ(100U, data_length);
  5437. body.append(data, data_length);
  5438. return true;
  5439. });
  5440. ASSERT_TRUE(res);
  5441. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5443. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5445. "7890123456789012345678901234567890",
  5446. body);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. }
  5449. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5450. Headers headers;
  5451. headers.emplace("Accept-Encoding", "gzip, deflate");
  5452. cli_.set_decompress(false);
  5453. auto res = cli_.Get("/compress", headers);
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5457. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5458. EXPECT_EQ(33U, res->body.size());
  5459. EXPECT_EQ(StatusCode::OK_200, res->status);
  5460. }
  5461. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5462. Headers headers;
  5463. headers.emplace("Accept-Encoding", "");
  5464. std::string body;
  5465. auto res = cli_.Get("/compress", headers,
  5466. [&](const char *data, uint64_t data_length) {
  5467. EXPECT_EQ(100U, data_length);
  5468. body.append(data, data_length);
  5469. return true;
  5470. });
  5471. ASSERT_TRUE(res);
  5472. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5473. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5474. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5475. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5476. "7890123456789012345678901234567890",
  5477. body);
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. }
  5480. TEST_F(ServerTest, NoGzip) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "gzip, deflate");
  5483. auto res = cli_.Get("/nocompress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5486. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5489. "7890123456789012345678901234567890",
  5490. res->body);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. }
  5493. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5494. Headers headers;
  5495. headers.emplace("Accept-Encoding", "gzip, deflate");
  5496. std::string body;
  5497. auto res = cli_.Get("/nocompress", headers,
  5498. [&](const char *data, uint64_t data_length) {
  5499. EXPECT_EQ(100U, data_length);
  5500. body.append(data, data_length);
  5501. return true;
  5502. });
  5503. ASSERT_TRUE(res);
  5504. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5505. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5506. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5507. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5508. "7890123456789012345678901234567890",
  5509. body);
  5510. EXPECT_EQ(StatusCode::OK_200, res->status);
  5511. }
  5512. TEST_F(ServerTest, MultipartFormDataGzip) {
  5513. UploadFormDataItems items = {
  5514. {"key1", "test", "", ""},
  5515. {"key2", "--abcdefg123", "", ""},
  5516. };
  5517. cli_.set_compress(true);
  5518. auto res = cli_.Post("/compress-multipart", items);
  5519. ASSERT_TRUE(res);
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. }
  5522. #endif
  5523. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5524. TEST_F(ServerTest, Brotli) {
  5525. Headers headers;
  5526. headers.emplace("Accept-Encoding", "br");
  5527. auto res = cli_.Get("/compress", headers);
  5528. ASSERT_TRUE(res);
  5529. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5531. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5532. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5533. "7890123456789012345678901234567890",
  5534. res->body);
  5535. EXPECT_EQ(StatusCode::OK_200, res->status);
  5536. }
  5537. #endif
  5538. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5539. TEST_F(ServerTest, Zstd) {
  5540. Headers headers;
  5541. headers.emplace("Accept-Encoding", "zstd");
  5542. auto res = cli_.Get("/compress", headers);
  5543. ASSERT_TRUE(res);
  5544. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5545. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5546. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5547. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5548. "7890123456789012345678901234567890",
  5549. res->body);
  5550. EXPECT_EQ(StatusCode::OK_200, res->status);
  5551. }
  5552. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5553. Headers headers;
  5554. headers.emplace("Accept-Encoding", "");
  5555. auto res = cli_.Get("/compress", headers);
  5556. ASSERT_TRUE(res);
  5557. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5558. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5559. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5560. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5561. "7890123456789012345678901234567890",
  5562. res->body);
  5563. EXPECT_EQ(StatusCode::OK_200, res->status);
  5564. }
  5565. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5566. Headers headers;
  5567. headers.emplace("Accept-Encoding", "zstd");
  5568. std::string body;
  5569. auto res = cli_.Get("/compress", headers,
  5570. [&](const char *data, uint64_t data_length) {
  5571. EXPECT_EQ(100U, data_length);
  5572. body.append(data, data_length);
  5573. return true;
  5574. });
  5575. ASSERT_TRUE(res);
  5576. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5577. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5578. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5579. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5580. "7890123456789012345678901234567890",
  5581. body);
  5582. EXPECT_EQ(StatusCode::OK_200, res->status);
  5583. }
  5584. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5585. Headers headers;
  5586. headers.emplace("Accept-Encoding", "zstd");
  5587. cli_.set_decompress(false);
  5588. auto res = cli_.Get("/compress", headers);
  5589. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5590. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5591. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5592. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5593. ASSERT_TRUE(res);
  5594. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5596. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. ASSERT_EQ(26U, res->body.size());
  5599. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5600. 0);
  5601. }
  5602. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5603. Headers headers;
  5604. headers.emplace("Accept-Encoding", "");
  5605. std::string body;
  5606. auto res = cli_.Get("/compress", headers,
  5607. [&](const char *data, uint64_t data_length) {
  5608. EXPECT_EQ(100U, data_length);
  5609. body.append(data, data_length);
  5610. return true;
  5611. });
  5612. ASSERT_TRUE(res);
  5613. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5615. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5616. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5617. "7890123456789012345678901234567890",
  5618. body);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. }
  5621. TEST_F(ServerTest, NoZstd) {
  5622. Headers headers;
  5623. headers.emplace("Accept-Encoding", "zstd");
  5624. auto res = cli_.Get("/nocompress", headers);
  5625. ASSERT_TRUE(res);
  5626. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5627. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5628. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5629. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5630. "7890123456789012345678901234567890",
  5631. res->body);
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. }
  5634. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5635. Headers headers;
  5636. headers.emplace("Accept-Encoding", "zstd");
  5637. std::string body;
  5638. auto res = cli_.Get("/nocompress", headers,
  5639. [&](const char *data, uint64_t data_length) {
  5640. EXPECT_EQ(100U, data_length);
  5641. body.append(data, data_length);
  5642. return true;
  5643. });
  5644. ASSERT_TRUE(res);
  5645. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5646. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5647. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5648. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5649. "7890123456789012345678901234567890",
  5650. body);
  5651. EXPECT_EQ(StatusCode::OK_200, res->status);
  5652. }
  5653. // TODO: How to enable zstd ??
  5654. TEST_F(ServerTest, MultipartFormDataZstd) {
  5655. UploadFormDataItems items = {
  5656. {"key1", "test", "", ""},
  5657. {"key2", "--abcdefg123", "", ""},
  5658. };
  5659. Headers headers;
  5660. headers.emplace("Accept-Encoding", "zstd");
  5661. cli_.set_compress(true);
  5662. auto res = cli_.Post("/compress-multipart", headers, items);
  5663. ASSERT_TRUE(res);
  5664. EXPECT_EQ(StatusCode::OK_200, res->status);
  5665. }
  5666. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5667. Headers headers;
  5668. headers.emplace("Accept-Encoding", "zstd");
  5669. cli_.set_compress(true);
  5670. auto res = cli_.Put(
  5671. "/put", headers, 3,
  5672. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5673. sink.os << "PUT";
  5674. return true;
  5675. },
  5676. "text/plain");
  5677. ASSERT_TRUE(res);
  5678. EXPECT_EQ(StatusCode::OK_200, res->status);
  5679. EXPECT_EQ("PUT", res->body);
  5680. }
  5681. // Pre-compression logging tests
  5682. TEST_F(ServerTest, PreCompressionLogging) {
  5683. // Test data for compression (matches the actual /compress endpoint content)
  5684. const std::string test_content =
  5685. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5686. "3456789012345678901234567890";
  5687. // Variables to capture logging data
  5688. std::string pre_compression_body;
  5689. std::string pre_compression_content_type;
  5690. std::string pre_compression_content_encoding;
  5691. std::string post_compression_body;
  5692. std::string post_compression_content_type;
  5693. std::string post_compression_content_encoding;
  5694. // Set up pre-compression logger
  5695. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5696. const Response &res) {
  5697. pre_compression_body = res.body;
  5698. pre_compression_content_type = res.get_header_value("Content-Type");
  5699. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5700. });
  5701. // Set up post-compression logger
  5702. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5703. post_compression_body = res.body;
  5704. post_compression_content_type = res.get_header_value("Content-Type");
  5705. post_compression_content_encoding =
  5706. res.get_header_value("Content-Encoding");
  5707. });
  5708. // Test with gzip compression
  5709. Headers headers;
  5710. headers.emplace("Accept-Encoding", "gzip");
  5711. auto res = cli_.Get("/compress", headers);
  5712. // Verify response was compressed
  5713. ASSERT_TRUE(res);
  5714. EXPECT_EQ(StatusCode::OK_200, res->status);
  5715. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5716. // Verify pre-compression logger captured uncompressed content
  5717. EXPECT_EQ(test_content, pre_compression_body);
  5718. EXPECT_EQ("text/plain", pre_compression_content_type);
  5719. EXPECT_TRUE(pre_compression_content_encoding
  5720. .empty()); // No encoding header before compression
  5721. // Verify post-compression logger captured compressed content
  5722. EXPECT_NE(test_content,
  5723. post_compression_body); // Should be different after compression
  5724. EXPECT_EQ("text/plain", post_compression_content_type);
  5725. EXPECT_EQ("gzip", post_compression_content_encoding);
  5726. // Verify compressed content is smaller
  5727. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5728. }
  5729. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5730. const std::string test_content =
  5731. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5732. "3456789012345678901234567890";
  5733. std::string pre_compression_body;
  5734. std::string post_compression_body;
  5735. svr_.set_pre_compression_logger(
  5736. [&](const Request & /*req*/, const Response &res) {
  5737. pre_compression_body = res.body;
  5738. });
  5739. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5740. post_compression_body = res.body;
  5741. });
  5742. Headers headers;
  5743. headers.emplace("Accept-Encoding", "br");
  5744. auto res = cli_.Get("/compress", headers);
  5745. ASSERT_TRUE(res);
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5748. // Verify pre-compression content is uncompressed
  5749. EXPECT_EQ(test_content, pre_compression_body);
  5750. // Verify post-compression content is compressed
  5751. EXPECT_NE(test_content, post_compression_body);
  5752. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5753. }
  5754. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5755. const std::string test_content =
  5756. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5757. "3456789012345678901234567890";
  5758. std::string pre_compression_body;
  5759. std::string post_compression_body;
  5760. svr_.set_pre_compression_logger(
  5761. [&](const Request & /*req*/, const Response &res) {
  5762. pre_compression_body = res.body;
  5763. });
  5764. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5765. post_compression_body = res.body;
  5766. });
  5767. // Request without compression (use /nocompress endpoint)
  5768. Headers headers;
  5769. auto res = cli_.Get("/nocompress", headers);
  5770. ASSERT_TRUE(res);
  5771. EXPECT_EQ(StatusCode::OK_200, res->status);
  5772. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5773. // Pre-compression logger should not be called when no compression is applied
  5774. EXPECT_TRUE(
  5775. pre_compression_body.empty()); // Pre-compression logger not called
  5776. EXPECT_EQ(
  5777. test_content,
  5778. post_compression_body); // Post-compression logger captures final content
  5779. }
  5780. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5781. const std::string test_content =
  5782. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5783. "3456789012345678901234567890";
  5784. std::string pre_compression_body;
  5785. bool pre_logger_called = false;
  5786. // Set only pre-compression logger
  5787. svr_.set_pre_compression_logger(
  5788. [&](const Request & /*req*/, const Response &res) {
  5789. pre_compression_body = res.body;
  5790. pre_logger_called = true;
  5791. });
  5792. Headers headers;
  5793. headers.emplace("Accept-Encoding", "gzip");
  5794. auto res = cli_.Get("/compress", headers);
  5795. ASSERT_TRUE(res);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5798. // Verify pre-compression logger was called
  5799. EXPECT_TRUE(pre_logger_called);
  5800. EXPECT_EQ(test_content, pre_compression_body);
  5801. }
  5802. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5803. {
  5804. // Test with Expect: 100-continue header - success case
  5805. // Server returns 100 Continue, client sends body, server returns 200 OK
  5806. Request req;
  5807. req.method = "POST";
  5808. req.path = "/post-large";
  5809. req.set_header("Expect", "100-continue");
  5810. req.body = LARGE_DATA;
  5811. Response res;
  5812. auto error = Error::Success;
  5813. cli_.set_keep_alive(true);
  5814. auto ret = cli_.send(req, res, error);
  5815. EXPECT_TRUE(ret);
  5816. EXPECT_EQ(StatusCode::OK_200, res.status);
  5817. EXPECT_EQ(LARGE_DATA, res.body);
  5818. }
  5819. {
  5820. // Test with Expect: 100-continue header - error case
  5821. // Client should not send the body when server returns an error
  5822. Request req;
  5823. req.method = "POST";
  5824. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5825. req.set_header("Expect", "100-continue");
  5826. req.body = LARGE_DATA;
  5827. Response res;
  5828. auto error = Error::Success;
  5829. auto start = std::chrono::high_resolution_clock::now();
  5830. cli_.set_keep_alive(true);
  5831. auto ret = cli_.send(req, res, error);
  5832. auto end = std::chrono::high_resolution_clock::now();
  5833. auto elapsed =
  5834. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5835. .count();
  5836. // With Expect: 100-continue, request completes successfully but with error
  5837. EXPECT_TRUE(ret);
  5838. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5839. EXPECT_EQ("close", res.get_header_value("Connection"));
  5840. EXPECT_FALSE(cli_.is_socket_open());
  5841. EXPECT_LE(elapsed, 200);
  5842. }
  5843. {
  5844. // Send an extra GET request to ensure error recovery without hanging
  5845. Request req;
  5846. req.method = "GET";
  5847. req.path = "/hi";
  5848. auto start = std::chrono::high_resolution_clock::now();
  5849. auto res = cli_.send(req);
  5850. auto end = std::chrono::high_resolution_clock::now();
  5851. auto elapsed =
  5852. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5853. .count();
  5854. ASSERT_TRUE(res);
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("Hello World!", res->body);
  5857. EXPECT_LE(elapsed, 500);
  5858. }
  5859. }
  5860. TEST(ZstdDecompressor, ChunkedDecompression) {
  5861. std::string data;
  5862. for (size_t i = 0; i < 32 * 1024; ++i) {
  5863. data.push_back(static_cast<char>('a' + i % 26));
  5864. }
  5865. std::string compressed_data;
  5866. {
  5867. httplib::detail::zstd_compressor compressor;
  5868. bool result = compressor.compress(
  5869. data.data(), data.size(),
  5870. /*last=*/true,
  5871. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5872. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5873. compressed_data_size);
  5874. return true;
  5875. });
  5876. ASSERT_TRUE(result);
  5877. }
  5878. std::string decompressed_data;
  5879. {
  5880. httplib::detail::zstd_decompressor decompressor;
  5881. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5882. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5883. size_t chunk_size = 130;
  5884. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5885. chunk_begin += chunk_size) {
  5886. size_t current_chunk_size =
  5887. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5888. bool result = decompressor.decompress(
  5889. compressed_data.data() + chunk_begin, current_chunk_size,
  5890. [&](const char *decompressed_data_chunk,
  5891. size_t decompressed_data_chunk_size) {
  5892. decompressed_data.insert(decompressed_data.size(),
  5893. decompressed_data_chunk,
  5894. decompressed_data_chunk_size);
  5895. return true;
  5896. });
  5897. ASSERT_TRUE(result);
  5898. }
  5899. }
  5900. ASSERT_EQ(data, decompressed_data);
  5901. }
  5902. TEST(ZstdDecompressor, Decompress) {
  5903. std::string original_text = "Compressed with ZSTD";
  5904. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5905. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5906. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5907. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5908. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5909. std::string decompressed_data;
  5910. {
  5911. httplib::detail::zstd_decompressor decompressor;
  5912. bool result = decompressor.decompress(
  5913. compressed_data.data(), compressed_data.size(),
  5914. [&](const char *decompressed_data_chunk,
  5915. size_t decompressed_data_chunk_size) {
  5916. decompressed_data.insert(decompressed_data.size(),
  5917. decompressed_data_chunk,
  5918. decompressed_data_chunk_size);
  5919. return true;
  5920. });
  5921. ASSERT_TRUE(result);
  5922. }
  5923. ASSERT_EQ(original_text, decompressed_data);
  5924. }
  5925. #endif
  5926. // Sends a raw request to a server listening at HOST:PORT.
  5927. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5928. std::string *resp = nullptr) {
  5929. auto error = Error::Success;
  5930. auto client_sock = detail::create_client_socket(
  5931. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5932. /*connection_timeout_sec=*/5, 0,
  5933. /*read_timeout_sec=*/5, 0,
  5934. /*write_timeout_sec=*/5, 0, std::string(), error);
  5935. if (client_sock == INVALID_SOCKET) { return false; }
  5936. auto ret = detail::process_client_socket(
  5937. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5938. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5939. if (req.size() !=
  5940. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5941. return false;
  5942. }
  5943. char buf[512];
  5944. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5945. while (line_reader.getline()) {
  5946. if (resp) { *resp += line_reader.ptr(); }
  5947. }
  5948. return true;
  5949. });
  5950. detail::close_socket(client_sock);
  5951. return ret;
  5952. }
  5953. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5954. Server svr;
  5955. std::string header_value;
  5956. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5957. header_value = req.get_header_value("foo");
  5958. res.set_content("ok", "text/plain");
  5959. });
  5960. thread t = thread([&] { svr.listen(HOST, PORT); });
  5961. auto se = detail::scope_exit([&] {
  5962. svr.stop();
  5963. t.join();
  5964. ASSERT_FALSE(svr.is_running());
  5965. });
  5966. svr.wait_until_ready();
  5967. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5968. // like characters are not treated the same - use vertical tab and escape.
  5969. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5970. "foo: \t \v bar \x1B\t \r\n"
  5971. "Connection: close\r\n"
  5972. "\r\n";
  5973. std::string res;
  5974. ASSERT_TRUE(send_request(5, req, &res));
  5975. EXPECT_EQ(header_value, "");
  5976. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5977. }
  5978. // Sends a raw request and verifies that there isn't a crash or exception.
  5979. static void test_raw_request(const std::string &req,
  5980. std::string *out = nullptr) {
  5981. Server svr;
  5982. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5983. res.set_content("ok", "text/plain");
  5984. });
  5985. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5986. res.set_content("ok", "text/plain");
  5987. });
  5988. svr.Get("/header_field_value_check",
  5989. [&](const Request & /*req*/, Response &res) {
  5990. res.set_content("ok", "text/plain");
  5991. });
  5992. // Server read timeout must be longer than the client read timeout for the
  5993. // bug to reproduce, probably to force the server to process a request
  5994. // without a trailing blank line.
  5995. const time_t client_read_timeout_sec = 1;
  5996. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5997. bool listen_thread_ok = false;
  5998. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5999. auto se = detail::scope_exit([&] {
  6000. svr.stop();
  6001. t.join();
  6002. ASSERT_FALSE(svr.is_running());
  6003. EXPECT_TRUE(listen_thread_ok);
  6004. });
  6005. svr.wait_until_ready();
  6006. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6007. }
  6008. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6009. // A certain header line causes an exception if the header property is parsed
  6010. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6011. test_raw_request(
  6012. "GET /hi HTTP/1.1\r\n"
  6013. " : "
  6014. " "
  6015. " ");
  6016. }
  6017. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6018. // A certain header line causes an exception if the header property *name* is
  6019. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6020. // greedy matcher and requires backtracking when there are a lot of ":"
  6021. // characters.
  6022. // This occurs with libc++ but not libstdc++.
  6023. test_raw_request(
  6024. "GET /hi HTTP/1.1\r\n"
  6025. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6026. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6027. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6028. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6029. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6030. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6031. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6032. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6033. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6034. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6035. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6036. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6037. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6038. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6039. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6040. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6041. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6042. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6043. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6044. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6045. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6046. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6047. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6048. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6049. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6050. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6051. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6052. "&&&%%%");
  6053. }
  6054. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6055. // Make sure this doesn't crash the server.
  6056. // In a previous version of the header line regex, the "\r" rendered the line
  6057. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6058. // a new position where the leading white space ended and the field value
  6059. // began.
  6060. // The crash occurs with libc++ but not libstdc++.
  6061. test_raw_request("GET /hi HTTP/1.1\r\n"
  6062. "a:" +
  6063. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6064. "\r\n"
  6065. "\r\n");
  6066. }
  6067. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6068. std::string out;
  6069. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6070. "Content-Type: text/plain\r\n"
  6071. "Transfer-Encoding: chunked\r\n"
  6072. "\r\n"
  6073. "nothex\r\n",
  6074. &out);
  6075. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6076. }
  6077. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6078. std::string out;
  6079. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6080. "Content-Type: text/plain\r\n"
  6081. "Transfer-Encoding: chunked\r\n"
  6082. "\r\n"
  6083. "3\r\n"
  6084. "xyz\r\n"
  6085. "NaN\r\n",
  6086. &out);
  6087. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6088. }
  6089. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6090. std::string out;
  6091. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6092. "Content-Type: text/plain\r\n"
  6093. "Transfer-Encoding: chunked\r\n"
  6094. "\r\n"
  6095. // Length is too large for 64 bits.
  6096. "1ffffffffffffffff\r\n"
  6097. "xyz\r\n",
  6098. &out);
  6099. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6100. }
  6101. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6102. test_raw_request("GET /hi HTTP/1.1\r\n"
  6103. "Content-Type: text/plain\r\n\r");
  6104. }
  6105. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6106. std::string out;
  6107. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6108. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6109. }
  6110. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6111. Server svr;
  6112. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6113. EXPECT_TRUE(!req.remote_addr.empty());
  6114. });
  6115. thread t = thread([&] { svr.listen(HOST, PORT); });
  6116. auto se = detail::scope_exit([&] {
  6117. svr.stop();
  6118. t.join();
  6119. ASSERT_FALSE(svr.is_running());
  6120. });
  6121. svr.wait_until_ready();
  6122. // Send an invalid request line to trigger Bad Request
  6123. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6124. std::string out;
  6125. ASSERT_TRUE(send_request(5, bad_req, &out));
  6126. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6127. }
  6128. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6129. std::string out;
  6130. std::string request(
  6131. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6132. test_raw_request(request, &out);
  6133. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6134. }
  6135. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6136. std::string out;
  6137. std::string request(
  6138. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6139. test_raw_request(request, &out);
  6140. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6141. }
  6142. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6143. std::string out;
  6144. std::string request(
  6145. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6146. test_raw_request(request, &out);
  6147. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6148. }
  6149. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6150. std::string out;
  6151. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6152. "Test: \r\n\r\n",
  6153. &out);
  6154. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6155. }
  6156. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6157. Server svr;
  6158. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6159. res.set_header("Cache-Control", "no-cache");
  6160. res.set_chunked_content_provider(
  6161. "text/event-stream", [](size_t offset, DataSink &sink) {
  6162. std::string s = "data:";
  6163. s += std::to_string(offset);
  6164. s += "\n\n";
  6165. auto ret = sink.write(s.data(), s.size());
  6166. EXPECT_TRUE(ret);
  6167. std::this_thread::sleep_for(std::chrono::seconds(1));
  6168. return true;
  6169. });
  6170. });
  6171. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6172. svr.wait_until_ready();
  6173. Client client(HOST, PORT);
  6174. const Headers headers = {{"Accept", "text/event-stream"}};
  6175. auto get_thread = std::thread([&client, &headers]() {
  6176. auto res = client.Get(
  6177. "/events", headers,
  6178. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6179. });
  6180. auto se = detail::scope_exit([&] {
  6181. svr.stop();
  6182. get_thread.join();
  6183. listen_thread.join();
  6184. ASSERT_FALSE(svr.is_running());
  6185. });
  6186. // Give GET time to get a few messages.
  6187. std::this_thread::sleep_for(std::chrono::seconds(2));
  6188. }
  6189. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6190. httplib::Server svr;
  6191. svr.Post("/hi",
  6192. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6193. res.status = StatusCode::OK_200;
  6194. });
  6195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6196. svr.wait_until_ready();
  6197. Client cli(HOST, PORT);
  6198. auto res = cli.Post("/hi", "data", "text/plain");
  6199. ASSERT_TRUE(res);
  6200. EXPECT_EQ(StatusCode::OK_200, res->status);
  6201. svr.stop();
  6202. thread.join();
  6203. ASSERT_FALSE(svr.is_running());
  6204. res = cli.Post("/hi", "data", "text/plain");
  6205. ASSERT_FALSE(res);
  6206. }
  6207. TEST(ServerStopTest, ListenFailure) {
  6208. Server svr;
  6209. auto t = thread([&]() {
  6210. auto ret = svr.listen("????", PORT);
  6211. EXPECT_FALSE(ret);
  6212. });
  6213. svr.wait_until_ready();
  6214. svr.stop();
  6215. t.join();
  6216. }
  6217. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6218. TEST(ServerStopTest, Decommision) {
  6219. Server svr;
  6220. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6221. for (int i = 0; i < 4; i++) {
  6222. auto is_even = !(i % 2);
  6223. std::thread t{[&] {
  6224. try {
  6225. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6226. if (is_even) {
  6227. throw std::runtime_error("Some thing that happens to go wrong.");
  6228. }
  6229. svr.listen(HOST, PORT);
  6230. } catch (...) { svr.decommission(); }
  6231. }};
  6232. svr.wait_until_ready();
  6233. // Server is up
  6234. {
  6235. Client cli(HOST, PORT);
  6236. auto res = cli.Get("/hi");
  6237. if (is_even) {
  6238. EXPECT_FALSE(res);
  6239. } else {
  6240. EXPECT_TRUE(res);
  6241. EXPECT_EQ("hi...", res->body);
  6242. }
  6243. }
  6244. svr.stop();
  6245. t.join();
  6246. // Server is down...
  6247. {
  6248. Client cli(HOST, PORT);
  6249. auto res = cli.Get("/hi");
  6250. EXPECT_FALSE(res);
  6251. }
  6252. }
  6253. }
  6254. #endif
  6255. // Helper function for string body upload progress tests
  6256. template <typename SetupHandler, typename ClientCall>
  6257. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6258. ClientCall &&client_call,
  6259. const string &body) {
  6260. Server svr;
  6261. setup_handler(svr);
  6262. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6263. auto se = detail::scope_exit([&] {
  6264. svr.stop();
  6265. t.join();
  6266. });
  6267. svr.wait_until_ready();
  6268. Client cli(HOST, PORT);
  6269. vector<uint64_t> progress_values;
  6270. bool progress_called = false;
  6271. auto res =
  6272. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6273. progress_values.push_back(current);
  6274. progress_called = true;
  6275. return true;
  6276. });
  6277. ASSERT_TRUE(res);
  6278. EXPECT_EQ(200, res->status);
  6279. EXPECT_TRUE(progress_called);
  6280. }
  6281. TEST(UploadProgressTest, PostStringBodyBasic) {
  6282. TestStringBodyUploadProgress(
  6283. [](Server &svr) {
  6284. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6285. res.set_content("received", "text/plain");
  6286. });
  6287. },
  6288. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6289. return cli.Post("/test", body, "text/plain", progress_callback);
  6290. },
  6291. "test data for upload progress");
  6292. }
  6293. TEST(UploadProgressTest, PutStringBodyBasic) {
  6294. TestStringBodyUploadProgress(
  6295. [](Server &svr) {
  6296. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6297. res.set_content("put received", "text/plain");
  6298. });
  6299. },
  6300. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6301. return cli.Put("/test", body, "text/plain", progress_callback);
  6302. },
  6303. "put test data for upload progress");
  6304. }
  6305. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6306. TestStringBodyUploadProgress(
  6307. [](Server &svr) {
  6308. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6309. res.set_content("patch received", "text/plain");
  6310. });
  6311. },
  6312. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6313. return cli.Patch("/test", body, "text/plain", progress_callback);
  6314. },
  6315. "patch test data for upload progress");
  6316. }
  6317. // Helper function for content provider upload progress tests
  6318. template <typename SetupHandler, typename ClientCall>
  6319. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6320. ClientCall &&client_call) {
  6321. Server svr;
  6322. setup_handler(svr);
  6323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6324. auto se = detail::scope_exit([&] {
  6325. svr.stop();
  6326. t.join();
  6327. });
  6328. svr.wait_until_ready();
  6329. Client cli(HOST, PORT);
  6330. vector<uint64_t> progress_values;
  6331. auto res =
  6332. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6333. progress_values.push_back(current);
  6334. return true;
  6335. });
  6336. ASSERT_TRUE(res);
  6337. EXPECT_EQ(200, res->status);
  6338. EXPECT_FALSE(progress_values.empty());
  6339. }
  6340. TEST(UploadProgressTest, PostContentProviderProgress) {
  6341. TestContentProviderUploadProgress(
  6342. [](Server &svr) {
  6343. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6344. res.set_content("provider received", "text/plain");
  6345. });
  6346. },
  6347. [](Client &cli, UploadProgress progress_callback) {
  6348. return cli.Post(
  6349. "/test", 10,
  6350. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6351. sink.os << "test data";
  6352. return true;
  6353. },
  6354. "text/plain", progress_callback);
  6355. });
  6356. }
  6357. // Helper function for multipart upload progress tests
  6358. template <typename SetupHandler, typename ClientCall>
  6359. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6360. ClientCall &&client_call,
  6361. const string &endpoint) {
  6362. Server svr;
  6363. setup_handler(svr);
  6364. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6365. auto se = detail::scope_exit([&] {
  6366. svr.stop();
  6367. t.join();
  6368. });
  6369. svr.wait_until_ready();
  6370. Client cli(HOST, PORT);
  6371. vector<uint64_t> progress_values;
  6372. UploadFormDataItems items = {
  6373. {"field1", "value1", "", ""},
  6374. {"field2", "longer value for progress tracking test", "", ""},
  6375. {"file1", "file content data for upload progress", "test.txt",
  6376. "text/plain"}};
  6377. auto res = client_call(cli, endpoint, items,
  6378. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6379. progress_values.push_back(current);
  6380. return true;
  6381. });
  6382. ASSERT_TRUE(res);
  6383. EXPECT_EQ(200, res->status);
  6384. EXPECT_FALSE(progress_values.empty());
  6385. }
  6386. TEST(UploadProgressTest, PostMultipartProgress) {
  6387. TestMultipartUploadProgress(
  6388. [](Server &svr) {
  6389. svr.Post("/multipart", [](const Request &req, Response &res) {
  6390. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6391. res.set_content("multipart received", "text/plain");
  6392. });
  6393. },
  6394. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6395. UploadProgress progress_callback) {
  6396. return cli.Post(endpoint, items, progress_callback);
  6397. },
  6398. "/multipart");
  6399. }
  6400. // Helper function for basic download progress tests
  6401. template <typename SetupHandler, typename ClientCall>
  6402. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6403. ClientCall &&client_call, const string &endpoint,
  6404. size_t expected_content_size) {
  6405. Server svr;
  6406. setup_handler(svr);
  6407. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6408. auto se = detail::scope_exit([&] {
  6409. svr.stop();
  6410. t.join();
  6411. });
  6412. svr.wait_until_ready();
  6413. Client cli(HOST, PORT);
  6414. vector<uint64_t> progress_values;
  6415. auto res = client_call(cli, endpoint,
  6416. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6417. progress_values.push_back(current);
  6418. return true;
  6419. });
  6420. ASSERT_TRUE(res);
  6421. EXPECT_EQ(200, res->status);
  6422. EXPECT_FALSE(progress_values.empty());
  6423. EXPECT_EQ(expected_content_size, res->body.size());
  6424. }
  6425. TEST(DownloadProgressTest, GetBasic) {
  6426. TestBasicDownloadProgress(
  6427. [](Server &svr) {
  6428. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6429. string content(1000, 'D');
  6430. res.set_content(content, "text/plain");
  6431. });
  6432. },
  6433. [](Client &cli, const string &endpoint,
  6434. DownloadProgress progress_callback) {
  6435. return cli.Get(endpoint, progress_callback);
  6436. },
  6437. "/download", 1000u);
  6438. }
  6439. // Helper function for content receiver download progress tests
  6440. template <typename SetupHandler, typename ClientCall>
  6441. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6442. ClientCall &&client_call,
  6443. const string &endpoint,
  6444. size_t expected_content_size) {
  6445. Server svr;
  6446. setup_handler(svr);
  6447. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6448. auto se = detail::scope_exit([&] {
  6449. svr.stop();
  6450. t.join();
  6451. });
  6452. svr.wait_until_ready();
  6453. Client cli(HOST, PORT);
  6454. vector<uint64_t> progress_values;
  6455. string received_body;
  6456. auto res = client_call(
  6457. cli, endpoint,
  6458. [&](const char *data, size_t data_length) -> bool {
  6459. received_body.append(data, data_length);
  6460. return true;
  6461. },
  6462. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6463. progress_values.push_back(current);
  6464. return true;
  6465. });
  6466. ASSERT_TRUE(res);
  6467. EXPECT_EQ(200, res->status);
  6468. EXPECT_FALSE(progress_values.empty());
  6469. EXPECT_EQ(expected_content_size, received_body.size());
  6470. EXPECT_TRUE(res->body.empty());
  6471. }
  6472. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6473. TestContentReceiverDownloadProgress(
  6474. [](Server &svr) {
  6475. svr.Get("/download-receiver",
  6476. [](const Request & /*req*/, Response &res) {
  6477. string content(2000, 'R');
  6478. res.set_content(content, "text/plain");
  6479. });
  6480. },
  6481. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6482. DownloadProgress progress_callback) {
  6483. return cli.Get(endpoint, content_receiver, progress_callback);
  6484. },
  6485. "/download-receiver", 2000u);
  6486. }
  6487. TEST(StreamingTest, NoContentLengthStreaming) {
  6488. Server svr;
  6489. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6490. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6491. if (offset < 6) {
  6492. sink.os << (offset < 3 ? "a" : "b");
  6493. } else {
  6494. sink.done();
  6495. }
  6496. return true;
  6497. });
  6498. });
  6499. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6500. auto listen_se = detail::scope_exit([&] {
  6501. svr.stop();
  6502. listen_thread.join();
  6503. ASSERT_FALSE(svr.is_running());
  6504. });
  6505. svr.wait_until_ready();
  6506. Client client(HOST, PORT);
  6507. auto get_thread = std::thread([&client]() {
  6508. std::string s;
  6509. auto res =
  6510. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6511. s += std::string(data, len);
  6512. return true;
  6513. });
  6514. ASSERT_TRUE(res);
  6515. EXPECT_EQ(StatusCode::OK_200, res->status);
  6516. EXPECT_EQ("aaabbb", s);
  6517. });
  6518. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6519. // Give GET time to get a few messages.
  6520. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6521. }
  6522. TEST(MountTest, Unmount) {
  6523. Server svr;
  6524. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6525. auto se = detail::scope_exit([&] {
  6526. svr.stop();
  6527. listen_thread.join();
  6528. ASSERT_FALSE(svr.is_running());
  6529. });
  6530. svr.wait_until_ready();
  6531. Client cli("localhost", PORT);
  6532. svr.set_mount_point("/mount2", "./www2");
  6533. auto res = cli.Get("/");
  6534. ASSERT_TRUE(res);
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. res = cli.Get("/mount2/dir/test.html");
  6537. ASSERT_TRUE(res);
  6538. EXPECT_EQ(StatusCode::OK_200, res->status);
  6539. svr.set_mount_point("/", "./www");
  6540. res = cli.Get("/dir/");
  6541. ASSERT_TRUE(res);
  6542. EXPECT_EQ(StatusCode::OK_200, res->status);
  6543. svr.remove_mount_point("/");
  6544. res = cli.Get("/dir/");
  6545. ASSERT_TRUE(res);
  6546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6547. svr.remove_mount_point("/mount2");
  6548. res = cli.Get("/mount2/dir/test.html");
  6549. ASSERT_TRUE(res);
  6550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6551. }
  6552. TEST(MountTest, Redicect) {
  6553. Server svr;
  6554. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6555. auto se = detail::scope_exit([&] {
  6556. svr.stop();
  6557. listen_thread.join();
  6558. ASSERT_FALSE(svr.is_running());
  6559. });
  6560. svr.set_mount_point("/", "./www");
  6561. svr.wait_until_ready();
  6562. Client cli("localhost", PORT);
  6563. auto res = cli.Get("/dir/");
  6564. ASSERT_TRUE(res);
  6565. EXPECT_EQ(StatusCode::OK_200, res->status);
  6566. res = cli.Get("/dir");
  6567. ASSERT_TRUE(res);
  6568. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6569. res = cli.Get("/file");
  6570. ASSERT_TRUE(res);
  6571. EXPECT_EQ(StatusCode::OK_200, res->status);
  6572. res = cli.Get("/file/");
  6573. ASSERT_TRUE(res);
  6574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6575. cli.set_follow_location(true);
  6576. res = cli.Get("/dir");
  6577. ASSERT_TRUE(res);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. }
  6580. TEST(MountTest, MultibytesPathName) {
  6581. Server svr;
  6582. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6583. auto se = detail::scope_exit([&] {
  6584. svr.stop();
  6585. listen_thread.join();
  6586. ASSERT_FALSE(svr.is_running());
  6587. });
  6588. svr.set_mount_point("/", "./www");
  6589. svr.wait_until_ready();
  6590. Client cli("localhost", PORT);
  6591. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6592. ASSERT_TRUE(res);
  6593. EXPECT_EQ(StatusCode::OK_200, res->status);
  6594. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6595. }
  6596. TEST(KeepAliveTest, ReadTimeout) {
  6597. Server svr;
  6598. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6599. std::this_thread::sleep_for(std::chrono::seconds(2));
  6600. res.set_content("a", "text/plain");
  6601. });
  6602. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6603. res.set_content("b", "text/plain");
  6604. });
  6605. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6606. auto se = detail::scope_exit([&] {
  6607. svr.stop();
  6608. listen_thread.join();
  6609. ASSERT_FALSE(svr.is_running());
  6610. });
  6611. svr.wait_until_ready();
  6612. Client cli("localhost", PORT);
  6613. cli.set_keep_alive(true);
  6614. cli.set_read_timeout(std::chrono::seconds(1));
  6615. auto resa = cli.Get("/a");
  6616. ASSERT_FALSE(resa);
  6617. EXPECT_EQ(Error::Read, resa.error());
  6618. auto resb = cli.Get("/b");
  6619. ASSERT_TRUE(resb);
  6620. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6621. EXPECT_EQ("b", resb->body);
  6622. }
  6623. TEST(KeepAliveTest, MaxCount) {
  6624. size_t keep_alive_max_count = 3;
  6625. Server svr;
  6626. svr.set_keep_alive_max_count(keep_alive_max_count);
  6627. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6628. res.set_content("Hello World!", "text/plain");
  6629. });
  6630. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6631. auto se = detail::scope_exit([&] {
  6632. svr.stop();
  6633. listen_thread.join();
  6634. ASSERT_FALSE(svr.is_running());
  6635. });
  6636. svr.wait_until_ready();
  6637. Client cli(HOST, PORT);
  6638. cli.set_keep_alive(true);
  6639. for (size_t i = 0; i < 5; i++) {
  6640. auto result = cli.Get("/hi");
  6641. ASSERT_TRUE(result);
  6642. EXPECT_EQ(StatusCode::OK_200, result->status);
  6643. if (i == keep_alive_max_count - 1) {
  6644. EXPECT_EQ("close", result->get_header_value("Connection"));
  6645. } else {
  6646. EXPECT_FALSE(result->has_header("Connection"));
  6647. }
  6648. }
  6649. }
  6650. TEST(KeepAliveTest, Issue1041) {
  6651. Server svr;
  6652. svr.set_keep_alive_timeout(3);
  6653. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6654. res.set_content("Hello World!", "text/plain");
  6655. });
  6656. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6657. auto se = detail::scope_exit([&] {
  6658. svr.stop();
  6659. listen_thread.join();
  6660. ASSERT_FALSE(svr.is_running());
  6661. });
  6662. svr.wait_until_ready();
  6663. Client cli(HOST, PORT);
  6664. cli.set_keep_alive(true);
  6665. auto result = cli.Get("/hi");
  6666. ASSERT_TRUE(result);
  6667. EXPECT_EQ(StatusCode::OK_200, result->status);
  6668. std::this_thread::sleep_for(std::chrono::seconds(5));
  6669. result = cli.Get("/hi");
  6670. ASSERT_TRUE(result);
  6671. EXPECT_EQ(StatusCode::OK_200, result->status);
  6672. }
  6673. TEST(KeepAliveTest, Issue1959) {
  6674. Server svr;
  6675. svr.set_keep_alive_timeout(5);
  6676. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6677. res.set_content("a", "text/plain");
  6678. });
  6679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6680. auto se = detail::scope_exit([&] {
  6681. if (!svr.is_running()) return;
  6682. svr.stop();
  6683. listen_thread.join();
  6684. ASSERT_FALSE(svr.is_running());
  6685. });
  6686. svr.wait_until_ready();
  6687. Client cli("localhost", PORT);
  6688. cli.set_keep_alive(true);
  6689. using namespace std::chrono;
  6690. auto start = steady_clock::now();
  6691. cli.Get("/a");
  6692. svr.stop();
  6693. listen_thread.join();
  6694. auto end = steady_clock::now();
  6695. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6696. EXPECT_LT(elapsed, 5000);
  6697. }
  6698. #ifdef CPPHTTPLIB_SSL_ENABLED
  6699. TEST(KeepAliveTest, SSLClientReconnection) {
  6700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6701. ASSERT_TRUE(svr.is_valid());
  6702. svr.set_keep_alive_timeout(1);
  6703. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6704. res.set_content("Hello World!", "text/plain");
  6705. });
  6706. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6707. auto se = detail::scope_exit([&] {
  6708. svr.stop();
  6709. listen_thread.join();
  6710. ASSERT_FALSE(svr.is_running());
  6711. });
  6712. svr.wait_until_ready();
  6713. SSLClient cli(HOST, PORT);
  6714. cli.enable_server_certificate_verification(false);
  6715. cli.set_keep_alive(true);
  6716. auto result = cli.Get("/hi");
  6717. ASSERT_TRUE(result);
  6718. EXPECT_EQ(StatusCode::OK_200, result->status);
  6719. result = cli.Get("/hi");
  6720. ASSERT_TRUE(result);
  6721. EXPECT_EQ(StatusCode::OK_200, result->status);
  6722. std::this_thread::sleep_for(std::chrono::seconds(2));
  6723. // Recoonect
  6724. result = cli.Get("/hi");
  6725. ASSERT_TRUE(result);
  6726. EXPECT_EQ(StatusCode::OK_200, result->status);
  6727. result = cli.Get("/hi");
  6728. ASSERT_TRUE(result);
  6729. EXPECT_EQ(StatusCode::OK_200, result->status);
  6730. }
  6731. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6733. ASSERT_TRUE(svr.is_valid());
  6734. svr.set_keep_alive_timeout(1);
  6735. std::string content = "reconnect";
  6736. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6737. res.set_content("Hello World!", "text/plain");
  6738. });
  6739. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6740. auto se = detail::scope_exit([&] {
  6741. svr.stop();
  6742. listen_thread.join();
  6743. ASSERT_FALSE(svr.is_running());
  6744. });
  6745. svr.wait_until_ready();
  6746. SSLClient cli(HOST, PORT);
  6747. cli.enable_server_certificate_verification(false);
  6748. cli.set_keep_alive(true);
  6749. auto result = cli.Post(
  6750. "/hi", content.size(),
  6751. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6752. sink.write(content.c_str(), content.size());
  6753. return true;
  6754. },
  6755. "text/plain");
  6756. ASSERT_TRUE(result);
  6757. EXPECT_EQ(200, result->status);
  6758. std::this_thread::sleep_for(std::chrono::seconds(2));
  6759. // Recoonect
  6760. result = cli.Post(
  6761. "/hi", content.size(),
  6762. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6763. sink.write(content.c_str(), content.size());
  6764. return true;
  6765. },
  6766. "text/plain");
  6767. ASSERT_TRUE(result);
  6768. EXPECT_EQ(200, result->status);
  6769. result = cli.Post(
  6770. "/hi", content.size(),
  6771. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6772. sink.write(content.c_str(), content.size());
  6773. return true;
  6774. },
  6775. "text/plain");
  6776. ASSERT_TRUE(result);
  6777. EXPECT_EQ(200, result->status);
  6778. }
  6779. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6780. using namespace httplib::tls;
  6781. {
  6782. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6783. ASSERT_TRUE(svr.is_valid());
  6784. svr.Get("/sni", [&](const Request &req, Response &res) {
  6785. std::string expected = req.sni();
  6786. EXPECT_EQ(expected, req.get_param_value("expected"));
  6787. res.set_content("ok", "text/plain");
  6788. });
  6789. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6790. auto se = detail::scope_exit([&] {
  6791. svr.stop();
  6792. listen_thread.join();
  6793. ASSERT_FALSE(svr.is_running());
  6794. });
  6795. svr.wait_until_ready();
  6796. {
  6797. SSLClient cli("localhost", PORT);
  6798. cli.enable_server_certificate_verification(false);
  6799. auto res = cli.Get("/sni?expected=localhost");
  6800. ASSERT_TRUE(res);
  6801. }
  6802. {
  6803. SSLClient cli("::1", PORT);
  6804. cli.enable_server_certificate_verification(false);
  6805. auto res = cli.Get("/sni?expected=");
  6806. // NOTE: This may fail if the server is listening on IPv4 only
  6807. // (e.g., when localhost resolves to 127.0.0.1 only)
  6808. if (res) {
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. } else {
  6811. EXPECT_EQ(Error::Connection, res.error());
  6812. }
  6813. }
  6814. }
  6815. }
  6816. #endif
  6817. TEST(ClientProblemDetectionTest, ContentProvider) {
  6818. Server svr;
  6819. size_t content_length = 1024 * 1024;
  6820. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6821. res.set_content_provider(
  6822. content_length, "text/plain",
  6823. [&](size_t offset, size_t length, DataSink &sink) {
  6824. auto out_len = std::min(length, static_cast<size_t>(1024));
  6825. std::string out(out_len, '@');
  6826. sink.write(out.data(), out_len);
  6827. return offset < 4096;
  6828. },
  6829. [](bool success) { ASSERT_FALSE(success); });
  6830. });
  6831. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6832. res.set_content_provider(
  6833. 0, "text/plain",
  6834. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6835. EXPECT_TRUE(false);
  6836. return true;
  6837. },
  6838. [](bool success) { ASSERT_FALSE(success); });
  6839. });
  6840. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6841. auto se = detail::scope_exit([&] {
  6842. svr.stop();
  6843. listen_thread.join();
  6844. ASSERT_FALSE(svr.is_running());
  6845. });
  6846. svr.wait_until_ready();
  6847. Client cli("localhost", PORT);
  6848. {
  6849. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6850. size_t /*data_length*/) { return false; });
  6851. ASSERT_FALSE(res);
  6852. }
  6853. {
  6854. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6855. size_t /*data_length*/) { return false; });
  6856. ASSERT_TRUE(res);
  6857. }
  6858. }
  6859. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6860. Server svr;
  6861. svr.set_error_handler([](Request const &, Response &res) -> void {
  6862. res.set_chunked_content_provider(
  6863. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6864. sink.os << "hello";
  6865. sink.os << "world";
  6866. sink.done();
  6867. return true;
  6868. });
  6869. });
  6870. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6871. auto se = detail::scope_exit([&] {
  6872. svr.stop();
  6873. listen_thread.join();
  6874. ASSERT_FALSE(svr.is_running());
  6875. });
  6876. svr.wait_until_ready();
  6877. Client cli("localhost", PORT);
  6878. auto res = cli.Get("/");
  6879. ASSERT_TRUE(res);
  6880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6881. EXPECT_EQ("helloworld", res->body);
  6882. }
  6883. TEST(LongPollingTest, ClientCloseDetection) {
  6884. Server svr;
  6885. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6886. res.set_chunked_content_provider(
  6887. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6888. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6889. sink.os << "hello";
  6890. auto count = 10;
  6891. while (count > 0 && sink.is_writable()) {
  6892. this_thread::sleep_for(chrono::milliseconds(10));
  6893. count--;
  6894. }
  6895. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6896. return true;
  6897. });
  6898. });
  6899. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6900. auto se = detail::scope_exit([&] {
  6901. svr.stop();
  6902. listen_thread.join();
  6903. ASSERT_FALSE(svr.is_running());
  6904. });
  6905. svr.wait_until_ready();
  6906. Client cli("localhost", PORT);
  6907. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6908. EXPECT_EQ("hello", string(data, data_length));
  6909. return false; // close the socket immediately.
  6910. });
  6911. ASSERT_FALSE(res);
  6912. }
  6913. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6914. Server svr;
  6915. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6916. res.set_chunked_content_provider(
  6917. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6918. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6919. sink.os << "hello";
  6920. EXPECT_TRUE(sink.os.good());
  6921. // Wait for the client to close the connection
  6922. auto count = 10;
  6923. while (count > 0 && sink.is_writable()) {
  6924. this_thread::sleep_for(chrono::milliseconds(10));
  6925. count--;
  6926. }
  6927. // After client disconnect, write repeatedly until the socket
  6928. // write actually fails (small writes may be absorbed by the
  6929. // kernel buffer)
  6930. std::string chunk(1024, 'x');
  6931. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6932. sink.os << chunk;
  6933. }
  6934. EXPECT_TRUE(sink.os.fail());
  6935. return true;
  6936. });
  6937. });
  6938. auto port = svr.bind_to_any_port("localhost");
  6939. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6940. auto se = detail::scope_exit([&] {
  6941. svr.stop();
  6942. listen_thread.join();
  6943. ASSERT_FALSE(svr.is_running());
  6944. });
  6945. svr.wait_until_ready();
  6946. Client cli("localhost", port);
  6947. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6948. EXPECT_EQ("hello", string(data, data_length));
  6949. return false; // close the socket immediately.
  6950. });
  6951. ASSERT_FALSE(res);
  6952. }
  6953. TEST(GetWithParametersTest, GetWithParameters) {
  6954. Server svr;
  6955. svr.Get("/", [&](const Request &req, Response &) {
  6956. EXPECT_EQ("world", req.get_param_value("hello"));
  6957. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6958. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6959. });
  6960. svr.Get("/params", [&](const Request &req, Response &) {
  6961. EXPECT_EQ("world", req.get_param_value("hello"));
  6962. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6963. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6964. });
  6965. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6966. EXPECT_EQ("resource-id", req.matches[1]);
  6967. EXPECT_EQ("foo", req.get_param_value("param1"));
  6968. EXPECT_EQ("bar", req.get_param_value("param2"));
  6969. });
  6970. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6971. EXPECT_EQ("user-id", req.path_params.at("id"));
  6972. EXPECT_EQ("foo", req.get_param_value("param1"));
  6973. EXPECT_EQ("bar", req.get_param_value("param2"));
  6974. });
  6975. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6976. auto se = detail::scope_exit([&] {
  6977. svr.stop();
  6978. listen_thread.join();
  6979. ASSERT_FALSE(svr.is_running());
  6980. });
  6981. svr.wait_until_ready();
  6982. {
  6983. Client cli(HOST, PORT);
  6984. Params params;
  6985. params.emplace("hello", "world");
  6986. params.emplace("hello2", "world2");
  6987. params.emplace("hello3", "world3");
  6988. auto res = cli.Get("/", params, Headers{});
  6989. ASSERT_TRUE(res);
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. }
  6992. {
  6993. Client cli(HOST, PORT);
  6994. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6995. ASSERT_TRUE(res);
  6996. EXPECT_EQ(StatusCode::OK_200, res->status);
  6997. }
  6998. {
  6999. Client cli(HOST, PORT);
  7000. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7001. ASSERT_TRUE(res);
  7002. EXPECT_EQ(StatusCode::OK_200, res->status);
  7003. }
  7004. {
  7005. Client cli(HOST, PORT);
  7006. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7007. ASSERT_TRUE(res);
  7008. EXPECT_EQ(StatusCode::OK_200, res->status);
  7009. }
  7010. }
  7011. TEST(GetWithParametersTest, GetWithParameters2) {
  7012. Server svr;
  7013. svr.Get("/", [&](const Request &req, Response &res) {
  7014. auto text = req.get_param_value("hello");
  7015. res.set_content(text, "text/plain");
  7016. });
  7017. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7018. auto se = detail::scope_exit([&] {
  7019. svr.stop();
  7020. listen_thread.join();
  7021. ASSERT_FALSE(svr.is_running());
  7022. });
  7023. svr.wait_until_ready();
  7024. Client cli("localhost", PORT);
  7025. Params params;
  7026. params.emplace("hello", "world");
  7027. std::string body;
  7028. auto res = cli.Get("/", params, Headers{},
  7029. [&](const char *data, size_t data_length) {
  7030. body.append(data, data_length);
  7031. return true;
  7032. });
  7033. ASSERT_TRUE(res);
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. EXPECT_EQ("world", body);
  7036. }
  7037. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7038. auto host = "httpbingo.org";
  7039. auto path = std::string{"/range/32"};
  7040. #ifdef CPPHTTPLIB_SSL_ENABLED
  7041. SSLClient cli(host);
  7042. #else
  7043. Client cli(host);
  7044. #endif
  7045. cli.set_default_headers({make_range_header({{1, 10}})});
  7046. cli.set_connection_timeout(5);
  7047. {
  7048. auto res = cli.Get(path);
  7049. ASSERT_TRUE(res);
  7050. EXPECT_EQ("bcdefghijk", res->body);
  7051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7052. }
  7053. {
  7054. auto res = cli.Get(path);
  7055. ASSERT_TRUE(res);
  7056. EXPECT_EQ("bcdefghijk", res->body);
  7057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7058. }
  7059. }
  7060. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7061. Server svr;
  7062. svr.set_default_headers({{"Hello", "World"}});
  7063. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7064. res.set_content("ok", "text/plain");
  7065. });
  7066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7067. auto se = detail::scope_exit([&] {
  7068. svr.stop();
  7069. listen_thread.join();
  7070. ASSERT_FALSE(svr.is_running());
  7071. });
  7072. svr.wait_until_ready();
  7073. Client cli("localhost", PORT);
  7074. auto res = cli.Get("/");
  7075. ASSERT_TRUE(res);
  7076. EXPECT_EQ(StatusCode::OK_200, res->status);
  7077. EXPECT_EQ("ok", res->body);
  7078. EXPECT_EQ("World", res->get_header_value("Hello"));
  7079. }
  7080. #ifdef CPPHTTPLIB_SSL_ENABLED
  7081. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7083. ASSERT_TRUE(svr.is_valid());
  7084. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7085. std::this_thread::sleep_for(std::chrono::seconds(2));
  7086. res.set_content("a", "text/plain");
  7087. });
  7088. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7089. res.set_content("b", "text/plain");
  7090. });
  7091. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7092. auto se = detail::scope_exit([&] {
  7093. svr.stop();
  7094. listen_thread.join();
  7095. ASSERT_FALSE(svr.is_running());
  7096. });
  7097. svr.wait_until_ready();
  7098. SSLClient cli("localhost", PORT);
  7099. cli.enable_server_certificate_verification(false);
  7100. cli.set_keep_alive(true);
  7101. cli.set_read_timeout(std::chrono::seconds(1));
  7102. auto resa = cli.Get("/a");
  7103. ASSERT_TRUE(!resa);
  7104. EXPECT_EQ(Error::Read, resa.error());
  7105. auto resb = cli.Get("/b");
  7106. ASSERT_TRUE(resb);
  7107. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7108. EXPECT_EQ("b", resb->body);
  7109. }
  7110. #endif
  7111. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7112. protected:
  7113. ServerTestWithAI_PASSIVE()
  7114. : cli_(HOST, PORT)
  7115. #ifdef CPPHTTPLIB_SSL_ENABLED
  7116. ,
  7117. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7118. #endif
  7119. {
  7120. #ifdef CPPHTTPLIB_SSL_ENABLED
  7121. cli_.enable_server_certificate_verification(false);
  7122. #endif
  7123. }
  7124. virtual void SetUp() {
  7125. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7126. res.set_content("Hello World!", "text/plain");
  7127. });
  7128. t_ = thread(
  7129. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7130. svr_.wait_until_ready();
  7131. }
  7132. virtual void TearDown() {
  7133. svr_.stop();
  7134. t_.join();
  7135. }
  7136. #ifdef CPPHTTPLIB_SSL_ENABLED
  7137. SSLClient cli_;
  7138. SSLServer svr_;
  7139. #else
  7140. Client cli_;
  7141. Server svr_;
  7142. #endif
  7143. thread t_;
  7144. };
  7145. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7146. auto res = cli_.Get("/hi");
  7147. ASSERT_TRUE(res);
  7148. EXPECT_EQ(StatusCode::OK_200, res->status);
  7149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7150. EXPECT_EQ("Hello World!", res->body);
  7151. }
  7152. class ServerUpDownTest : public ::testing::Test {
  7153. protected:
  7154. ServerUpDownTest() : cli_(HOST, PORT) {}
  7155. virtual void SetUp() {
  7156. t_ = thread([&]() {
  7157. svr_.bind_to_any_port(HOST);
  7158. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7159. ASSERT_TRUE(svr_.listen_after_bind());
  7160. });
  7161. svr_.wait_until_ready();
  7162. }
  7163. virtual void TearDown() {
  7164. svr_.stop();
  7165. t_.join();
  7166. }
  7167. Client cli_;
  7168. Server svr_;
  7169. thread t_;
  7170. };
  7171. TEST_F(ServerUpDownTest, QuickStartStop) {
  7172. // Should not crash, especially when run with
  7173. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7174. }
  7175. class PayloadMaxLengthTest : public ::testing::Test {
  7176. protected:
  7177. PayloadMaxLengthTest()
  7178. : cli_(HOST, PORT)
  7179. #ifdef CPPHTTPLIB_SSL_ENABLED
  7180. ,
  7181. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7182. #endif
  7183. {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. cli_.enable_server_certificate_verification(false);
  7186. #endif
  7187. }
  7188. virtual void SetUp() {
  7189. svr_.set_payload_max_length(8);
  7190. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7191. res.set_content("test", "text/plain");
  7192. });
  7193. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7194. svr_.wait_until_ready();
  7195. }
  7196. virtual void TearDown() {
  7197. svr_.stop();
  7198. t_.join();
  7199. }
  7200. #ifdef CPPHTTPLIB_SSL_ENABLED
  7201. SSLClient cli_;
  7202. SSLServer svr_;
  7203. #else
  7204. Client cli_;
  7205. Server svr_;
  7206. #endif
  7207. thread t_;
  7208. };
  7209. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7210. auto res = cli_.Post("/test", "123456789", "text/plain");
  7211. ASSERT_TRUE(res);
  7212. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7213. res = cli_.Post("/test", "12345678", "text/plain");
  7214. ASSERT_TRUE(res);
  7215. EXPECT_EQ(StatusCode::OK_200, res->status);
  7216. }
  7217. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7218. // Test chunked encoding with payload exceeding the 8-byte limit
  7219. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7220. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7221. ASSERT_TRUE(res);
  7222. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7223. }
  7224. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7225. // Test chunked encoding with payload within the 8-byte limit
  7226. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7227. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7228. ASSERT_TRUE(res);
  7229. EXPECT_EQ(StatusCode::OK_200, res->status);
  7230. }
  7231. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7232. // Test using send_request to send chunked data exceeding payload limit
  7233. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7234. "Host: " +
  7235. std::string(HOST) + ":" + std::to_string(PORT) +
  7236. "\r\n"
  7237. "Transfer-Encoding: chunked\r\n"
  7238. "Connection: close\r\n"
  7239. "\r\n"
  7240. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7241. "0123456789\r\n"
  7242. "0\r\n" // End chunk
  7243. "\r\n";
  7244. std::string response;
  7245. bool result = send_request(1, chunked_request, &response);
  7246. if (!result) {
  7247. // If send_request fails, it might be because the server closed the
  7248. // connection due to payload limit enforcement, which is acceptable
  7249. SUCCEED()
  7250. << "Server rejected oversized chunked request (connection closed)";
  7251. } else {
  7252. // If we got a response, check if it's an error response or connection was
  7253. // closed early Short response length indicates connection was closed due to
  7254. // payload limit
  7255. if (response.length() <= 10) {
  7256. SUCCEED() << "Server closed connection for oversized chunked request";
  7257. } else {
  7258. // Check for error status codes
  7259. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7260. response.find("Payload Too Large") != std::string::npos ||
  7261. response.find("400") != std::string::npos);
  7262. }
  7263. }
  7264. }
  7265. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7266. // Test request without Content-Length header exceeding payload limit
  7267. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7268. "Host: " +
  7269. std::string(HOST) + ":" +
  7270. std::to_string(PORT) +
  7271. "\r\n"
  7272. "Connection: close\r\n"
  7273. "\r\n";
  7274. // Add payload exceeding the 8-byte limit
  7275. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7276. request_without_content_length += large_payload;
  7277. std::string response;
  7278. bool result = send_request(1, request_without_content_length, &response);
  7279. if (!result) {
  7280. // If send_request fails, server likely closed connection due to payload
  7281. // limit
  7282. SUCCEED() << "Server rejected oversized request without Content-Length "
  7283. "(connection closed)";
  7284. } else {
  7285. // Check if server responded with error or closed connection early
  7286. if (response.length() <= 10) {
  7287. SUCCEED() << "Server closed connection for oversized request without "
  7288. "Content-Length";
  7289. } else {
  7290. // Check for error status codes
  7291. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7292. response.find("Payload Too Large") != std::string::npos ||
  7293. response.find("400") != std::string::npos);
  7294. }
  7295. }
  7296. }
  7297. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7298. // Test request without Content-Length header within payload limit
  7299. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7300. "Host: " +
  7301. std::string(HOST) + ":" +
  7302. std::to_string(PORT) +
  7303. "\r\n"
  7304. "Connection: close\r\n"
  7305. "\r\n";
  7306. // Add payload within the 8-byte limit
  7307. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7308. request_without_content_length += small_payload;
  7309. std::string response;
  7310. bool result = send_request(1, request_without_content_length, &response);
  7311. // For requests without Content-Length, the server may have different behavior
  7312. // The key is that it should not reject due to payload limit for small
  7313. // payloads
  7314. if (result) {
  7315. // Check for any HTTP response (success or error, but not connection closed)
  7316. if (response.length() > 10) {
  7317. SUCCEED()
  7318. << "Server processed request without Content-Length within limit";
  7319. } else {
  7320. // Short response might indicate connection closed, which is acceptable
  7321. SUCCEED() << "Server closed connection for request without "
  7322. "Content-Length (acceptable behavior)";
  7323. }
  7324. } else {
  7325. // Connection failure might be due to protocol requirements
  7326. SUCCEED() << "Connection issue with request without Content-Length "
  7327. "(environment-specific)";
  7328. }
  7329. }
  7330. class LargePayloadMaxLengthTest : public ::testing::Test {
  7331. protected:
  7332. LargePayloadMaxLengthTest()
  7333. : cli_(HOST, PORT)
  7334. #ifdef CPPHTTPLIB_SSL_ENABLED
  7335. ,
  7336. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7337. #endif
  7338. {
  7339. #ifdef CPPHTTPLIB_SSL_ENABLED
  7340. cli_.enable_server_certificate_verification(false);
  7341. #endif
  7342. }
  7343. virtual void SetUp() {
  7344. // Set 10MB payload limit
  7345. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7346. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7347. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7348. res.set_content("Large payload test", "text/plain");
  7349. });
  7350. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7351. svr_.wait_until_ready();
  7352. }
  7353. virtual void TearDown() {
  7354. svr_.stop();
  7355. t_.join();
  7356. }
  7357. #ifdef CPPHTTPLIB_SSL_ENABLED
  7358. SSLClient cli_;
  7359. SSLServer svr_;
  7360. #else
  7361. Client cli_;
  7362. Server svr_;
  7363. #endif
  7364. thread t_;
  7365. };
  7366. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7367. // Test chunked encoding with payload within 10MB limit
  7368. std::string medium_payload(5 * 1024 * 1024,
  7369. 'A'); // 5MB payload, within 10MB limit
  7370. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7371. ASSERT_TRUE(res);
  7372. EXPECT_EQ(StatusCode::OK_200, res->status);
  7373. }
  7374. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7375. // Test chunked encoding with payload exceeding 10MB limit
  7376. std::string large_payload(12 * 1024 * 1024,
  7377. 'B'); // 12MB payload, exceeds 10MB limit
  7378. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7379. // Server may either return 413 or close the connection
  7380. if (res) {
  7381. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7382. } else {
  7383. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7384. }
  7385. }
  7386. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7387. // Test request without Content-Length header within 10MB limit
  7388. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7389. "Host: " +
  7390. std::string(HOST) + ":" +
  7391. std::to_string(PORT) +
  7392. "\r\n"
  7393. "Connection: close\r\n"
  7394. "\r\n";
  7395. // Add 1MB payload (within 10MB limit)
  7396. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7397. request_without_content_length += medium_payload;
  7398. std::string response;
  7399. bool result = send_request(5, request_without_content_length, &response);
  7400. if (result) {
  7401. // Should get a proper HTTP response for payloads within limit
  7402. if (response.length() > 10) {
  7403. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7404. "10MB limit";
  7405. } else {
  7406. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7407. "Content-Length)";
  7408. }
  7409. } else {
  7410. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7411. }
  7412. }
  7413. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7414. // Test request without Content-Length header exceeding 10MB limit
  7415. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7416. "Host: " +
  7417. std::string(HOST) + ":" +
  7418. std::to_string(PORT) +
  7419. "\r\n"
  7420. "Connection: close\r\n"
  7421. "\r\n";
  7422. // Add 12MB payload (exceeds 10MB limit)
  7423. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7424. request_without_content_length += large_payload;
  7425. std::string response;
  7426. bool result = send_request(10, request_without_content_length, &response);
  7427. if (!result) {
  7428. // Server should close connection due to payload limit
  7429. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7430. "(connection closed)";
  7431. } else {
  7432. // Check for error response
  7433. if (response.length() <= 10) {
  7434. SUCCEED()
  7435. << "Server closed connection for 12MB request exceeding 10MB limit";
  7436. } else {
  7437. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7438. response.find("Payload Too Large") != std::string::npos ||
  7439. response.find("400") != std::string::npos);
  7440. }
  7441. }
  7442. }
  7443. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7444. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7445. // path.
  7446. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7447. Server svr;
  7448. const size_t LIMIT = 64 * 1024; // 64KB
  7449. svr.set_payload_max_length(LIMIT);
  7450. size_t total = 0;
  7451. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7452. const ContentReader &content_reader) {
  7453. content_reader([&](const char * /*data*/, size_t len) {
  7454. total += len;
  7455. return true;
  7456. });
  7457. res.status = 200;
  7458. res.set_content("stream_ok", "text/plain");
  7459. });
  7460. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7461. auto se = detail::scope_exit([&] {
  7462. svr.stop();
  7463. thread.join();
  7464. ASSERT_FALSE(svr.is_running());
  7465. });
  7466. svr.wait_until_ready();
  7467. // Prepare 256KB raw data and gzip-compress it
  7468. std::string raw(256 * 1024, 'A');
  7469. std::string gz;
  7470. {
  7471. z_stream zs{};
  7472. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7473. Z_DEFAULT_STRATEGY);
  7474. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7475. zs.avail_in = static_cast<uInt>(raw.size());
  7476. char outbuf[4096];
  7477. int ret;
  7478. do {
  7479. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7480. zs.avail_out = sizeof(outbuf);
  7481. ret = deflate(&zs, Z_FINISH);
  7482. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7483. } while (ret != Z_STREAM_END);
  7484. deflateEnd(&zs);
  7485. }
  7486. Client cli(HOST, PORT);
  7487. cli.set_connection_timeout(std::chrono::seconds(5));
  7488. Headers headers = {{"Content-Encoding", "gzip"}};
  7489. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7490. "application/octet-stream");
  7491. ASSERT_TRUE(res);
  7492. // Server must reject oversized decompressed payloads with 413.
  7493. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7494. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7495. EXPECT_LE(total, LIMIT);
  7496. }
  7497. #endif
  7498. // Regression test for DoS vulnerability: a malicious server sending a response
  7499. // without Content-Length header must not cause unbounded memory consumption on
  7500. // the client side. The client should stop reading after a reasonable limit,
  7501. // similar to the server-side set_payload_max_length protection.
  7502. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7503. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7504. #ifndef _WIN32
  7505. signal(SIGPIPE, SIG_IGN);
  7506. #endif
  7507. auto server_thread = std::thread([] {
  7508. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7509. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7510. default_socket_options(srv);
  7511. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7512. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7513. sockaddr_in addr{};
  7514. addr.sin_family = AF_INET;
  7515. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7516. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7517. int opt = 1;
  7518. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7519. #ifdef _WIN32
  7520. reinterpret_cast<const char *>(&opt),
  7521. #else
  7522. &opt,
  7523. #endif
  7524. sizeof(opt));
  7525. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7526. ::listen(srv, 1);
  7527. sockaddr_in cli_addr{};
  7528. socklen_t cli_len = sizeof(cli_addr);
  7529. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7530. if (cli != INVALID_SOCKET) {
  7531. char buf[4096];
  7532. ::recv(cli, buf, sizeof(buf), 0);
  7533. // Malicious response: no Content-Length, no chunked encoding
  7534. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7535. "Connection: close\r\n"
  7536. "\r\n";
  7537. ::send(cli,
  7538. #ifdef _WIN32
  7539. static_cast<const char *>(response_header.c_str()),
  7540. static_cast<int>(response_header.size()),
  7541. #else
  7542. response_header.c_str(), response_header.size(),
  7543. #endif
  7544. 0);
  7545. // Send 10MB of data
  7546. std::string chunk(64 * 1024, 'A');
  7547. size_t total_sent = 0;
  7548. while (total_sent < MALICIOUS_DATA_SIZE) {
  7549. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7550. auto sent = ::send(cli,
  7551. #ifdef _WIN32
  7552. static_cast<const char *>(chunk.c_str()),
  7553. static_cast<int>(to_send),
  7554. #else
  7555. chunk.c_str(), to_send,
  7556. #endif
  7557. 0);
  7558. if (sent <= 0) break;
  7559. total_sent += static_cast<size_t>(sent);
  7560. }
  7561. detail::close_socket(cli);
  7562. }
  7563. detail::close_socket(srv);
  7564. });
  7565. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7566. size_t total_read = 0;
  7567. {
  7568. Client cli("127.0.0.1", PORT + 2);
  7569. cli.set_read_timeout(5, 0);
  7570. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7571. auto stream = cli.open_stream("GET", "/malicious");
  7572. ASSERT_TRUE(stream.is_valid());
  7573. char buffer[64 * 1024];
  7574. ssize_t n;
  7575. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7576. total_read += static_cast<size_t>(n);
  7577. }
  7578. } // StreamHandle and Client destroyed here, closing the socket
  7579. server_thread.join();
  7580. // With set_payload_max_length, the client must stop reading before consuming
  7581. // all 10MB. The read loop should be cut off at or near the configured limit.
  7582. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7583. << "Client read " << total_read << " bytes, exceeding the configured "
  7584. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7585. }
  7586. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7587. // the entire response body without truncation.
  7588. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7589. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7590. #ifndef _WIN32
  7591. signal(SIGPIPE, SIG_IGN);
  7592. #endif
  7593. auto server_thread = std::thread([] {
  7594. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7595. default_socket_options(srv);
  7596. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7597. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7598. sockaddr_in addr{};
  7599. addr.sin_family = AF_INET;
  7600. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7601. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7602. int opt = 1;
  7603. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7604. #ifdef _WIN32
  7605. reinterpret_cast<const char *>(&opt),
  7606. #else
  7607. &opt,
  7608. #endif
  7609. sizeof(opt));
  7610. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7611. ::listen(srv, 1);
  7612. sockaddr_in cli_addr{};
  7613. socklen_t cli_len = sizeof(cli_addr);
  7614. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7615. if (cli != INVALID_SOCKET) {
  7616. char buf[4096];
  7617. ::recv(cli, buf, sizeof(buf), 0);
  7618. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7619. "Connection: close\r\n"
  7620. "\r\n";
  7621. ::send(cli,
  7622. #ifdef _WIN32
  7623. static_cast<const char *>(response_header.c_str()),
  7624. static_cast<int>(response_header.size()),
  7625. #else
  7626. response_header.c_str(), response_header.size(),
  7627. #endif
  7628. 0);
  7629. std::string chunk(64 * 1024, 'A');
  7630. size_t total_sent = 0;
  7631. while (total_sent < DATA_SIZE) {
  7632. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7633. auto sent = ::send(cli,
  7634. #ifdef _WIN32
  7635. static_cast<const char *>(chunk.c_str()),
  7636. static_cast<int>(to_send),
  7637. #else
  7638. chunk.c_str(), to_send,
  7639. #endif
  7640. 0);
  7641. if (sent <= 0) break;
  7642. total_sent += static_cast<size_t>(sent);
  7643. }
  7644. #ifdef _WIN32
  7645. ::shutdown(cli, SD_SEND);
  7646. #else
  7647. ::shutdown(cli, SHUT_WR);
  7648. #endif
  7649. // Drain until the client closes its end, ensuring all data is delivered
  7650. char drain[1024];
  7651. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7652. detail::close_socket(cli);
  7653. }
  7654. detail::close_socket(srv);
  7655. });
  7656. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7657. size_t total_read = 0;
  7658. {
  7659. Client cli("127.0.0.1", PORT + 2);
  7660. cli.set_read_timeout(5, 0);
  7661. cli.set_payload_max_length(0); // 0 means no limit
  7662. auto stream = cli.open_stream("GET", "/data");
  7663. ASSERT_TRUE(stream.is_valid());
  7664. char buffer[64 * 1024];
  7665. ssize_t n;
  7666. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7667. total_read += static_cast<size_t>(n);
  7668. }
  7669. }
  7670. server_thread.join();
  7671. EXPECT_EQ(total_read, DATA_SIZE)
  7672. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7673. << " bytes without truncation, but only read " << total_read << " bytes.";
  7674. }
  7675. // Verify that content_receiver bypasses the default payload_max_length,
  7676. // allowing streaming downloads larger than 100MB without requiring an explicit
  7677. // set_payload_max_length call.
  7678. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7679. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7680. #ifndef _WIN32
  7681. signal(SIGPIPE, SIG_IGN);
  7682. #endif
  7683. auto server_thread = std::thread([] {
  7684. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7685. default_socket_options(srv);
  7686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7687. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7688. sockaddr_in addr{};
  7689. addr.sin_family = AF_INET;
  7690. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7691. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7692. int opt = 1;
  7693. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7694. #ifdef _WIN32
  7695. reinterpret_cast<const char *>(&opt),
  7696. #else
  7697. &opt,
  7698. #endif
  7699. sizeof(opt));
  7700. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7701. ::listen(srv, 1);
  7702. sockaddr_in cli_addr{};
  7703. socklen_t cli_len = sizeof(cli_addr);
  7704. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7705. if (cli != INVALID_SOCKET) {
  7706. char buf[4096];
  7707. ::recv(cli, buf, sizeof(buf), 0);
  7708. // Response with Content-Length larger than default 100MB limit
  7709. auto content_length = std::to_string(DATA_SIZE);
  7710. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7711. "Content-Length: " +
  7712. content_length +
  7713. "\r\n"
  7714. "Connection: close\r\n"
  7715. "\r\n";
  7716. ::send(cli,
  7717. #ifdef _WIN32
  7718. static_cast<const char *>(response_header.c_str()),
  7719. static_cast<int>(response_header.size()),
  7720. #else
  7721. response_header.c_str(), response_header.size(),
  7722. #endif
  7723. 0);
  7724. std::string chunk(64 * 1024, 'A');
  7725. size_t total_sent = 0;
  7726. while (total_sent < DATA_SIZE) {
  7727. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7728. auto sent = ::send(cli,
  7729. #ifdef _WIN32
  7730. static_cast<const char *>(chunk.c_str()),
  7731. static_cast<int>(to_send),
  7732. #else
  7733. chunk.c_str(), to_send,
  7734. #endif
  7735. 0);
  7736. if (sent <= 0) break;
  7737. total_sent += static_cast<size_t>(sent);
  7738. }
  7739. detail::close_socket(cli);
  7740. }
  7741. detail::close_socket(srv);
  7742. });
  7743. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7744. size_t total_received = 0;
  7745. {
  7746. Client cli("127.0.0.1", PORT + 2);
  7747. cli.set_read_timeout(10, 0);
  7748. // Do NOT call set_payload_max_length — use the default 100MB limit
  7749. auto res =
  7750. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7751. total_received += data_length;
  7752. return true;
  7753. });
  7754. ASSERT_TRUE(res);
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. }
  7757. server_thread.join();
  7758. EXPECT_EQ(total_received, DATA_SIZE)
  7759. << "With content_receiver, the client should read all " << DATA_SIZE
  7760. << " bytes despite the default 100MB payload_max_length, but only read "
  7761. << total_received << " bytes.";
  7762. }
  7763. // Verify that an explicit set_payload_max_length smaller than the response is
  7764. // enforced even when a content_receiver is used.
  7765. TEST(ClientVulnerabilityTest,
  7766. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7767. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7768. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7769. #ifndef _WIN32
  7770. signal(SIGPIPE, SIG_IGN);
  7771. #endif
  7772. auto server_thread = std::thread([] {
  7773. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7774. default_socket_options(srv);
  7775. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7776. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7777. sockaddr_in addr{};
  7778. addr.sin_family = AF_INET;
  7779. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7780. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7781. int opt = 1;
  7782. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7783. #ifdef _WIN32
  7784. reinterpret_cast<const char *>(&opt),
  7785. #else
  7786. &opt,
  7787. #endif
  7788. sizeof(opt));
  7789. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7790. ::listen(srv, 1);
  7791. sockaddr_in cli_addr{};
  7792. socklen_t cli_len = sizeof(cli_addr);
  7793. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7794. if (cli != INVALID_SOCKET) {
  7795. char buf[4096];
  7796. ::recv(cli, buf, sizeof(buf), 0);
  7797. auto content_length = std::to_string(DATA_SIZE);
  7798. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7799. "Content-Length: " +
  7800. content_length +
  7801. "\r\n"
  7802. "Connection: close\r\n"
  7803. "\r\n";
  7804. ::send(cli,
  7805. #ifdef _WIN32
  7806. static_cast<const char *>(response_header.c_str()),
  7807. static_cast<int>(response_header.size()),
  7808. #else
  7809. response_header.c_str(), response_header.size(),
  7810. #endif
  7811. 0);
  7812. std::string chunk(64 * 1024, 'A');
  7813. size_t total_sent = 0;
  7814. while (total_sent < DATA_SIZE) {
  7815. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7816. auto sent = ::send(cli,
  7817. #ifdef _WIN32
  7818. static_cast<const char *>(chunk.c_str()),
  7819. static_cast<int>(to_send),
  7820. #else
  7821. chunk.c_str(), to_send,
  7822. #endif
  7823. 0);
  7824. if (sent <= 0) break;
  7825. total_sent += static_cast<size_t>(sent);
  7826. }
  7827. detail::close_socket(cli);
  7828. }
  7829. detail::close_socket(srv);
  7830. });
  7831. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7832. size_t total_received = 0;
  7833. {
  7834. Client cli("127.0.0.1", PORT + 2);
  7835. cli.set_read_timeout(10, 0);
  7836. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7837. auto res =
  7838. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7839. total_received += data_length;
  7840. return true;
  7841. });
  7842. // Should fail because 200MB exceeds the explicit 150MB limit
  7843. EXPECT_FALSE(res);
  7844. }
  7845. server_thread.join();
  7846. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7847. << "Client with content_receiver should respect the explicit "
  7848. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7849. << total_received << " bytes.";
  7850. }
  7851. // Verify that an explicit set_payload_max_length larger than the response
  7852. // allows the content_receiver to read all data successfully.
  7853. TEST(ClientVulnerabilityTest,
  7854. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7855. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7856. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7857. #ifndef _WIN32
  7858. signal(SIGPIPE, SIG_IGN);
  7859. #endif
  7860. auto server_thread = std::thread([] {
  7861. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7862. default_socket_options(srv);
  7863. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7864. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7865. sockaddr_in addr{};
  7866. addr.sin_family = AF_INET;
  7867. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7868. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7869. int opt = 1;
  7870. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7871. #ifdef _WIN32
  7872. reinterpret_cast<const char *>(&opt),
  7873. #else
  7874. &opt,
  7875. #endif
  7876. sizeof(opt));
  7877. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7878. ::listen(srv, 1);
  7879. sockaddr_in cli_addr{};
  7880. socklen_t cli_len = sizeof(cli_addr);
  7881. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7882. if (cli != INVALID_SOCKET) {
  7883. char buf[4096];
  7884. ::recv(cli, buf, sizeof(buf), 0);
  7885. auto content_length = std::to_string(DATA_SIZE);
  7886. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7887. "Content-Length: " +
  7888. content_length +
  7889. "\r\n"
  7890. "Connection: close\r\n"
  7891. "\r\n";
  7892. ::send(cli,
  7893. #ifdef _WIN32
  7894. static_cast<const char *>(response_header.c_str()),
  7895. static_cast<int>(response_header.size()),
  7896. #else
  7897. response_header.c_str(), response_header.size(),
  7898. #endif
  7899. 0);
  7900. std::string chunk(64 * 1024, 'A');
  7901. size_t total_sent = 0;
  7902. while (total_sent < DATA_SIZE) {
  7903. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7904. auto sent = ::send(cli,
  7905. #ifdef _WIN32
  7906. static_cast<const char *>(chunk.c_str()),
  7907. static_cast<int>(to_send),
  7908. #else
  7909. chunk.c_str(), to_send,
  7910. #endif
  7911. 0);
  7912. if (sent <= 0) break;
  7913. total_sent += static_cast<size_t>(sent);
  7914. }
  7915. #ifdef _WIN32
  7916. ::shutdown(cli, SD_SEND);
  7917. #else
  7918. ::shutdown(cli, SHUT_WR);
  7919. #endif
  7920. char drain[1024];
  7921. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7922. detail::close_socket(cli);
  7923. }
  7924. detail::close_socket(srv);
  7925. });
  7926. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7927. size_t total_received = 0;
  7928. {
  7929. Client cli("127.0.0.1", PORT + 2);
  7930. cli.set_read_timeout(10, 0);
  7931. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7932. auto res =
  7933. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7934. total_received += data_length;
  7935. return true;
  7936. });
  7937. ASSERT_TRUE(res);
  7938. EXPECT_EQ(StatusCode::OK_200, res->status);
  7939. }
  7940. server_thread.join();
  7941. EXPECT_EQ(total_received, DATA_SIZE)
  7942. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7943. << " bytes (larger than " << DATA_SIZE
  7944. << " bytes response), content_receiver should read all data, but only "
  7945. "read "
  7946. << total_received << " bytes.";
  7947. }
  7948. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7949. // Regression test for "zip bomb" attack on the client side: a malicious server
  7950. // sends a small gzip-compressed response that decompresses to a huge payload.
  7951. // The client must enforce payload_max_length on the decompressed size.
  7952. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7953. constexpr size_t DECOMPRESSED_SIZE =
  7954. 10 * 1024 * 1024; // 10MB after decompression
  7955. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7956. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7957. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7958. std::string compressed;
  7959. {
  7960. httplib::detail::gzip_compressor compressor;
  7961. bool ok =
  7962. compressor.compress(uncompressed.data(), uncompressed.size(),
  7963. /*last=*/true, [&](const char *buf, size_t len) {
  7964. compressed.append(buf, len);
  7965. return true;
  7966. });
  7967. ASSERT_TRUE(ok);
  7968. }
  7969. // Sanity: compressed data should be much smaller than the decompressed size
  7970. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7971. #ifndef _WIN32
  7972. signal(SIGPIPE, SIG_IGN);
  7973. #endif
  7974. // Set up the listening socket in the main thread so the server is guaranteed
  7975. // to be ready before the client connects (eliminates race condition).
  7976. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7977. default_socket_options(srv);
  7978. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7979. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7980. sockaddr_in addr{};
  7981. addr.sin_family = AF_INET;
  7982. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  7983. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7984. int opt = 1;
  7985. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7986. #ifdef _WIN32
  7987. reinterpret_cast<const char *>(&opt),
  7988. #else
  7989. &opt,
  7990. #endif
  7991. sizeof(opt));
  7992. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7993. ASSERT_EQ(0, ::listen(srv, 1));
  7994. auto server_thread = std::thread([&compressed, srv] {
  7995. sockaddr_in cli_addr{};
  7996. socklen_t cli_len = sizeof(cli_addr);
  7997. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7998. if (cli != INVALID_SOCKET) {
  7999. // Read the full HTTP request (until \r\n\r\n)
  8000. char buf[4096];
  8001. size_t total = 0;
  8002. while (total < sizeof(buf)) {
  8003. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8004. if (n <= 0) break;
  8005. total += static_cast<size_t>(n);
  8006. // Check for end of headers
  8007. if (total >= 4) {
  8008. std::string req(buf, total);
  8009. if (req.find("\r\n\r\n") != std::string::npos) break;
  8010. }
  8011. }
  8012. // Malicious response: gzip-compressed body, no Content-Length
  8013. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8014. "Content-Encoding: gzip\r\n"
  8015. "Connection: close\r\n"
  8016. "\r\n";
  8017. ::send(cli,
  8018. #ifdef _WIN32
  8019. static_cast<const char *>(response_header.c_str()),
  8020. static_cast<int>(response_header.size()),
  8021. #else
  8022. response_header.c_str(), response_header.size(),
  8023. #endif
  8024. 0);
  8025. // Send the compressed payload (small on the wire, huge when decompressed)
  8026. size_t total_sent = 0;
  8027. while (total_sent < compressed.size()) {
  8028. auto to_send = std::min(compressed.size() - total_sent,
  8029. static_cast<size_t>(64 * 1024));
  8030. auto sent =
  8031. ::send(cli,
  8032. #ifdef _WIN32
  8033. static_cast<const char *>(compressed.c_str() + total_sent),
  8034. static_cast<int>(to_send),
  8035. #else
  8036. compressed.c_str() + total_sent, to_send,
  8037. #endif
  8038. 0);
  8039. if (sent <= 0) break;
  8040. total_sent += static_cast<size_t>(sent);
  8041. }
  8042. detail::close_socket(cli);
  8043. }
  8044. });
  8045. auto se = detail::scope_exit([&] {
  8046. detail::close_socket(srv);
  8047. server_thread.join();
  8048. });
  8049. size_t total_decompressed = 0;
  8050. {
  8051. Client cli("127.0.0.1", PORT + 3);
  8052. cli.set_read_timeout(5, 0);
  8053. cli.set_decompress(true);
  8054. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8055. auto stream = cli.open_stream("GET", "/zipbomb");
  8056. ASSERT_TRUE(stream.is_valid());
  8057. char buffer[64 * 1024];
  8058. ssize_t n;
  8059. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8060. total_decompressed += static_cast<size_t>(n);
  8061. }
  8062. }
  8063. // The decompressed size must be capped by payload_max_length. Without
  8064. // protection, the client would decompress the full 10MB from a tiny
  8065. // compressed payload, enabling a zip bomb DoS attack.
  8066. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8067. << "Client decompressed " << total_decompressed
  8068. << " bytes from a gzip response. The decompressed size should be "
  8069. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8070. }
  8071. #endif
  8072. TEST(HostAndPortPropertiesTest, NoSSL) {
  8073. httplib::Client cli("www.google.com", 1234);
  8074. ASSERT_EQ("www.google.com", cli.host());
  8075. ASSERT_EQ(1234, cli.port());
  8076. }
  8077. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8078. httplib::Client cli("www.google.com:1234");
  8079. ASSERT_EQ("www.google.com", cli.host());
  8080. ASSERT_EQ(1234, cli.port());
  8081. }
  8082. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8083. // Port number that overflows int — should not crash, client becomes invalid
  8084. httplib::Client cli("http://www.google.com:99999999999999999999");
  8085. ASSERT_FALSE(cli.is_valid());
  8086. }
  8087. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8088. // Port 99999 exceeds valid range (1-65535) — should not crash
  8089. httplib::Client cli("http://www.google.com:99999");
  8090. ASSERT_FALSE(cli.is_valid());
  8091. }
  8092. #ifdef CPPHTTPLIB_SSL_ENABLED
  8093. TEST(HostAndPortPropertiesTest, SSL) {
  8094. httplib::SSLClient cli("www.google.com");
  8095. ASSERT_EQ("www.google.com", cli.host());
  8096. ASSERT_EQ(443, cli.port());
  8097. }
  8098. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8099. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8100. std::string cert;
  8101. read_file(CA_CERT_FILE, cert);
  8102. httplib::SSLClient httplib_client("www.google.com");
  8103. // Load CA store first time
  8104. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8105. // Load CA store second time (update)
  8106. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8107. // Verify client is still valid and can make connections
  8108. httplib_client.enable_server_certificate_verification(true);
  8109. auto res = httplib_client.Get("/");
  8110. ASSERT_TRUE(res);
  8111. // Google may return 200 or 301 depending on various factors
  8112. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8113. res->status == StatusCode::MovedPermanently_301);
  8114. }
  8115. TEST(SSLClientTest, ServerNameIndication_Online) {
  8116. auto host = "httpbingo.org";
  8117. auto path = std::string{"/get"};
  8118. SSLClient cli(host, 443);
  8119. auto res = cli.Get(path);
  8120. ASSERT_TRUE(res);
  8121. ASSERT_EQ(StatusCode::OK_200, res->status);
  8122. }
  8123. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8124. // Use a site that will cause SSL verification failure due to self-signed cert
  8125. SSLClient cli("self-signed.badssl.com", 443);
  8126. cli.enable_server_certificate_verification(true);
  8127. auto res = cli.Get("/");
  8128. ASSERT_TRUE(!res);
  8129. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8130. // Verify backend error is captured for SSLServerVerification
  8131. // This occurs when certificate verification fails
  8132. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8133. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8134. EXPECT_NE(0UL, res.ssl_backend_error());
  8135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8136. // For OpenSSL, ssl_error is 0 for verification errors
  8137. EXPECT_EQ(0, res.ssl_error());
  8138. #if !defined(_WIN32) || \
  8139. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8140. // On non-Windows or when Windows Schannel is disabled, the error comes
  8141. // from OpenSSL's verification
  8142. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8143. res.ssl_backend_error());
  8144. #endif
  8145. #endif
  8146. }
  8147. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8148. // Use a site where hostname doesn't match the certificate
  8149. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8150. SSLClient cli("wrong.host.badssl.com", 443);
  8151. cli.enable_server_certificate_verification(true);
  8152. cli.enable_server_hostname_verification(true);
  8153. auto res = cli.Get("/");
  8154. ASSERT_TRUE(!res);
  8155. // The error type depends on when hostname verification occurs:
  8156. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8157. // - Mbed TLS: SSLServerVerification (during handshake)
  8158. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8159. res.error() == Error::SSLServerVerification);
  8160. // Verify backend error is captured for hostname verification failure
  8161. EXPECT_NE(0UL, res.ssl_backend_error());
  8162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8163. // For OpenSSL, ssl_error is 0 for verification errors
  8164. EXPECT_EQ(0, res.ssl_error());
  8165. #if !defined(_WIN32) || \
  8166. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8167. // On non-Windows or when Windows Schannel is disabled, the error comes
  8168. // from OpenSSL's hostname verification
  8169. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8170. res.ssl_backend_error());
  8171. #endif
  8172. #endif
  8173. }
  8174. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8175. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8176. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8177. SSLClient cli("www.google.com", 443);
  8178. cli.enable_server_certificate_verification(true);
  8179. auto res = cli.Get("/");
  8180. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8181. }
  8182. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8183. SSLClient cli("www.google.com", 443);
  8184. cli.enable_server_certificate_verification(true);
  8185. cli.enable_windows_certificate_verification(false);
  8186. auto res = cli.Get("/");
  8187. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8188. }
  8189. #endif
  8190. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8191. Client cli("https://google.com");
  8192. auto res = cli.Get("/");
  8193. ASSERT_TRUE(res);
  8194. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8195. }
  8196. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8197. SSLClient cli("google.com");
  8198. cli.set_ca_cert_path(CA_CERT_FILE);
  8199. auto res = cli.Get("/");
  8200. ASSERT_TRUE(res);
  8201. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8202. }
  8203. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8204. SSLClient cli("google.com");
  8205. cli.enable_server_certificate_verification(true);
  8206. cli.set_ca_cert_path("hello");
  8207. auto res = cli.Get("/");
  8208. ASSERT_TRUE(!res);
  8209. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8210. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8211. // should be set
  8212. EXPECT_EQ(0, res.ssl_error());
  8213. // Verify backend error is captured for SSLLoadingCerts
  8214. // This error occurs when loading CA certificates fails
  8215. EXPECT_NE(0UL, res.ssl_backend_error());
  8216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8217. // OpenSSL specific error codes:
  8218. // > openssl errstr 0x80000002
  8219. // error:80000002:system library::No such file or directory
  8220. // > openssl errstr 0xA000126
  8221. // error:0A000126:SSL routines::unexpected eof while reading
  8222. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8223. res.ssl_backend_error() == 0xA000126);
  8224. #endif
  8225. }
  8226. TEST(SSLClientTest, ServerCertificateVerification4) {
  8227. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8228. ASSERT_TRUE(svr.is_valid());
  8229. svr.Get("/test", [&](const Request &, Response &res) {
  8230. res.set_content("test", "text/plain");
  8231. svr.stop();
  8232. ASSERT_TRUE(true);
  8233. });
  8234. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8235. auto se = detail::scope_exit([&] {
  8236. t.join();
  8237. ASSERT_FALSE(svr.is_running());
  8238. });
  8239. svr.wait_until_ready();
  8240. SSLClient cli("127.0.0.1", PORT);
  8241. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8242. cli.enable_server_certificate_verification(true);
  8243. cli.set_connection_timeout(30);
  8244. auto res = cli.Get("/test");
  8245. ASSERT_TRUE(res);
  8246. ASSERT_EQ(StatusCode::OK_200, res->status);
  8247. }
  8248. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8249. std::string cert;
  8250. read_file(CA_CERT_FILE, cert);
  8251. SSLClient cli("google.com");
  8252. cli.load_ca_cert_store(cert.data(), cert.size());
  8253. const auto res = cli.Get("/");
  8254. ASSERT_TRUE(res);
  8255. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8256. }
  8257. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8258. // clang-format off
  8259. static constexpr char cert[] =
  8260. "GlobalSign Root CA\n"
  8261. "==================\n"
  8262. "-----BEGIN CERTIFICATE-----\n"
  8263. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8264. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8265. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8266. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8267. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8268. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8269. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8270. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8271. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8272. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8273. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8274. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8275. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8276. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8277. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8278. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8279. "-----END CERTIFICATE-----\n";
  8280. // clang-format on
  8281. SSLClient cli("google.com");
  8282. cli.load_ca_cert_store(cert, sizeof(cert));
  8283. const auto res = cli.Get("/");
  8284. ASSERT_TRUE(res);
  8285. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8286. }
  8287. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8288. SSLClient cli("www.youtube.com");
  8289. cli.set_ca_cert_path(CA_CERT_FILE);
  8290. cli.enable_server_certificate_verification(true);
  8291. cli.set_follow_location(true);
  8292. auto res = cli.Get("/");
  8293. ASSERT_TRUE(res);
  8294. ASSERT_EQ(StatusCode::OK_200, res->status);
  8295. }
  8296. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8297. SSLClient cli("wWw.YouTube.Com");
  8298. cli.set_ca_cert_path(CA_CERT_FILE);
  8299. cli.enable_server_certificate_verification(true);
  8300. cli.enable_server_hostname_verification(true);
  8301. cli.set_follow_location(true);
  8302. auto res = cli.Get("/");
  8303. ASSERT_TRUE(res);
  8304. ASSERT_EQ(StatusCode::OK_200, res->status);
  8305. }
  8306. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8307. SSLClient cli("gOoGlE.COm");
  8308. cli.enable_server_certificate_verification(true);
  8309. cli.enable_server_hostname_verification(true);
  8310. cli.set_follow_location(true);
  8311. auto res = cli.Get("/");
  8312. ASSERT_TRUE(res);
  8313. ASSERT_EQ(StatusCode::OK_200, res->status);
  8314. }
  8315. TEST(SSLClientTest, Issue2004_Online) {
  8316. Client client("https://google.com");
  8317. client.set_follow_location(true);
  8318. auto res = client.Get("/");
  8319. ASSERT_TRUE(res);
  8320. ASSERT_EQ(StatusCode::OK_200, res->status);
  8321. auto body = res->body;
  8322. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8323. }
  8324. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8325. // Create SSLClient with invalid cert/key to make is_valid() return false
  8326. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8327. "nonexistent_key.pem");
  8328. // is_valid() should be false due to cert loading failure
  8329. ASSERT_FALSE(cli.is_valid());
  8330. auto res = cli.Get("/");
  8331. ASSERT_FALSE(res);
  8332. EXPECT_EQ(Error::SSLConnection, res.error());
  8333. }
  8334. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8335. // Test for Issue #2251: SSL error not properly reported when client cert
  8336. // and key paths are swapped or mismatched
  8337. // This simulates the scenario where user accidentally swaps the cert and key
  8338. // files
  8339. // Using client cert file as private key and vice versa (completely wrong)
  8340. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8341. // Should fail validation due to cert/key mismatch
  8342. ASSERT_FALSE(cli.is_valid());
  8343. // Attempt to make a request should fail with proper error
  8344. auto res = cli.Get("/");
  8345. ASSERT_FALSE(res);
  8346. EXPECT_EQ(Error::SSLConnection, res.error());
  8347. // SSL error should be recorded in the Result object (this is the key fix for
  8348. // Issue #2251)
  8349. auto backend_error = res.ssl_backend_error();
  8350. EXPECT_NE(0u, backend_error);
  8351. }
  8352. // Tests cert/key mismatch detection at the TLS context level
  8353. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8354. // Test that using mismatched cert/key causes connection failure.
  8355. // We verify this at the SSLClient level rather than through internal
  8356. // TLS API functions.
  8357. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8358. cli.enable_server_certificate_verification(false);
  8359. cli.set_connection_timeout(2);
  8360. // The mismatch should cause a connection or handshake error
  8361. auto res = cli.Get("/test");
  8362. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8363. // Either way, the request should fail
  8364. EXPECT_FALSE(res);
  8365. }
  8366. #endif
  8367. #if 0
  8368. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8369. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8370. ASSERT_TRUE(cli != nullptr);
  8371. cli->set_address_family(AF_INET6);
  8372. cli->set_interface("en0");
  8373. auto res = cli->Get("/get");
  8374. ASSERT_TRUE(res);
  8375. ASSERT_EQ(StatusCode::OK_200, res->status);
  8376. }
  8377. #endif
  8378. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8379. #ifdef CPPHTTPLIB_SSL_ENABLED
  8380. void ClientCertPresent(
  8381. const std::string &client_cert_file,
  8382. const std::string &client_private_key_file,
  8383. const std::string &client_encrypted_private_key_pass = std::string()) {
  8384. using namespace httplib::tls;
  8385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8386. CLIENT_CA_CERT_DIR);
  8387. ASSERT_TRUE(svr.is_valid());
  8388. svr.Get("/test", [&](const Request &req, Response &res) {
  8389. res.set_content("test", "text/plain");
  8390. auto cert = req.peer_cert();
  8391. ASSERT_TRUE(static_cast<bool>(cert));
  8392. std::string common_name = cert.subject_cn();
  8393. EXPECT_EQ("Common Name", common_name);
  8394. });
  8395. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8396. auto se = detail::scope_exit([&] {
  8397. svr.stop();
  8398. t.join();
  8399. ASSERT_FALSE(svr.is_running());
  8400. });
  8401. svr.wait_until_ready();
  8402. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8403. client_encrypted_private_key_pass);
  8404. cli.enable_server_certificate_verification(false);
  8405. cli.set_connection_timeout(30);
  8406. auto res = cli.Get("/test");
  8407. ASSERT_TRUE(res);
  8408. ASSERT_EQ(StatusCode::OK_200, res->status);
  8409. }
  8410. TEST(SSLClientServerTest, ClientCertPresent) {
  8411. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8412. }
  8413. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8414. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8415. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8416. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8417. }
  8418. // PEM memory-based constructor tests (works with all TLS backends)
  8419. void PemMemoryClientCertPresent(
  8420. const std::string &client_cert_file,
  8421. const std::string &client_private_key_file,
  8422. const std::string &client_encrypted_private_key_pass = std::string()) {
  8423. // Read PEM files into memory
  8424. std::string server_cert_pem, server_key_pem;
  8425. std::string client_ca_pem;
  8426. std::string client_cert_pem, client_key_pem;
  8427. read_file(SERVER_CERT_FILE, server_cert_pem);
  8428. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8429. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8430. read_file(client_cert_file, client_cert_pem);
  8431. read_file(client_private_key_file, client_key_pem);
  8432. // Create server with PEM memory
  8433. SSLServer::PemMemory server_pem = {
  8434. server_cert_pem.c_str(),
  8435. server_cert_pem.size(),
  8436. server_key_pem.c_str(),
  8437. server_key_pem.size(),
  8438. client_ca_pem.c_str(),
  8439. client_ca_pem.size(),
  8440. nullptr // no password for server key
  8441. };
  8442. SSLServer svr(server_pem);
  8443. ASSERT_TRUE(svr.is_valid());
  8444. svr.Get("/test", [&](const Request &, Response &res) {
  8445. res.set_content("test", "text/plain");
  8446. });
  8447. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8448. auto se = detail::scope_exit([&] {
  8449. svr.stop();
  8450. t.join();
  8451. ASSERT_FALSE(svr.is_running());
  8452. });
  8453. svr.wait_until_ready();
  8454. // Create client with PEM memory
  8455. const char *password = client_encrypted_private_key_pass.empty()
  8456. ? nullptr
  8457. : client_encrypted_private_key_pass.c_str();
  8458. SSLClient::PemMemory client_pem = {
  8459. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8460. client_key_pem.size(), password};
  8461. SSLClient cli(HOST, PORT, client_pem);
  8462. cli.enable_server_certificate_verification(false);
  8463. cli.set_connection_timeout(30);
  8464. auto res = cli.Get("/test");
  8465. ASSERT_TRUE(res);
  8466. ASSERT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8469. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8470. }
  8471. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8472. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8473. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8474. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8475. }
  8476. TEST(SSLClientServerTest, ClientCertMissing) {
  8477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8478. CLIENT_CA_CERT_DIR);
  8479. ASSERT_TRUE(svr.is_valid());
  8480. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8481. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8482. auto se = detail::scope_exit([&] {
  8483. svr.stop();
  8484. t.join();
  8485. ASSERT_FALSE(svr.is_running());
  8486. });
  8487. svr.wait_until_ready();
  8488. SSLClient cli(HOST, PORT);
  8489. cli.set_connection_timeout(30);
  8490. auto res = cli.Get("/test");
  8491. ASSERT_TRUE(!res);
  8492. // When client cert is missing and server requires it, connection fails
  8493. // Error type depends on backend implementation
  8494. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8495. res.error() == Error::SSLConnection);
  8496. // Verify backend error is captured
  8497. // Note: This test may have different error codes depending on the exact
  8498. // verification failure
  8499. EXPECT_NE(0UL, res.ssl_backend_error());
  8500. }
  8501. TEST(SSLClientServerTest, TrustDirOptional) {
  8502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8503. ASSERT_TRUE(svr.is_valid());
  8504. svr.Get("/test", [&](const Request &, Response &res) {
  8505. res.set_content("test", "text/plain");
  8506. });
  8507. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8508. auto se = detail::scope_exit([&] {
  8509. svr.stop();
  8510. t.join();
  8511. ASSERT_FALSE(svr.is_running());
  8512. });
  8513. svr.wait_until_ready();
  8514. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8515. cli.enable_server_certificate_verification(false);
  8516. cli.set_connection_timeout(30);
  8517. auto res = cli.Get("/test");
  8518. ASSERT_TRUE(res);
  8519. ASSERT_EQ(StatusCode::OK_200, res->status);
  8520. }
  8521. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8522. class NoListenSSLServer : public SSLServer {
  8523. public:
  8524. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8525. const char *client_ca_cert_file_path,
  8526. const char *client_ca_cert_dir_path = nullptr)
  8527. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8528. client_ca_cert_dir_path),
  8529. stop_(false) {}
  8530. std::atomic_bool stop_;
  8531. private:
  8532. bool process_and_close_socket(socket_t /*sock*/) override {
  8533. // Don't create SSL context
  8534. while (!stop_.load()) {
  8535. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8536. }
  8537. return true;
  8538. }
  8539. };
  8540. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8541. CLIENT_CA_CERT_FILE);
  8542. ASSERT_TRUE(svr.is_valid());
  8543. svr.Get("/test", [&](const Request &, Response &res) {
  8544. res.set_content("test", "text/plain");
  8545. });
  8546. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8547. auto se = detail::scope_exit([&] {
  8548. svr.stop_ = true;
  8549. svr.stop();
  8550. t.join();
  8551. ASSERT_FALSE(svr.is_running());
  8552. });
  8553. svr.wait_until_ready();
  8554. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8555. cli.enable_server_certificate_verification(false);
  8556. cli.set_connection_timeout(1);
  8557. auto res = cli.Get("/test");
  8558. ASSERT_TRUE(!res);
  8559. EXPECT_EQ(Error::SSLConnection, res.error());
  8560. // Timeout results in WantRead error code (maps to backend-specific value)
  8561. EXPECT_NE(0, res.ssl_error());
  8562. }
  8563. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8564. // Test SSLServer with client certificate verification using the standard
  8565. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8567. CLIENT_CA_CERT_DIR);
  8568. ASSERT_TRUE(svr.is_valid());
  8569. svr.Get("/test", [&](const Request &req, Response &res) {
  8570. res.set_content("test", "text/plain");
  8571. auto cert = req.peer_cert();
  8572. ASSERT_TRUE(static_cast<bool>(cert));
  8573. auto common_name = cert.subject_cn();
  8574. EXPECT_EQ("Common Name", common_name);
  8575. });
  8576. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8577. auto se = detail::scope_exit([&] {
  8578. svr.stop();
  8579. t.join();
  8580. ASSERT_FALSE(svr.is_running());
  8581. });
  8582. svr.wait_until_ready();
  8583. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8584. cli.enable_server_certificate_verification(false);
  8585. cli.set_connection_timeout(30);
  8586. auto res = cli.Get("/test");
  8587. ASSERT_TRUE(res);
  8588. ASSERT_EQ(StatusCode::OK_200, res->status);
  8589. }
  8590. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8591. // Verifies that wildcard matching and exact matching work consistently
  8592. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8593. using namespace httplib::tls;
  8594. // We need a running server to test against
  8595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8596. ASSERT_TRUE(svr.is_valid());
  8597. svr.Get("/test", [](const Request &, Response &res) {
  8598. res.set_content("ok", "text/plain");
  8599. });
  8600. thread t([&]() { svr.listen(HOST, PORT); });
  8601. auto se = detail::scope_exit([&] {
  8602. svr.stop();
  8603. t.join();
  8604. });
  8605. svr.wait_until_ready();
  8606. bool verify_callback_called = false;
  8607. bool verify_result_wrong = false;
  8608. SSLClient cli(HOST, PORT);
  8609. cli.enable_server_certificate_verification(true);
  8610. cli.set_ca_cert_path(CA_CERT_FILE);
  8611. cli.set_connection_timeout(5);
  8612. // Note: Test certificate has CN="Common Name", not "localhost"
  8613. bool verify_result_cn = false;
  8614. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8615. verify_callback_called = true;
  8616. if (!ctx.cert) return false;
  8617. // Test 1: "Common Name" should match (our test server cert CN)
  8618. verify_result_cn = ctx.check_hostname("Common Name");
  8619. // Test 2: wrong hostname should not match
  8620. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8621. return true; // Accept for the purpose of this test
  8622. });
  8623. auto res = cli.Get("/test");
  8624. // The request may succeed or fail depending on cert configuration
  8625. // but the callback should have been called
  8626. ASSERT_TRUE(verify_callback_called)
  8627. << "Verify callback should have been called";
  8628. // CN="Common Name" should match our test certificate
  8629. EXPECT_TRUE(verify_result_cn)
  8630. << "verify_hostname should match 'Common Name' (certificate CN)";
  8631. // Wrong hostname should not match
  8632. EXPECT_FALSE(verify_result_wrong)
  8633. << "verify_hostname should not match 'wronghost.example.com'";
  8634. }
  8635. #endif
  8636. // mbedTLS-specific callback constructor test
  8637. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8638. #ifdef CPPHTTPLIB_SSL_ENABLED
  8639. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8640. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8641. ASSERT_TRUE(svr.is_valid());
  8642. // Set up a handler to verify client certificate is present
  8643. bool client_cert_verified = false;
  8644. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8645. // Verify that client certificate was provided
  8646. client_cert_verified = true;
  8647. res.set_content("success", "text/plain");
  8648. });
  8649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8650. auto se = detail::scope_exit([&] {
  8651. svr.stop();
  8652. t.join();
  8653. ASSERT_FALSE(svr.is_running());
  8654. });
  8655. svr.wait_until_ready();
  8656. // Client with certificate
  8657. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8658. cli.enable_server_certificate_verification(false);
  8659. cli.set_connection_timeout(30);
  8660. auto res = cli.Get("/test");
  8661. ASSERT_TRUE(res);
  8662. ASSERT_EQ(StatusCode::OK_200, res->status);
  8663. ASSERT_TRUE(client_cert_verified);
  8664. EXPECT_EQ("success", res->body);
  8665. }
  8666. #endif
  8667. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8668. // backends
  8669. #ifdef CPPHTTPLIB_SSL_ENABLED
  8670. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8671. using namespace httplib::tls;
  8672. // Test that when client CA cert file is provided,
  8673. // the server properly requests and validates client certificates
  8674. // Create a server with client authentication
  8675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8676. ASSERT_TRUE(svr.is_valid());
  8677. bool handler_called = false;
  8678. svr.Get("/test", [&](const Request &req, Response &res) {
  8679. handler_called = true;
  8680. // Verify that a client certificate was provided
  8681. auto cert = req.peer_cert();
  8682. ASSERT_TRUE(static_cast<bool>(cert));
  8683. // Get the issuer name
  8684. std::string issuer_str = cert.issuer_name();
  8685. ASSERT_FALSE(issuer_str.empty());
  8686. // The client certificate should be issued by our test CA
  8687. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8688. res.set_content("authenticated", "text/plain");
  8689. });
  8690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8691. auto se = detail::scope_exit([&] {
  8692. svr.stop();
  8693. t.join();
  8694. ASSERT_FALSE(svr.is_running());
  8695. });
  8696. svr.wait_until_ready();
  8697. // Connect with a client certificate issued by the CA
  8698. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8699. cli.enable_server_certificate_verification(false);
  8700. cli.set_connection_timeout(30);
  8701. auto res = cli.Get("/test");
  8702. ASSERT_TRUE(res);
  8703. ASSERT_EQ(StatusCode::OK_200, res->status);
  8704. ASSERT_TRUE(handler_called);
  8705. EXPECT_EQ("authenticated", res->body);
  8706. }
  8707. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8708. using namespace httplib::tls;
  8709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8710. ASSERT_TRUE(svr.is_valid());
  8711. svr.Get("/test", [](const Request &, Response &res) {
  8712. res.set_content("ok", "text/plain");
  8713. });
  8714. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8715. auto se = detail::scope_exit([&] {
  8716. svr.stop();
  8717. t.join();
  8718. });
  8719. svr.wait_until_ready();
  8720. SSLClient cli(HOST, PORT);
  8721. cli.enable_server_certificate_verification(false);
  8722. cli.set_connection_timeout(30);
  8723. bool cert_checked = false;
  8724. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8725. if (ctx.cert) {
  8726. auto sans = ctx.sans();
  8727. // Test certificate may or may not have SANs - just verify the API
  8728. // works If SANs exist, verify the types are valid
  8729. for (const auto &san : sans) {
  8730. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8731. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8732. san.type == SanType::OTHER);
  8733. EXPECT_FALSE(san.value.empty());
  8734. }
  8735. cert_checked = true;
  8736. }
  8737. return true;
  8738. });
  8739. auto res = cli.Get("/test");
  8740. ASSERT_TRUE(res);
  8741. EXPECT_TRUE(cert_checked);
  8742. }
  8743. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8744. using namespace httplib::tls;
  8745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8746. ASSERT_TRUE(svr.is_valid());
  8747. svr.Get("/test", [](const Request &, Response &res) {
  8748. res.set_content("ok", "text/plain");
  8749. });
  8750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. t.join();
  8754. });
  8755. svr.wait_until_ready();
  8756. SSLClient cli(HOST, PORT);
  8757. cli.enable_server_certificate_verification(false);
  8758. cli.set_connection_timeout(30);
  8759. bool validity_checked = false;
  8760. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8761. if (ctx.cert) {
  8762. time_t not_before = 0, not_after = 0;
  8763. bool result = ctx.validity(not_before, not_after);
  8764. EXPECT_TRUE(result);
  8765. // Verify that not_before < now < not_after for a valid cert
  8766. time_t now = time(nullptr);
  8767. EXPECT_LT(not_before, now);
  8768. EXPECT_GT(not_after, now);
  8769. validity_checked = true;
  8770. }
  8771. return true;
  8772. });
  8773. auto res = cli.Get("/test");
  8774. ASSERT_TRUE(res);
  8775. EXPECT_TRUE(validity_checked);
  8776. }
  8777. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8778. using namespace httplib::tls;
  8779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8780. ASSERT_TRUE(svr.is_valid());
  8781. svr.Get("/test", [](const Request &, Response &res) {
  8782. res.set_content("ok", "text/plain");
  8783. });
  8784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8785. auto se = detail::scope_exit([&] {
  8786. svr.stop();
  8787. t.join();
  8788. });
  8789. svr.wait_until_ready();
  8790. SSLClient cli(HOST, PORT);
  8791. cli.enable_server_certificate_verification(false);
  8792. cli.set_connection_timeout(30);
  8793. bool serial_checked = false;
  8794. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8795. if (ctx.cert) {
  8796. std::string serial = ctx.serial();
  8797. EXPECT_FALSE(serial.empty());
  8798. // Serial should be a hex string
  8799. for (char c : serial) {
  8800. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8801. (c >= 'a' && c <= 'f'));
  8802. }
  8803. serial_checked = true;
  8804. }
  8805. return true;
  8806. });
  8807. auto res = cli.Get("/test");
  8808. ASSERT_TRUE(res);
  8809. EXPECT_TRUE(serial_checked);
  8810. }
  8811. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8812. // Test 1: Valid CA file - no error should be recorded
  8813. {
  8814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8815. CLIENT_CA_CERT_FILE);
  8816. ASSERT_TRUE(svr.is_valid());
  8817. // With valid setup, last_ssl_error should be 0
  8818. EXPECT_EQ(0, svr.ssl_last_error());
  8819. }
  8820. // Test 2: Invalid CA file content
  8821. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8822. {
  8823. // Create a temporary file with completely invalid content
  8824. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8825. {
  8826. std::ofstream ofs(temp_invalid_ca);
  8827. ofs << "This is not a certificate file at all\n";
  8828. ofs << "Just plain text content\n";
  8829. }
  8830. // Create server with invalid CA file
  8831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8832. // Clean up temporary file
  8833. std::remove(temp_invalid_ca);
  8834. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8835. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8836. // Note: SSL_CTX_load_verify_locations typically fails first,
  8837. // but our error handling code path is still exercised
  8838. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8839. }
  8840. }
  8841. TEST(VerifyCallbackTest, VerifyContextFields) {
  8842. using namespace httplib::tls;
  8843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8844. ASSERT_TRUE(svr.is_valid());
  8845. svr.Get("/test", [](const Request &, Response &res) {
  8846. res.set_content("ok", "text/plain");
  8847. });
  8848. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8849. auto se = detail::scope_exit([&] {
  8850. svr.stop();
  8851. t.join();
  8852. });
  8853. svr.wait_until_ready();
  8854. SSLClient cli(HOST, PORT);
  8855. cli.enable_server_certificate_verification(false);
  8856. cli.set_connection_timeout(30);
  8857. int callback_count = 0;
  8858. bool saw_leaf_cert = false;
  8859. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8860. if (ctx.cert) {
  8861. callback_count++;
  8862. // We should see at least one certificate (the leaf)
  8863. std::string cn = ctx.subject_cn();
  8864. if (!cn.empty()) { saw_leaf_cert = true; }
  8865. // Verify context fields are populated
  8866. EXPECT_NE(ctx.session, nullptr);
  8867. EXPECT_GE(ctx.depth, 0);
  8868. }
  8869. return true;
  8870. });
  8871. auto res = cli.Get("/test");
  8872. ASSERT_TRUE(res);
  8873. EXPECT_GT(callback_count, 0);
  8874. EXPECT_TRUE(saw_leaf_cert);
  8875. }
  8876. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8877. using httplib::tls::TlsError;
  8878. // Test that verify_error_to_string returns empty for success
  8879. std::string success_str = TlsError::verify_error_to_string(0);
  8880. EXPECT_TRUE(success_str.empty());
  8881. // Test that verify_error_to_string returns non-empty for error codes
  8882. // Using a common error code (certificate expired)
  8883. std::string error_str =
  8884. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8885. EXPECT_FALSE(error_str.empty());
  8886. }
  8887. TEST(SessionVerifierTest, CertificateAccepted) {
  8888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8889. ASSERT_TRUE(svr.is_valid());
  8890. svr.Get("/test", [](const Request &, Response &res) {
  8891. res.set_content("ok", "text/plain");
  8892. });
  8893. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8894. auto se = detail::scope_exit([&] {
  8895. svr.stop();
  8896. t.join();
  8897. });
  8898. svr.wait_until_ready();
  8899. SSLClient cli(HOST, PORT);
  8900. cli.enable_server_certificate_verification(false);
  8901. cli.set_connection_timeout(30);
  8902. bool callback_called = false;
  8903. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8904. EXPECT_NE(session, nullptr);
  8905. callback_called = true;
  8906. return SSLVerifierResponse::CertificateAccepted;
  8907. });
  8908. auto res = cli.Get("/test");
  8909. ASSERT_TRUE(res);
  8910. EXPECT_EQ(200, res->status);
  8911. EXPECT_TRUE(callback_called);
  8912. }
  8913. TEST(SessionVerifierTest, CertificateRejected) {
  8914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8915. ASSERT_TRUE(svr.is_valid());
  8916. svr.Get("/test", [](const Request &, Response &res) {
  8917. res.set_content("ok", "text/plain");
  8918. });
  8919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8920. auto se = detail::scope_exit([&] {
  8921. svr.stop();
  8922. t.join();
  8923. });
  8924. svr.wait_until_ready();
  8925. SSLClient cli(HOST, PORT);
  8926. cli.enable_server_certificate_verification(false);
  8927. cli.set_connection_timeout(30);
  8928. bool callback_called = false;
  8929. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8930. EXPECT_NE(session, nullptr);
  8931. callback_called = true;
  8932. return SSLVerifierResponse::CertificateRejected;
  8933. });
  8934. auto res = cli.Get("/test");
  8935. EXPECT_FALSE(res);
  8936. EXPECT_TRUE(callback_called);
  8937. }
  8938. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8940. ASSERT_TRUE(svr.is_valid());
  8941. svr.Get("/test", [](const Request &, Response &res) {
  8942. res.set_content("ok", "text/plain");
  8943. });
  8944. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8945. auto se = detail::scope_exit([&] {
  8946. svr.stop();
  8947. t.join();
  8948. });
  8949. svr.wait_until_ready();
  8950. // NoDecisionMade with verification disabled should succeed (no default check)
  8951. SSLClient cli(HOST, PORT);
  8952. cli.enable_server_certificate_verification(false);
  8953. cli.set_connection_timeout(30);
  8954. bool callback_called = false;
  8955. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8956. EXPECT_NE(session, nullptr);
  8957. callback_called = true;
  8958. return SSLVerifierResponse::NoDecisionMade;
  8959. });
  8960. auto res = cli.Get("/test");
  8961. ASSERT_TRUE(res);
  8962. EXPECT_EQ(200, res->status);
  8963. EXPECT_TRUE(callback_called);
  8964. }
  8965. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8967. ASSERT_TRUE(svr.is_valid());
  8968. svr.Get("/test", [](const Request &, Response &res) {
  8969. res.set_content("ok", "text/plain");
  8970. });
  8971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8972. auto se = detail::scope_exit([&] {
  8973. svr.stop();
  8974. t.join();
  8975. });
  8976. svr.wait_until_ready();
  8977. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8978. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8979. // so we only check that the request fails, not whether the callback was
  8980. // called.
  8981. SSLClient cli(HOST, PORT);
  8982. cli.enable_server_certificate_verification(true);
  8983. cli.set_connection_timeout(30);
  8984. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8985. EXPECT_NE(session, nullptr);
  8986. return SSLVerifierResponse::NoDecisionMade;
  8987. });
  8988. auto res = cli.Get("/test");
  8989. EXPECT_FALSE(res);
  8990. }
  8991. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8992. // Test SSL server using PemMemory constructor with client CA certificates
  8993. // Read PEM files
  8994. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8995. read_file(SERVER_CERT_FILE, server_cert_pem);
  8996. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8997. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8998. // Create SSLServer with PemMemory constructor including client CA
  8999. SSLServer::PemMemory server_pem = {
  9000. server_cert_pem.c_str(),
  9001. server_cert_pem.size(),
  9002. server_key_pem.c_str(),
  9003. server_key_pem.size(),
  9004. client_ca_pem.c_str(),
  9005. client_ca_pem.size(),
  9006. nullptr // no password for server key
  9007. };
  9008. SSLServer svr(server_pem);
  9009. ASSERT_TRUE(svr.is_valid());
  9010. // No SSL error should be recorded for valid setup
  9011. EXPECT_EQ(0, svr.ssl_last_error());
  9012. // Set up server endpoints
  9013. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9014. res.set_content("ok", "text/plain");
  9015. });
  9016. // Start server in a thread
  9017. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9018. svr.wait_until_ready();
  9019. // Connect with client certificate (using constructor with paths)
  9020. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9021. cli.enable_server_certificate_verification(false);
  9022. auto res = cli.Get("/test-pem-ca");
  9023. ASSERT_TRUE(res);
  9024. EXPECT_EQ(200, res->status);
  9025. EXPECT_EQ("ok", res->body);
  9026. svr.stop();
  9027. server_thread.join();
  9028. }
  9029. #endif
  9030. #ifdef _WIN32
  9031. TEST(CleanupTest, WSACleanup) {
  9032. int ret = WSACleanup();
  9033. ASSERT_EQ(0, ret);
  9034. }
  9035. #endif
  9036. #ifndef CPPHTTPLIB_SSL_ENABLED
  9037. TEST(NoSSLSupport, SimpleInterface) {
  9038. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9039. }
  9040. #endif
  9041. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9042. TEST(InvalidScheme, SimpleInterface) {
  9043. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9044. }
  9045. #endif
  9046. TEST(NoScheme, SimpleInterface) {
  9047. Client cli("yahoo.com:80");
  9048. ASSERT_TRUE(cli.is_valid());
  9049. }
  9050. TEST(SendAPI, SimpleInterface_Online) {
  9051. Client cli("http://yahoo.com");
  9052. Request req;
  9053. req.method = "GET";
  9054. req.path = "/";
  9055. auto res = cli.send(req);
  9056. ASSERT_TRUE(res);
  9057. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9058. }
  9059. TEST(SendAPI, WithParamsInRequest) {
  9060. Server svr;
  9061. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9062. EXPECT_TRUE(req.has_param("test"));
  9063. EXPECT_EQ("test_value", req.get_param_value("test"));
  9064. });
  9065. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9066. auto se = detail::scope_exit([&] {
  9067. svr.stop();
  9068. t.join();
  9069. ASSERT_FALSE(svr.is_running());
  9070. });
  9071. svr.wait_until_ready();
  9072. Client cli(HOST, PORT);
  9073. {
  9074. Request req;
  9075. req.method = "GET";
  9076. req.path = "/";
  9077. req.params.emplace("test", "test_value");
  9078. auto res = cli.send(req);
  9079. ASSERT_TRUE(res);
  9080. }
  9081. {
  9082. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9083. ASSERT_TRUE(res);
  9084. }
  9085. }
  9086. TEST(ClientImplMethods, GetSocketTest) {
  9087. httplib::Server svr;
  9088. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9089. res.status = StatusCode::OK_200;
  9090. });
  9091. auto port = svr.bind_to_any_port("127.0.0.1");
  9092. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9093. auto se = detail::scope_exit([&] {
  9094. svr.stop();
  9095. thread.join();
  9096. ASSERT_FALSE(svr.is_running());
  9097. });
  9098. svr.wait_until_ready();
  9099. {
  9100. httplib::Client cli("127.0.0.1", port);
  9101. cli.set_keep_alive(true);
  9102. // Use the behavior of cpp-httplib of opening the connection
  9103. // only when the first request happens. If that changes,
  9104. // this test would be obsolete.
  9105. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9106. // This also implicitly tests the server. But other tests would fail much
  9107. // earlier than this one to be considered.
  9108. auto res = cli.Get("/");
  9109. ASSERT_TRUE(res);
  9110. EXPECT_EQ(StatusCode::OK_200, res->status);
  9111. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9112. }
  9113. }
  9114. #ifdef CPPHTTPLIB_SSL_ENABLED
  9115. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9116. Client cli("http://yahoo.com");
  9117. auto res = cli.Get("/");
  9118. ASSERT_TRUE(res);
  9119. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9120. cli.set_follow_location(true);
  9121. res = cli.Get("/");
  9122. ASSERT_TRUE(res);
  9123. EXPECT_EQ(StatusCode::OK_200, res->status);
  9124. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9125. }
  9126. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9127. Client cli("https://yahoo.com");
  9128. auto res = cli.Get("/");
  9129. ASSERT_TRUE(res);
  9130. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9131. cli.set_follow_location(true);
  9132. res = cli.Get("/");
  9133. ASSERT_TRUE(res);
  9134. EXPECT_EQ(StatusCode::OK_200, res->status);
  9135. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9136. }
  9137. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9138. Client cli("https://yahoo.com");
  9139. auto res = cli.Get("/");
  9140. ASSERT_TRUE(res);
  9141. ASSERT_FALSE(!res);
  9142. ASSERT_TRUE(res);
  9143. ASSERT_FALSE(res == nullptr);
  9144. ASSERT_TRUE(res != nullptr);
  9145. EXPECT_EQ(Error::Success, res.error());
  9146. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9147. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9148. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9149. cli.set_follow_location(true);
  9150. res = cli.Get("/");
  9151. ASSERT_TRUE(res);
  9152. EXPECT_EQ(Error::Success, res.error());
  9153. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9154. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9157. }
  9158. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9159. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9160. Client cli("https://cdnjs.cloudflare.com");
  9161. auto res =
  9162. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9163. ASSERT_TRUE(res);
  9164. EXPECT_EQ(StatusCode::OK_200, res->status);
  9165. EXPECT_EQ(287630U, res->body.size());
  9166. EXPECT_EQ("application/javascript; charset=utf-8",
  9167. res->get_header_value("Content-Type"));
  9168. }
  9169. #endif
  9170. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9171. #undef REDIR_HOST // Silence compiler warning
  9172. #define REDIR_HOST "https://httpbingo.org"
  9173. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9174. Client cli(REDIR_HOST);
  9175. cli.set_follow_location(true);
  9176. auto res =
  9177. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9178. ASSERT_TRUE(res);
  9179. EXPECT_EQ(StatusCode::OK_200, res->status);
  9180. }
  9181. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9182. Client cli(REDIR_HOST);
  9183. cli.set_follow_location(true);
  9184. Params params;
  9185. params.emplace("url", "http://example.com");
  9186. params.emplace("status_code", "302");
  9187. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9188. ASSERT_TRUE(res);
  9189. EXPECT_EQ(StatusCode::OK_200, res->status);
  9190. }
  9191. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9192. Client cli(REDIR_HOST);
  9193. cli.set_follow_location(true);
  9194. Params params;
  9195. params.emplace("url", "http://example.com");
  9196. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9197. ASSERT_TRUE(res);
  9198. EXPECT_EQ(StatusCode::OK_200, res->status);
  9199. }
  9200. TEST(HttpToHttpsRedirectTest, CertFile) {
  9201. auto ssl_port = PORT + 1;
  9202. Server svr;
  9203. ASSERT_TRUE(svr.is_valid());
  9204. svr.Get("/index", [&](const Request &, Response &res) {
  9205. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9206. "/index");
  9207. svr.stop();
  9208. });
  9209. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9210. ASSERT_TRUE(ssl_svr.is_valid());
  9211. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9212. res.set_content("test", "text/plain");
  9213. ssl_svr.stop();
  9214. });
  9215. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9216. thread t2 =
  9217. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9218. auto se = detail::scope_exit([&] {
  9219. t2.join();
  9220. t.join();
  9221. ASSERT_FALSE(svr.is_running());
  9222. });
  9223. svr.wait_until_ready();
  9224. ssl_svr.wait_until_ready();
  9225. Client cli("127.0.0.1", PORT);
  9226. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9227. cli.enable_server_certificate_verification(true);
  9228. cli.set_follow_location(true);
  9229. cli.set_connection_timeout(30);
  9230. auto res = cli.Get("/index");
  9231. ASSERT_TRUE(res);
  9232. ASSERT_EQ(StatusCode::OK_200, res->status);
  9233. }
  9234. TEST(SSLClientRedirectTest, CertFile) {
  9235. auto ssl_port = PORT + 1;
  9236. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9237. ASSERT_TRUE(ssl_svr1.is_valid());
  9238. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9239. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9240. "/index");
  9241. ssl_svr1.stop();
  9242. });
  9243. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9244. ASSERT_TRUE(ssl_svr2.is_valid());
  9245. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9246. res.set_content("test", "text/plain");
  9247. ssl_svr2.stop();
  9248. });
  9249. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9250. thread t2 =
  9251. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9252. auto se = detail::scope_exit([&] {
  9253. t2.join();
  9254. t.join();
  9255. ASSERT_FALSE(ssl_svr1.is_running());
  9256. });
  9257. ssl_svr1.wait_until_ready();
  9258. ssl_svr2.wait_until_ready();
  9259. SSLClient cli("127.0.0.1", PORT);
  9260. std::string cert;
  9261. read_file(SERVER_CERT2_FILE, cert);
  9262. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9263. cli.enable_server_certificate_verification(true);
  9264. cli.set_follow_location(true);
  9265. cli.set_connection_timeout(30);
  9266. auto res = cli.Get("/index");
  9267. ASSERT_TRUE(res);
  9268. ASSERT_EQ(StatusCode::OK_200, res->status);
  9269. }
  9270. #endif
  9271. #ifdef CPPHTTPLIB_SSL_ENABLED
  9272. // Test that set_ca_cert_store() skips system certs (consistent with
  9273. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9274. // should be trusted - system certs should NOT be loaded.
  9275. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9276. // Load a specific cert that is NOT a system CA cert
  9277. std::string cert;
  9278. read_file(SERVER_CERT2_FILE, cert);
  9279. SSLClient cli("google.com");
  9280. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9281. cli.enable_server_certificate_verification(true);
  9282. // This should FAIL because:
  9283. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9284. // 2. System certs should NOT be loaded when custom store is set
  9285. // If system certs WERE loaded, this would succeed
  9286. auto res = cli.Get("/");
  9287. ASSERT_FALSE(res);
  9288. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9289. }
  9290. TEST(MultipartFormDataTest, LargeData) {
  9291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9292. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9293. const ContentReader &content_reader) {
  9294. if (req.is_multipart_form_data()) {
  9295. std::vector<FormData> items;
  9296. content_reader(
  9297. [&](const FormData &file) {
  9298. items.push_back(file);
  9299. return true;
  9300. },
  9301. [&](const char *data, size_t data_length) {
  9302. items.back().content.append(data, data_length);
  9303. return true;
  9304. });
  9305. EXPECT_TRUE(std::string(items[0].name) == "document");
  9306. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9307. EXPECT_TRUE(items[0].filename == "2MB_data");
  9308. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9309. EXPECT_TRUE(items[1].name == "hello");
  9310. EXPECT_TRUE(items[1].content == "world");
  9311. EXPECT_TRUE(items[1].filename == "");
  9312. EXPECT_TRUE(items[1].content_type == "");
  9313. } else {
  9314. std::string body;
  9315. content_reader([&](const char *data, size_t data_length) {
  9316. body.append(data, data_length);
  9317. return true;
  9318. });
  9319. }
  9320. });
  9321. auto port = svr.bind_to_any_port(HOST);
  9322. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9323. auto se = detail::scope_exit([&] {
  9324. svr.stop();
  9325. t.join();
  9326. ASSERT_FALSE(svr.is_running());
  9327. });
  9328. svr.wait_until_ready();
  9329. {
  9330. std::string data(1024 * 1024 * 2, '.');
  9331. std::stringstream buffer;
  9332. buffer << data;
  9333. SSLClient cli(HOST, port);
  9334. cli.enable_server_certificate_verification(false);
  9335. UploadFormDataItems items{
  9336. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9337. {"hello", "world", "", ""},
  9338. };
  9339. auto res = cli.Post("/post", items);
  9340. ASSERT_TRUE(res);
  9341. ASSERT_EQ(StatusCode::OK_200, res->status);
  9342. }
  9343. }
  9344. TEST(MultipartFormDataTest, DataProviderItems) {
  9345. std::random_device seed_gen;
  9346. std::mt19937 random(seed_gen());
  9347. std::string rand1;
  9348. rand1.resize(1000);
  9349. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9350. std::string rand2;
  9351. rand2.resize(3000);
  9352. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9354. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9355. const ContentReader &content_reader) {
  9356. ASSERT_FALSE(req.is_multipart_form_data());
  9357. std::string body;
  9358. content_reader([&](const char *data, size_t data_length) {
  9359. body.append(data, data_length);
  9360. return true;
  9361. });
  9362. EXPECT_EQ(body, "");
  9363. });
  9364. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9365. const ContentReader &content_reader) {
  9366. ASSERT_TRUE(req.is_multipart_form_data());
  9367. std::vector<FormData> items;
  9368. content_reader(
  9369. [&](const FormData &file) {
  9370. items.push_back(file);
  9371. return true;
  9372. },
  9373. [&](const char *data, size_t data_length) {
  9374. items.back().content.append(data, data_length);
  9375. return true;
  9376. });
  9377. ASSERT_TRUE(items.size() == 2);
  9378. EXPECT_EQ(std::string(items[0].name), "name1");
  9379. EXPECT_EQ(items[0].content, "Testing123");
  9380. EXPECT_EQ(items[0].filename, "filename1");
  9381. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9382. EXPECT_EQ(items[1].name, "name2");
  9383. EXPECT_EQ(items[1].content, "Testing456");
  9384. EXPECT_EQ(items[1].filename, "");
  9385. EXPECT_EQ(items[1].content_type, "");
  9386. });
  9387. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9388. const ContentReader &content_reader) {
  9389. ASSERT_TRUE(req.is_multipart_form_data());
  9390. std::vector<FormData> items;
  9391. content_reader(
  9392. [&](const FormData &file) {
  9393. items.push_back(file);
  9394. return true;
  9395. },
  9396. [&](const char *data, size_t data_length) {
  9397. items.back().content.append(data, data_length);
  9398. return true;
  9399. });
  9400. ASSERT_TRUE(items.size() == 2);
  9401. EXPECT_EQ(items[0].name, "name3");
  9402. EXPECT_EQ(items[0].content, rand1);
  9403. EXPECT_EQ(items[0].filename, "filename3");
  9404. EXPECT_EQ(items[0].content_type, "");
  9405. EXPECT_EQ(items[1].name, "name4");
  9406. EXPECT_EQ(items[1].content, rand2);
  9407. EXPECT_EQ(items[1].filename, "filename4");
  9408. EXPECT_EQ(items[1].content_type, "");
  9409. });
  9410. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9411. const ContentReader &content_reader) {
  9412. ASSERT_TRUE(req.is_multipart_form_data());
  9413. std::vector<FormData> items;
  9414. content_reader(
  9415. [&](const FormData &file) {
  9416. items.push_back(file);
  9417. return true;
  9418. },
  9419. [&](const char *data, size_t data_length) {
  9420. items.back().content.append(data, data_length);
  9421. return true;
  9422. });
  9423. ASSERT_TRUE(items.size() == 4);
  9424. EXPECT_EQ(std::string(items[0].name), "name1");
  9425. EXPECT_EQ(items[0].content, "Testing123");
  9426. EXPECT_EQ(items[0].filename, "filename1");
  9427. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9428. EXPECT_EQ(items[1].name, "name2");
  9429. EXPECT_EQ(items[1].content, "Testing456");
  9430. EXPECT_EQ(items[1].filename, "");
  9431. EXPECT_EQ(items[1].content_type, "");
  9432. EXPECT_EQ(items[2].name, "name3");
  9433. EXPECT_EQ(items[2].content, rand1);
  9434. EXPECT_EQ(items[2].filename, "filename3");
  9435. EXPECT_EQ(items[2].content_type, "");
  9436. EXPECT_EQ(items[3].name, "name4");
  9437. EXPECT_EQ(items[3].content, rand2);
  9438. EXPECT_EQ(items[3].filename, "filename4");
  9439. EXPECT_EQ(items[3].content_type, "");
  9440. });
  9441. auto port = svr.bind_to_any_port("localhost");
  9442. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9443. auto se = detail::scope_exit([&] {
  9444. svr.stop();
  9445. t.join();
  9446. ASSERT_FALSE(svr.is_running());
  9447. });
  9448. svr.wait_until_ready();
  9449. {
  9450. SSLClient cli("localhost", port);
  9451. cli.enable_server_certificate_verification(false);
  9452. UploadFormDataItems items{
  9453. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9454. {"name2", "Testing456", "", ""}, // not a file
  9455. };
  9456. {
  9457. auto res = cli.Post("/post-none", {}, {}, {});
  9458. ASSERT_TRUE(res);
  9459. ASSERT_EQ(StatusCode::OK_200, res->status);
  9460. }
  9461. FormDataProviderItems providers;
  9462. {
  9463. auto res =
  9464. cli.Post("/post-items", {}, items, providers); // empty providers
  9465. ASSERT_TRUE(res);
  9466. ASSERT_EQ(StatusCode::OK_200, res->status);
  9467. }
  9468. providers.push_back({"name3",
  9469. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9470. // test the offset is given correctly at each step
  9471. if (!offset)
  9472. sink.os.write(rand1.data(), 30);
  9473. else if (offset == 30)
  9474. sink.os.write(rand1.data() + 30, 300);
  9475. else if (offset == 330)
  9476. sink.os.write(rand1.data() + 330, 670);
  9477. else if (offset == rand1.size())
  9478. sink.done();
  9479. return true;
  9480. },
  9481. "filename3",
  9482. {}});
  9483. providers.push_back({"name4",
  9484. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9485. // test the offset is given correctly at each step
  9486. if (!offset)
  9487. sink.os.write(rand2.data(), 2000);
  9488. else if (offset == 2000)
  9489. sink.os.write(rand2.data() + 2000, 1);
  9490. else if (offset == 2001)
  9491. sink.os.write(rand2.data() + 2001, 999);
  9492. else if (offset == rand2.size())
  9493. sink.done();
  9494. return true;
  9495. },
  9496. "filename4",
  9497. {}});
  9498. {
  9499. auto res = cli.Post("/post-providers", {}, {}, providers);
  9500. ASSERT_TRUE(res);
  9501. ASSERT_EQ(StatusCode::OK_200, res->status);
  9502. }
  9503. {
  9504. auto res = cli.Post("/post-both", {}, items, providers);
  9505. ASSERT_TRUE(res);
  9506. ASSERT_EQ(StatusCode::OK_200, res->status);
  9507. }
  9508. }
  9509. }
  9510. TEST(MultipartFormDataTest, BadHeader) {
  9511. Server svr;
  9512. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9513. res.set_content("ok", "text/plain");
  9514. });
  9515. thread t = thread([&] { svr.listen(HOST, PORT); });
  9516. auto se = detail::scope_exit([&] {
  9517. svr.stop();
  9518. t.join();
  9519. ASSERT_FALSE(svr.is_running());
  9520. });
  9521. svr.wait_until_ready();
  9522. const std::string body =
  9523. "This is the preamble. It is to be ignored, though it\r\n"
  9524. "is a handy place for composition agents to include an\r\n"
  9525. "explanatory note to non-MIME conformant readers.\r\n"
  9526. "\r\n"
  9527. "\r\n"
  9528. "--simple boundary\r\n"
  9529. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9530. ": BAD...\r\n"
  9531. "\r\n"
  9532. "value1\r\n"
  9533. "--simple boundary\r\n"
  9534. "Content-Disposition: form-data; name=\"field2\"; "
  9535. "filename=\"example.txt\"\r\n"
  9536. "\r\n"
  9537. "value2\r\n"
  9538. "--simple boundary--\r\n"
  9539. "This is the epilogue. It is also to be ignored.\r\n";
  9540. std::string content_type =
  9541. R"(multipart/form-data; boundary="simple boundary")";
  9542. Client cli(HOST, PORT);
  9543. auto res = cli.Post("/post", body, content_type.c_str());
  9544. ASSERT_TRUE(res);
  9545. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9546. }
  9547. TEST(MultipartFormDataTest, WithPreamble) {
  9548. Server svr;
  9549. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9550. res.set_content("ok", "text/plain");
  9551. });
  9552. thread t = thread([&] { svr.listen(HOST, PORT); });
  9553. auto se = detail::scope_exit([&] {
  9554. svr.stop();
  9555. t.join();
  9556. ASSERT_FALSE(svr.is_running());
  9557. });
  9558. svr.wait_until_ready();
  9559. const std::string body =
  9560. "This is the preamble. It is to be ignored, though it\r\n"
  9561. "is a handy place for composition agents to include an\r\n"
  9562. "explanatory note to non-MIME conformant readers.\r\n"
  9563. "\r\n"
  9564. "\r\n"
  9565. "--simple boundary\r\n"
  9566. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9567. "\r\n"
  9568. "value1\r\n"
  9569. "--simple boundary\r\n"
  9570. "Content-Disposition: form-data; name=\"field2\"; "
  9571. "filename=\"example.txt\"\r\n"
  9572. "\r\n"
  9573. "value2\r\n"
  9574. "--simple boundary--\r\n"
  9575. "This is the epilogue. It is also to be ignored.\r\n";
  9576. std::string content_type =
  9577. R"(multipart/form-data; boundary="simple boundary")";
  9578. Client cli(HOST, PORT);
  9579. auto res = cli.Post("/post", body, content_type.c_str());
  9580. ASSERT_TRUE(res);
  9581. EXPECT_EQ(StatusCode::OK_200, res->status);
  9582. }
  9583. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9585. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9586. const ContentReader &content_reader) {
  9587. if (req.is_multipart_form_data()) {
  9588. std::vector<FormData> items;
  9589. content_reader(
  9590. [&](const FormData &file) {
  9591. items.push_back(file);
  9592. return true;
  9593. },
  9594. [&](const char *data, size_t data_length) {
  9595. items.back().content.append(data, data_length);
  9596. return true;
  9597. });
  9598. EXPECT_TRUE(std::string(items[0].name) == "document");
  9599. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9600. EXPECT_TRUE(items[0].filename == "2MB_data");
  9601. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9602. EXPECT_TRUE(items[1].name == "hello");
  9603. EXPECT_TRUE(items[1].content == "world");
  9604. EXPECT_TRUE(items[1].filename == "");
  9605. EXPECT_TRUE(items[1].content_type == "");
  9606. } else {
  9607. std::string body;
  9608. content_reader([&](const char *data, size_t data_length) {
  9609. body.append(data, data_length);
  9610. return true;
  9611. });
  9612. }
  9613. });
  9614. auto port = svr.bind_to_any_port("localhost");
  9615. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9616. auto se = detail::scope_exit([&] {
  9617. svr.stop();
  9618. t.join();
  9619. ASSERT_FALSE(svr.is_running());
  9620. });
  9621. svr.wait_until_ready();
  9622. {
  9623. std::string data(1024 * 1024 * 2, '.');
  9624. std::stringstream buffer;
  9625. buffer << data;
  9626. SSLClient cli("localhost", port);
  9627. cli.enable_server_certificate_verification(false);
  9628. UploadFormDataItems items{
  9629. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9630. {"hello", "world", "", ""},
  9631. };
  9632. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9633. ASSERT_TRUE(res);
  9634. ASSERT_EQ(StatusCode::OK_200, res->status);
  9635. }
  9636. }
  9637. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9638. std::string data(1024 * 1024 * 2, '&');
  9639. std::stringstream buffer;
  9640. buffer << data;
  9641. Client cli("https://localhost:8080");
  9642. UploadFormDataItems items{
  9643. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9644. {"hello", "world", "", ""},
  9645. };
  9646. for (const char &c : " \t\r\n") {
  9647. auto res =
  9648. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9649. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9650. ASSERT_FALSE(res);
  9651. }
  9652. }
  9653. TEST(MultipartFormDataTest, PutFormData) {
  9654. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9655. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9656. const ContentReader &content_reader) {
  9657. if (req.is_multipart_form_data()) {
  9658. std::vector<FormData> items;
  9659. content_reader(
  9660. [&](const FormData &file) {
  9661. items.push_back(file);
  9662. return true;
  9663. },
  9664. [&](const char *data, size_t data_length) {
  9665. items.back().content.append(data, data_length);
  9666. return true;
  9667. });
  9668. EXPECT_TRUE(std::string(items[0].name) == "document");
  9669. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9670. EXPECT_TRUE(items[0].filename == "2MB_data");
  9671. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9672. EXPECT_TRUE(items[1].name == "hello");
  9673. EXPECT_TRUE(items[1].content == "world");
  9674. EXPECT_TRUE(items[1].filename == "");
  9675. EXPECT_TRUE(items[1].content_type == "");
  9676. } else {
  9677. std::string body;
  9678. content_reader([&](const char *data, size_t data_length) {
  9679. body.append(data, data_length);
  9680. return true;
  9681. });
  9682. }
  9683. });
  9684. auto port = svr.bind_to_any_port("localhost");
  9685. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. ASSERT_FALSE(svr.is_running());
  9690. });
  9691. svr.wait_until_ready();
  9692. {
  9693. std::string data(1024 * 1024 * 2, '&');
  9694. std::stringstream buffer;
  9695. buffer << data;
  9696. SSLClient cli("localhost", port);
  9697. cli.enable_server_certificate_verification(false);
  9698. UploadFormDataItems items{
  9699. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9700. {"hello", "world", "", ""},
  9701. };
  9702. auto res = cli.Put("/put", items);
  9703. ASSERT_TRUE(res);
  9704. ASSERT_EQ(StatusCode::OK_200, res->status);
  9705. }
  9706. }
  9707. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9709. svr.Put("/put_customboundary",
  9710. [&](const Request &req, const Response & /*res*/,
  9711. const ContentReader &content_reader) {
  9712. if (req.is_multipart_form_data()) {
  9713. std::vector<FormData> items;
  9714. content_reader(
  9715. [&](const FormData &file) {
  9716. items.push_back(file);
  9717. return true;
  9718. },
  9719. [&](const char *data, size_t data_length) {
  9720. items.back().content.append(data, data_length);
  9721. return true;
  9722. });
  9723. EXPECT_TRUE(std::string(items[0].name) == "document");
  9724. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9725. EXPECT_TRUE(items[0].filename == "2MB_data");
  9726. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9727. EXPECT_TRUE(items[1].name == "hello");
  9728. EXPECT_TRUE(items[1].content == "world");
  9729. EXPECT_TRUE(items[1].filename == "");
  9730. EXPECT_TRUE(items[1].content_type == "");
  9731. } else {
  9732. std::string body;
  9733. content_reader([&](const char *data, size_t data_length) {
  9734. body.append(data, data_length);
  9735. return true;
  9736. });
  9737. }
  9738. });
  9739. auto port = svr.bind_to_any_port("localhost");
  9740. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9741. auto se = detail::scope_exit([&] {
  9742. svr.stop();
  9743. t.join();
  9744. ASSERT_FALSE(svr.is_running());
  9745. });
  9746. svr.wait_until_ready();
  9747. {
  9748. std::string data(1024 * 1024 * 2, '&');
  9749. std::stringstream buffer;
  9750. buffer << data;
  9751. SSLClient cli("localhost", port);
  9752. cli.enable_server_certificate_verification(false);
  9753. UploadFormDataItems items{
  9754. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9755. {"hello", "world", "", ""},
  9756. };
  9757. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9758. ASSERT_TRUE(res);
  9759. ASSERT_EQ(StatusCode::OK_200, res->status);
  9760. }
  9761. }
  9762. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9763. std::string data(1024 * 1024 * 2, '&');
  9764. std::stringstream buffer;
  9765. buffer << data;
  9766. Client cli("https://localhost:8080");
  9767. cli.enable_server_certificate_verification(false);
  9768. UploadFormDataItems items{
  9769. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9770. {"hello", "world", "", ""},
  9771. };
  9772. for (const char &c : " \t\r\n") {
  9773. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9774. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9775. ASSERT_FALSE(res);
  9776. }
  9777. }
  9778. TEST(MultipartFormDataTest, AlternateFilename) {
  9779. auto handled = false;
  9780. Server svr;
  9781. svr.Post("/test", [&](const Request &req, Response &res) {
  9782. ASSERT_EQ(2u, req.form.files.size());
  9783. ASSERT_EQ(1u, req.form.fields.size());
  9784. // Test files
  9785. const auto &file1 = req.form.get_file("file1");
  9786. ASSERT_EQ("file1", file1.name);
  9787. ASSERT_EQ("A.txt", file1.filename);
  9788. ASSERT_EQ("text/plain", file1.content_type);
  9789. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9790. const auto &file2 = req.form.get_file("file2");
  9791. ASSERT_EQ("file2", file2.name);
  9792. ASSERT_EQ("a.html", file2.filename);
  9793. ASSERT_EQ("text/html", file2.content_type);
  9794. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9795. file2.content);
  9796. // Test text field
  9797. const auto &text = req.form.get_field("text");
  9798. ASSERT_EQ("text default", text);
  9799. res.set_content("ok", "text/plain");
  9800. handled = true;
  9801. });
  9802. thread t = thread([&] { svr.listen(HOST, PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. t.join();
  9806. ASSERT_FALSE(svr.is_running());
  9807. ASSERT_TRUE(handled);
  9808. });
  9809. svr.wait_until_ready();
  9810. auto req = "POST /test HTTP/1.1\r\n"
  9811. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9812. "Content-Length: 399\r\n"
  9813. "\r\n"
  9814. "----------\r\n"
  9815. "Content-Disposition: form-data; name=\"text\"\r\n"
  9816. "\r\n"
  9817. "text default\r\n"
  9818. "----------\r\n"
  9819. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9820. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9821. "Content-Type: text/plain\r\n"
  9822. "\r\n"
  9823. "Content of a.txt.\r\n"
  9824. "\r\n"
  9825. "----------\r\n"
  9826. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9827. "\"a.html\"\r\n"
  9828. "Content-Type: text/html\r\n"
  9829. "\r\n"
  9830. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9831. "\r\n"
  9832. "------------\r\n";
  9833. ASSERT_TRUE(send_request(1, req));
  9834. }
  9835. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9836. auto handled = false;
  9837. Server svr;
  9838. svr.Post("/test", [&](const Request &req, Response &res) {
  9839. // Case-insensitive "utf-8''" prefix with a long value
  9840. const auto &file = req.form.get_file("file1");
  9841. ASSERT_EQ("file1", file.name);
  9842. // 8000 chars exercises both the Content-Disposition parser and the
  9843. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9844. // Prior to the fix, std::regex_match on this header would cause O(N)
  9845. // stack recursion in libstdc++, leading to SIGSEGV.
  9846. std::string expected_filename(8000, 'A');
  9847. ASSERT_EQ(expected_filename, file.filename);
  9848. res.set_content("ok", "text/plain");
  9849. handled = true;
  9850. });
  9851. thread t = thread([&] { svr.listen(HOST, PORT); });
  9852. auto se = detail::scope_exit([&] {
  9853. svr.stop();
  9854. t.join();
  9855. ASSERT_FALSE(svr.is_running());
  9856. ASSERT_TRUE(handled);
  9857. });
  9858. svr.wait_until_ready();
  9859. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9860. // Regression test for GHSA-qq6v-r583-3h69
  9861. std::string long_filename(8000, 'A');
  9862. std::string body = "----------\r\n"
  9863. "Content-Disposition: form-data; name=\"file1\"; "
  9864. "filename*=\"Utf-8''" +
  9865. long_filename +
  9866. "\"\r\n"
  9867. "\r\n"
  9868. "hello\r\n"
  9869. "------------\r\n";
  9870. auto req = "POST /test HTTP/1.1\r\n"
  9871. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9872. "Content-Length: " +
  9873. std::to_string(body.size()) + "\r\n\r\n" + body;
  9874. ASSERT_TRUE(send_request(1, req));
  9875. }
  9876. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9877. auto handled = false;
  9878. Server svr;
  9879. svr.Post("/test", [&](const Request &req, Response &) {
  9880. ASSERT_EQ(2u, req.form.fields.size());
  9881. const auto &text1 = req.form.get_field("text1");
  9882. ASSERT_EQ("text1", text1);
  9883. const auto &text2 = req.form.get_field("text2");
  9884. ASSERT_EQ("text2", text2);
  9885. handled = true;
  9886. });
  9887. thread t = thread([&] { svr.listen(HOST, PORT); });
  9888. auto se = detail::scope_exit([&] {
  9889. svr.stop();
  9890. t.join();
  9891. ASSERT_FALSE(svr.is_running());
  9892. ASSERT_TRUE(handled);
  9893. });
  9894. svr.wait_until_ready();
  9895. auto req = "POST /test HTTP/1.1\r\n"
  9896. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9897. "Content-Length: 146\r\n"
  9898. "\r\n----------\r\n"
  9899. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9900. "\r\n"
  9901. "text1"
  9902. "\r\n----------\r\n"
  9903. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9904. "\r\n"
  9905. "text2"
  9906. "\r\n------------";
  9907. std::string response;
  9908. ASSERT_TRUE(send_request(1, req, &response));
  9909. ASSERT_EQ("200", response.substr(9, 3));
  9910. }
  9911. TEST(MultipartFormDataTest, ContentLength) {
  9912. auto handled = false;
  9913. Server svr;
  9914. svr.Post("/test", [&](const Request &req, Response &) {
  9915. ASSERT_EQ(2u, req.form.fields.size());
  9916. const auto &text1 = req.form.get_field("text1");
  9917. ASSERT_EQ("text1", text1);
  9918. const auto &text2 = req.form.get_field("text2");
  9919. ASSERT_EQ("text2", text2);
  9920. handled = true;
  9921. });
  9922. thread t = thread([&] { svr.listen(HOST, PORT); });
  9923. auto se = detail::scope_exit([&] {
  9924. svr.stop();
  9925. t.join();
  9926. ASSERT_FALSE(svr.is_running());
  9927. ASSERT_TRUE(handled);
  9928. });
  9929. svr.wait_until_ready();
  9930. auto req = "POST /test HTTP/1.1\r\n"
  9931. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9932. "Content-Length: 167\r\n"
  9933. "\r\n----------\r\n"
  9934. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9935. "Content-Length: 5\r\n"
  9936. "\r\n"
  9937. "text1"
  9938. "\r\n----------\r\n"
  9939. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9940. "\r\n"
  9941. "text2"
  9942. "\r\n------------\r\n";
  9943. std::string response;
  9944. ASSERT_TRUE(send_request(1, req, &response));
  9945. ASSERT_EQ("200", response.substr(9, 3));
  9946. }
  9947. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9948. auto handled = false;
  9949. Server svr;
  9950. svr.Post("/test", [&](const Request &req, Response &) {
  9951. ASSERT_EQ(2u, req.form.fields.size());
  9952. const auto &text1 = req.form.get_field("text1");
  9953. ASSERT_EQ("text1", text1);
  9954. // TODO: Add header access for text fields if needed
  9955. const auto &text2 = req.form.get_field("text2");
  9956. ASSERT_EQ("text2", text2);
  9957. // TODO: Header access for text fields needs to be implemented
  9958. // auto &headers = it->second.headers;
  9959. // ASSERT_EQ(3U, headers.size());
  9960. // auto custom_header = headers.find("x-whatever");
  9961. // ASSERT_TRUE(custom_header != headers.end());
  9962. // ASSERT_NE("customvalue", custom_header->second);
  9963. // ASSERT_EQ("CustomValue", custom_header->second);
  9964. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9965. handled = true;
  9966. });
  9967. thread t = thread([&] { svr.listen(HOST, PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. t.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. ASSERT_TRUE(handled);
  9973. });
  9974. svr.wait_until_ready();
  9975. auto req = "POST /test HTTP/1.1\r\n"
  9976. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9977. "Content-Length: 232\r\n"
  9978. "\r\n----------\r\n"
  9979. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9980. "Content-Length: 5\r\n"
  9981. "X-Test: 1\r\n"
  9982. "\r\n"
  9983. "text1"
  9984. "\r\n----------\r\n"
  9985. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9986. "Content-Type: text/plain\r\n"
  9987. "X-Whatever: CustomValue\r\n"
  9988. "\r\n"
  9989. "text2"
  9990. "\r\n------------\r\n"
  9991. "That should be disregarded. Not even read";
  9992. std::string response;
  9993. ASSERT_TRUE(send_request(1, req, &response));
  9994. ASSERT_EQ("200", response.substr(9, 3));
  9995. }
  9996. TEST(MultipartFormDataTest, LargeHeader) {
  9997. auto handled = false;
  9998. Server svr;
  9999. svr.Post("/test", [&](const Request &req, Response &) {
  10000. ASSERT_EQ(1u, req.form.fields.size());
  10001. const auto &text = req.form.get_field("name1");
  10002. ASSERT_EQ("text1", text);
  10003. handled = true;
  10004. });
  10005. thread t = thread([&] { svr.listen(HOST, PORT); });
  10006. auto se = detail::scope_exit([&] {
  10007. svr.stop();
  10008. t.join();
  10009. ASSERT_FALSE(svr.is_running());
  10010. ASSERT_TRUE(handled);
  10011. });
  10012. svr.wait_until_ready();
  10013. auto boundary = std::string("cpp-httplib-multipart-data");
  10014. std::string content = "--" + boundary +
  10015. "\r\n"
  10016. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10017. "\r\n"
  10018. "text1\r\n"
  10019. "--" +
  10020. boundary + "--\r\n";
  10021. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10022. "Content-Type: multipart/form-data;boundary=" +
  10023. boundary +
  10024. "\r\n"
  10025. "Content-Length: " +
  10026. std::to_string(content.size()) +
  10027. "\r\n"
  10028. "Dummy-Header: ";
  10029. std::string header_suffix = "\r\n"
  10030. "\r\n";
  10031. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10032. size_t header_dummy_size =
  10033. read_buff_size -
  10034. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10035. auto header_dummy = std::string(header_dummy_size, '@');
  10036. auto req = header_prefix + header_dummy + header_suffix + content;
  10037. std::string response;
  10038. ASSERT_TRUE(send_request(1, req, &response));
  10039. ASSERT_EQ("200", response.substr(9, 3));
  10040. }
  10041. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10042. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10043. // (not chunked Transfer-Encoding) after the streaming refactor.
  10044. auto handled = false;
  10045. Server svr;
  10046. svr.Post("/upload", [&](const Request &req, Response &res) {
  10047. auto cl_it = req.headers.find("Content-Length");
  10048. EXPECT_TRUE(cl_it != req.headers.end());
  10049. auto te_it = req.headers.find("Transfer-Encoding");
  10050. EXPECT_TRUE(te_it == req.headers.end());
  10051. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10052. res.set_content("ok", "text/plain");
  10053. handled = true;
  10054. });
  10055. auto port = svr.bind_to_any_port(HOST);
  10056. auto t = thread([&] { svr.listen_after_bind(); });
  10057. auto se = detail::scope_exit([&] {
  10058. svr.stop();
  10059. t.join();
  10060. ASSERT_FALSE(svr.is_running());
  10061. ASSERT_TRUE(handled);
  10062. });
  10063. svr.wait_until_ready();
  10064. UploadFormDataItems items = {
  10065. {"field1", "hello", "", "text/plain"},
  10066. {"file1", "world", "test.txt", "application/octet-stream"},
  10067. };
  10068. Client cli(HOST, port);
  10069. auto res = cli.Post("/upload", {}, items);
  10070. ASSERT_TRUE(res);
  10071. EXPECT_EQ(StatusCode::OK_200, res->status);
  10072. }
  10073. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10074. // Verify that make_multipart_content_provider coalesces many small segments
  10075. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10076. constexpr size_t kItemCount = 1000;
  10077. UploadFormDataItems items;
  10078. items.reserve(kItemCount);
  10079. for (size_t i = 0; i < kItemCount; i++) {
  10080. items.push_back(
  10081. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10082. }
  10083. const std::string boundary = "----test-boundary";
  10084. auto content_length = detail::get_multipart_content_length(items, boundary);
  10085. auto provider = detail::make_multipart_content_provider(items, boundary);
  10086. // Drive the provider the same way write_content_with_progress does
  10087. size_t write_count = 0;
  10088. size_t total_bytes = 0;
  10089. DataSink sink;
  10090. size_t offset = 0;
  10091. sink.write = [&](const char *d, size_t l) -> bool {
  10092. (void)d;
  10093. write_count++;
  10094. total_bytes += l;
  10095. offset += l;
  10096. return true;
  10097. };
  10098. sink.is_writable = []() -> bool { return true; };
  10099. while (offset < content_length) {
  10100. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10101. }
  10102. EXPECT_EQ(content_length, total_bytes);
  10103. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10104. // With buffering into 64KB blocks, write_count should be much smaller.
  10105. auto segment_count = 3 * kItemCount + 1;
  10106. EXPECT_LT(write_count, segment_count / 10);
  10107. }
  10108. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10109. // Integration test: send many UploadFormDataItems and verify the server
  10110. // receives all of them correctly (#2410).
  10111. constexpr size_t kItemCount = 500;
  10112. auto handled = false;
  10113. Server svr;
  10114. svr.Post("/upload", [&](const Request &req, Response &res) {
  10115. EXPECT_EQ(kItemCount, req.form.fields.size());
  10116. for (size_t i = 0; i < kItemCount; i++) {
  10117. auto key = "field" + std::to_string(i);
  10118. auto val = "value" + std::to_string(i);
  10119. auto it = req.form.fields.find(key);
  10120. if (it != req.form.fields.end()) {
  10121. EXPECT_EQ(val, it->second.content);
  10122. } else {
  10123. ADD_FAILURE() << "Missing field: " << key;
  10124. }
  10125. }
  10126. res.set_content("ok", "text/plain");
  10127. handled = true;
  10128. });
  10129. auto port = svr.bind_to_any_port(HOST);
  10130. auto t = thread([&] { svr.listen_after_bind(); });
  10131. auto se = detail::scope_exit([&] {
  10132. svr.stop();
  10133. t.join();
  10134. ASSERT_FALSE(svr.is_running());
  10135. ASSERT_TRUE(handled);
  10136. });
  10137. svr.wait_until_ready();
  10138. UploadFormDataItems items;
  10139. items.reserve(kItemCount);
  10140. for (size_t i = 0; i < kItemCount; i++) {
  10141. items.push_back(
  10142. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10143. }
  10144. Client cli(HOST, port);
  10145. auto res = cli.Post("/upload", items);
  10146. ASSERT_TRUE(res);
  10147. EXPECT_EQ(StatusCode::OK_200, res->status);
  10148. }
  10149. TEST(MultipartFormDataTest, MakeFileProvider) {
  10150. // Verify make_file_provider sends a file's contents correctly.
  10151. const std::string file_content(4096, 'Z');
  10152. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10153. {
  10154. std::ofstream ofs(tmp_path, std::ios::binary);
  10155. ofs.write(file_content.data(),
  10156. static_cast<std::streamsize>(file_content.size()));
  10157. }
  10158. auto handled = false;
  10159. Server svr;
  10160. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10161. const ContentReader &content_reader) {
  10162. ASSERT_TRUE(req.is_multipart_form_data());
  10163. std::vector<FormData> items;
  10164. content_reader(
  10165. [&](const FormData &file) {
  10166. items.push_back(file);
  10167. return true;
  10168. },
  10169. [&](const char *data, size_t data_length) {
  10170. items.back().content.append(data, data_length);
  10171. return true;
  10172. });
  10173. ASSERT_EQ(1u, items.size());
  10174. EXPECT_EQ("myfile", items[0].name);
  10175. EXPECT_EQ("data.bin", items[0].filename);
  10176. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10177. EXPECT_EQ(file_content, items[0].content);
  10178. handled = true;
  10179. });
  10180. auto port = svr.bind_to_any_port(HOST);
  10181. auto t = thread([&] { svr.listen_after_bind(); });
  10182. auto se = detail::scope_exit([&] {
  10183. svr.stop();
  10184. t.join();
  10185. ASSERT_FALSE(svr.is_running());
  10186. ASSERT_TRUE(handled);
  10187. std::remove(tmp_path.c_str());
  10188. });
  10189. svr.wait_until_ready();
  10190. FormDataProviderItems providers;
  10191. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10192. "application/octet-stream"));
  10193. Client cli(HOST, port);
  10194. auto res = cli.Post("/upload", {}, {}, providers);
  10195. ASSERT_TRUE(res);
  10196. EXPECT_EQ(StatusCode::OK_200, res->status);
  10197. }
  10198. TEST(MakeFileBodyTest, Basic) {
  10199. const std::string file_content(4096, 'Z');
  10200. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10201. {
  10202. std::ofstream ofs(tmp_path, std::ios::binary);
  10203. ofs.write(file_content.data(),
  10204. static_cast<std::streamsize>(file_content.size()));
  10205. }
  10206. auto handled = false;
  10207. Server svr;
  10208. svr.Post("/upload", [&](const Request &req, Response &res) {
  10209. EXPECT_EQ(file_content, req.body);
  10210. handled = true;
  10211. res.status = StatusCode::OK_200;
  10212. });
  10213. auto port = svr.bind_to_any_port(HOST);
  10214. auto t = thread([&] { svr.listen_after_bind(); });
  10215. auto se = detail::scope_exit([&] {
  10216. svr.stop();
  10217. t.join();
  10218. ASSERT_FALSE(svr.is_running());
  10219. ASSERT_TRUE(handled);
  10220. std::remove(tmp_path.c_str());
  10221. });
  10222. svr.wait_until_ready();
  10223. auto fb = make_file_body(tmp_path);
  10224. ASSERT_GT(fb.first, 0u);
  10225. Client cli(HOST, port);
  10226. auto res =
  10227. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10228. ASSERT_TRUE(res);
  10229. EXPECT_EQ(StatusCode::OK_200, res->status);
  10230. }
  10231. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10232. static constexpr unsigned int number_of_tasks{1000000};
  10233. std::atomic_uint count{0};
  10234. std::unique_ptr<TaskQueue> task_queue{
  10235. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10236. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10237. auto queued = task_queue->enqueue(
  10238. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10239. EXPECT_TRUE(queued);
  10240. }
  10241. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10242. task_queue->shutdown();
  10243. #else
  10244. EXPECT_NO_THROW(task_queue->shutdown());
  10245. #endif
  10246. EXPECT_EQ(number_of_tasks, count.load());
  10247. }
  10248. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10249. static constexpr unsigned int number_of_tasks{1000000};
  10250. static constexpr unsigned int qlimit{2};
  10251. unsigned int queued_count{0};
  10252. std::atomic_uint count{0};
  10253. std::unique_ptr<TaskQueue> task_queue{
  10254. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10255. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10256. if (task_queue->enqueue(
  10257. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10258. queued_count++;
  10259. }
  10260. }
  10261. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10262. task_queue->shutdown();
  10263. #else
  10264. EXPECT_NO_THROW(task_queue->shutdown());
  10265. #endif
  10266. EXPECT_EQ(queued_count, count.load());
  10267. EXPECT_TRUE(queued_count <= number_of_tasks);
  10268. EXPECT_TRUE(queued_count >= qlimit);
  10269. }
  10270. TEST(TaskQueueTest, MaxQueuedRequests) {
  10271. static constexpr unsigned int qlimit{3};
  10272. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10273. std::condition_variable sem_cv;
  10274. std::mutex sem_mtx;
  10275. int credits = 0;
  10276. bool queued;
  10277. /* Fill up the queue with tasks that will block until we give them credits to
  10278. * complete. */
  10279. for (unsigned int n = 0; n <= qlimit;) {
  10280. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10281. std::unique_lock<std::mutex> lock(sem_mtx);
  10282. while (credits <= 0) {
  10283. sem_cv.wait(lock);
  10284. }
  10285. /* Consume the credit and signal the test code if they are all gone. */
  10286. if (--credits == 0) { sem_cv.notify_one(); }
  10287. });
  10288. if (n < qlimit) {
  10289. /* The first qlimit enqueues must succeed. */
  10290. EXPECT_TRUE(queued);
  10291. } else {
  10292. /* The last one will succeed only when the worker thread
  10293. * starts and dequeues the first blocking task. Although
  10294. * not necessary for the correctness of this test, we sleep for
  10295. * a short while to avoid busy waiting. */
  10296. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10297. }
  10298. if (queued) { n++; }
  10299. }
  10300. /* Further enqueues must fail since the queue is full. */
  10301. for (auto i = 0; i < 4; i++) {
  10302. queued = task_queue->enqueue([] {});
  10303. EXPECT_FALSE(queued);
  10304. }
  10305. /* Give the credits to allow the previous tasks to complete. */
  10306. {
  10307. std::unique_lock<std::mutex> lock(sem_mtx);
  10308. credits += qlimit + 1;
  10309. }
  10310. sem_cv.notify_all();
  10311. /* Wait for all the credits to be consumed. */
  10312. {
  10313. std::unique_lock<std::mutex> lock(sem_mtx);
  10314. while (credits > 0) {
  10315. sem_cv.wait(lock);
  10316. }
  10317. }
  10318. /* Check that we are able again to enqueue at least qlimit tasks. */
  10319. for (unsigned int i = 0; i < qlimit; i++) {
  10320. queued = task_queue->enqueue([] {});
  10321. EXPECT_TRUE(queued);
  10322. }
  10323. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10324. task_queue->shutdown();
  10325. #else
  10326. EXPECT_NO_THROW(task_queue->shutdown());
  10327. #endif
  10328. }
  10329. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10330. Server svr;
  10331. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10332. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10333. });
  10334. svr.Get("/hello", [](const Request &req, Response &res) {
  10335. res.set_content(req.get_param_value("key"), "text/plain");
  10336. });
  10337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10338. auto se = detail::scope_exit([&] {
  10339. svr.stop();
  10340. thread.join();
  10341. ASSERT_FALSE(svr.is_running());
  10342. });
  10343. svr.wait_until_ready();
  10344. {
  10345. Client cli(HOST, PORT);
  10346. cli.set_follow_location(true);
  10347. auto res = cli.Get("/");
  10348. ASSERT_TRUE(res);
  10349. EXPECT_EQ(StatusCode::OK_200, res->status);
  10350. EXPECT_EQ("val&key2=val2", res->body);
  10351. }
  10352. }
  10353. #endif
  10354. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10355. Server svr;
  10356. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10357. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10358. });
  10359. svr.Get("/hello", [](const Request &req, Response &res) {
  10360. res.set_content(req.get_param_value("key"), "text/plain");
  10361. });
  10362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10363. auto se = detail::scope_exit([&] {
  10364. svr.stop();
  10365. thread.join();
  10366. ASSERT_FALSE(svr.is_running());
  10367. });
  10368. svr.wait_until_ready();
  10369. {
  10370. Client cli(HOST, PORT);
  10371. cli.set_follow_location(true);
  10372. auto res = cli.Get("/");
  10373. ASSERT_TRUE(res);
  10374. EXPECT_EQ(StatusCode::OK_200, res->status);
  10375. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10376. }
  10377. }
  10378. TEST(RedirectTest, RedirectWithPlusInPath) {
  10379. Server svr;
  10380. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10381. res.set_redirect("/a+b");
  10382. });
  10383. // Route pattern uses regex; escape + as \\+
  10384. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10385. res.set_content(req.path, "text/plain");
  10386. });
  10387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10388. auto se = detail::scope_exit([&] {
  10389. svr.stop();
  10390. thread.join();
  10391. ASSERT_FALSE(svr.is_running());
  10392. });
  10393. svr.wait_until_ready();
  10394. {
  10395. Client cli(HOST, PORT);
  10396. cli.set_follow_location(true);
  10397. auto res = cli.Get("/");
  10398. ASSERT_TRUE(res);
  10399. EXPECT_EQ(StatusCode::OK_200, res->status);
  10400. EXPECT_EQ("/a+b", res->body);
  10401. }
  10402. }
  10403. #ifdef CPPHTTPLIB_SSL_ENABLED
  10404. TEST(RedirectTest, Issue2185_Online) {
  10405. SSLClient client("github.com");
  10406. client.set_follow_location(true);
  10407. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10408. "Coollab-Windows.zip");
  10409. ASSERT_TRUE(res);
  10410. EXPECT_EQ(StatusCode::OK_200, res->status);
  10411. EXPECT_EQ(9920427U, res->body.size());
  10412. }
  10413. #endif
  10414. TEST(VulnerabilityTest, CRLFInjection) {
  10415. Server svr;
  10416. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10417. res.set_content("Hello 1", "text/plain");
  10418. });
  10419. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10420. res.set_content("Hello 2", "text/plain");
  10421. });
  10422. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10423. res.set_content("Hello 3", "text/plain");
  10424. });
  10425. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10426. res.set_content("Hello 4", "text/plain");
  10427. });
  10428. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10429. for (const auto &x : req.headers) {
  10430. auto key = x.first;
  10431. EXPECT_STRNE("evil", key.c_str());
  10432. }
  10433. });
  10434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10435. auto se = detail::scope_exit([&] {
  10436. svr.stop();
  10437. thread.join();
  10438. ASSERT_FALSE(svr.is_running());
  10439. });
  10440. svr.wait_until_ready();
  10441. {
  10442. Client cli(HOST, PORT);
  10443. cli.Post("/test1", "A=B",
  10444. "application/x-www-form-urlencoded\r\nevil: hello1");
  10445. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10446. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10447. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10448. }
  10449. }
  10450. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10451. auto server_thread = std::thread([] {
  10452. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10453. default_socket_options(srv);
  10454. sockaddr_in addr{};
  10455. addr.sin_family = AF_INET;
  10456. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10457. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10458. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10459. ::listen(srv, 1);
  10460. sockaddr_in cli_addr{};
  10461. socklen_t cli_len = sizeof(cli_addr);
  10462. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10463. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10464. std::string buf_all;
  10465. char buf[2048];
  10466. ssize_t n;
  10467. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10468. buf_all.append(buf, static_cast<size_t>(n));
  10469. size_t pos;
  10470. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10471. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10472. auto e = request_block.find("\r\n");
  10473. if (e != std::string::npos) {
  10474. auto request_line = request_block.substr(0, e);
  10475. std::string msg =
  10476. "CRLF injection detected in request line: '" + request_line + "'";
  10477. EXPECT_FALSE(true) << msg;
  10478. }
  10479. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10480. ::send(cli,
  10481. #ifdef _WIN32
  10482. static_cast<const char *>(resp.c_str()),
  10483. static_cast<int>(resp.size()),
  10484. #else
  10485. resp.c_str(), resp.size(),
  10486. #endif
  10487. 0);
  10488. buf_all.erase(0, pos + 4);
  10489. }
  10490. }
  10491. detail::close_socket(cli);
  10492. detail::close_socket(srv);
  10493. });
  10494. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10495. auto cli = Client("127.0.0.1", PORT + 1);
  10496. auto headers = Headers{
  10497. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10498. {"Connection", "keep-alive"}};
  10499. auto res = cli.Get("/hi", headers);
  10500. EXPECT_FALSE(res);
  10501. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10502. server_thread.join();
  10503. }
  10504. TEST(PathParamsTest, StaticMatch) {
  10505. const auto pattern = "/users/all";
  10506. detail::PathParamsMatcher matcher(pattern);
  10507. Request request;
  10508. request.path = "/users/all";
  10509. ASSERT_TRUE(matcher.match(request));
  10510. std::unordered_map<std::string, std::string> expected_params = {};
  10511. EXPECT_EQ(request.path_params, expected_params);
  10512. }
  10513. TEST(PathParamsTest, StaticMismatch) {
  10514. const auto pattern = "/users/all";
  10515. detail::PathParamsMatcher matcher(pattern);
  10516. Request request;
  10517. request.path = "/users/1";
  10518. ASSERT_FALSE(matcher.match(request));
  10519. }
  10520. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10521. const auto pattern = "/users/:id/subscriptions";
  10522. detail::PathParamsMatcher matcher(pattern);
  10523. Request request;
  10524. request.path = "/users/42/subscriptions";
  10525. ASSERT_TRUE(matcher.match(request));
  10526. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10527. EXPECT_EQ(request.path_params, expected_params);
  10528. }
  10529. TEST(PathParamsTest, SingleParamInTheEnd) {
  10530. const auto pattern = "/users/:id";
  10531. detail::PathParamsMatcher matcher(pattern);
  10532. Request request;
  10533. request.path = "/users/24";
  10534. ASSERT_TRUE(matcher.match(request));
  10535. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10536. EXPECT_EQ(request.path_params, expected_params);
  10537. }
  10538. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10539. const auto pattern = "/users/:id/";
  10540. detail::PathParamsMatcher matcher(pattern);
  10541. Request request;
  10542. request.path = "/users/42/";
  10543. ASSERT_TRUE(matcher.match(request));
  10544. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10545. EXPECT_EQ(request.path_params, expected_params);
  10546. }
  10547. TEST(PathParamsTest, EmptyParam) {
  10548. const auto pattern = "/users/:id/";
  10549. detail::PathParamsMatcher matcher(pattern);
  10550. Request request;
  10551. request.path = "/users//";
  10552. ASSERT_TRUE(matcher.match(request));
  10553. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10554. EXPECT_EQ(request.path_params, expected_params);
  10555. }
  10556. TEST(PathParamsTest, FragmentMismatch) {
  10557. const auto pattern = "/users/:id/";
  10558. detail::PathParamsMatcher matcher(pattern);
  10559. Request request;
  10560. request.path = "/admins/24/";
  10561. ASSERT_FALSE(matcher.match(request));
  10562. }
  10563. TEST(PathParamsTest, ExtraFragments) {
  10564. const auto pattern = "/users/:id";
  10565. detail::PathParamsMatcher matcher(pattern);
  10566. Request request;
  10567. request.path = "/users/42/subscriptions";
  10568. ASSERT_FALSE(matcher.match(request));
  10569. }
  10570. TEST(PathParamsTest, MissingTrailingParam) {
  10571. const auto pattern = "/users/:id";
  10572. detail::PathParamsMatcher matcher(pattern);
  10573. Request request;
  10574. request.path = "/users";
  10575. ASSERT_FALSE(matcher.match(request));
  10576. }
  10577. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10578. const auto pattern = "/users/:id/subscriptions";
  10579. detail::PathParamsMatcher matcher(pattern);
  10580. Request request;
  10581. request.path = "/users/subscriptions";
  10582. ASSERT_FALSE(matcher.match(request));
  10583. }
  10584. TEST(PathParamsTest, MultipleParams) {
  10585. const auto pattern = "/users/:userid/subscriptions/:subid";
  10586. detail::PathParamsMatcher matcher(pattern);
  10587. Request request;
  10588. request.path = "/users/42/subscriptions/2";
  10589. ASSERT_TRUE(matcher.match(request));
  10590. std::unordered_map<std::string, std::string> expected_params = {
  10591. {"userid", "42"}, {"subid", "2"}};
  10592. EXPECT_EQ(request.path_params, expected_params);
  10593. }
  10594. TEST(PathParamsTest, SequenceOfParams) {
  10595. const auto pattern = "/values/:x/:y/:z";
  10596. detail::PathParamsMatcher matcher(pattern);
  10597. Request request;
  10598. request.path = "/values/1/2/3";
  10599. ASSERT_TRUE(matcher.match(request));
  10600. std::unordered_map<std::string, std::string> expected_params = {
  10601. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10602. EXPECT_EQ(request.path_params, expected_params);
  10603. }
  10604. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10605. const auto pattern = "/prefix:suffix";
  10606. detail::PathParamsMatcher matcher(pattern);
  10607. Request request;
  10608. request.path = "/prefix:suffix";
  10609. ASSERT_TRUE(matcher.match(request));
  10610. const std::unordered_map<std::string, std::string> expected_params = {};
  10611. EXPECT_EQ(request.path_params, expected_params);
  10612. }
  10613. TEST(ParseUrlTest, VariousPatterns) {
  10614. {
  10615. detail::UrlComponents uc;
  10616. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10617. EXPECT_EQ("http", uc.scheme);
  10618. EXPECT_EQ("example.com", uc.host);
  10619. EXPECT_EQ("8080", uc.port);
  10620. EXPECT_EQ("/path", uc.path);
  10621. EXPECT_EQ("?q=1", uc.query);
  10622. }
  10623. {
  10624. detail::UrlComponents uc;
  10625. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10626. EXPECT_EQ("https", uc.scheme);
  10627. EXPECT_EQ("example.com", uc.host);
  10628. EXPECT_TRUE(uc.port.empty());
  10629. EXPECT_EQ("/path", uc.path);
  10630. }
  10631. {
  10632. detail::UrlComponents uc;
  10633. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10634. EXPECT_EQ("::1", uc.host);
  10635. EXPECT_EQ("8080", uc.port);
  10636. EXPECT_EQ("/path", uc.path);
  10637. }
  10638. {
  10639. detail::UrlComponents uc;
  10640. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10641. }
  10642. {
  10643. detail::UrlComponents uc;
  10644. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10645. EXPECT_TRUE(uc.scheme.empty());
  10646. EXPECT_EQ("example.com", uc.host);
  10647. EXPECT_EQ("/path", uc.path);
  10648. EXPECT_EQ("?q=1", uc.query);
  10649. }
  10650. {
  10651. detail::UrlComponents uc;
  10652. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10653. EXPECT_TRUE(uc.host.empty());
  10654. EXPECT_EQ("/path", uc.path);
  10655. EXPECT_EQ("?q=1", uc.query);
  10656. }
  10657. {
  10658. detail::UrlComponents uc;
  10659. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10660. EXPECT_EQ("example.com", uc.host);
  10661. EXPECT_EQ("8080", uc.port);
  10662. }
  10663. {
  10664. // Unix socket path — must not be parsed as host
  10665. detail::UrlComponents uc;
  10666. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  10667. EXPECT_TRUE(uc.host.empty());
  10668. }
  10669. {
  10670. detail::UrlComponents uc;
  10671. ASSERT_TRUE(detail::parse_url("", uc));
  10672. EXPECT_TRUE(uc.host.empty());
  10673. EXPECT_TRUE(uc.path.empty());
  10674. }
  10675. {
  10676. detail::UrlComponents uc;
  10677. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  10678. }
  10679. {
  10680. detail::UrlComponents uc;
  10681. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  10682. }
  10683. {
  10684. // Accepted by parse_url; callers restrict to http/https
  10685. detail::UrlComponents uc;
  10686. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  10687. EXPECT_EQ("ftp", uc.scheme);
  10688. }
  10689. {
  10690. detail::UrlComponents uc;
  10691. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  10692. }
  10693. {
  10694. detail::UrlComponents uc;
  10695. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  10696. }
  10697. }
  10698. TEST(ParseUrlTest, FragmentHandling) {
  10699. {
  10700. detail::UrlComponents uc;
  10701. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  10702. EXPECT_EQ("/path", uc.path);
  10703. EXPECT_TRUE(uc.query.empty());
  10704. }
  10705. {
  10706. detail::UrlComponents uc;
  10707. ASSERT_TRUE(detail::parse_url("#frag", uc));
  10708. EXPECT_TRUE(uc.path.empty());
  10709. EXPECT_TRUE(uc.query.empty());
  10710. }
  10711. }
  10712. TEST(ParseUrlTest, UserinfoHandling) {
  10713. // Userinfo with @ but no colon — host includes @
  10714. detail::UrlComponents uc;
  10715. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  10716. EXPECT_EQ("user@host.com", uc.host);
  10717. EXPECT_EQ("/path", uc.path);
  10718. }
  10719. TEST(ParseUrlTest, IPv6EdgeCases) {
  10720. {
  10721. detail::UrlComponents uc;
  10722. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  10723. EXPECT_TRUE(uc.scheme.empty());
  10724. EXPECT_EQ("::1", uc.host);
  10725. EXPECT_EQ("8080", uc.port);
  10726. }
  10727. {
  10728. // Zone ID '%25' is not in [a-fA-F0-9:]
  10729. detail::UrlComponents uc;
  10730. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  10731. }
  10732. }
  10733. TEST(ParseUrlTest, SchemeEdgeCases) {
  10734. {
  10735. detail::UrlComponents uc;
  10736. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  10737. }
  10738. {
  10739. detail::UrlComponents uc;
  10740. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  10741. }
  10742. {
  10743. detail::UrlComponents uc;
  10744. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  10745. }
  10746. }
  10747. TEST(ParseUrlTest, PortEdgeCases) {
  10748. {
  10749. detail::UrlComponents uc;
  10750. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  10751. EXPECT_TRUE(uc.port.empty());
  10752. EXPECT_EQ("/path", uc.path);
  10753. }
  10754. {
  10755. // parse_url accepts any port string; validation is done by parse_port
  10756. detail::UrlComponents uc;
  10757. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  10758. EXPECT_EQ("abc", uc.port);
  10759. }
  10760. }
  10761. TEST(ParseUrlTest, WebSocketPatterns) {
  10762. {
  10763. detail::UrlComponents uc;
  10764. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  10765. EXPECT_EQ("ws", uc.scheme);
  10766. EXPECT_EQ("echo.example.com", uc.host);
  10767. EXPECT_EQ("8080", uc.port);
  10768. EXPECT_EQ("/ws", uc.path);
  10769. }
  10770. {
  10771. detail::UrlComponents uc;
  10772. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  10773. EXPECT_EQ("wss", uc.scheme);
  10774. EXPECT_EQ("echo.example.com", uc.host);
  10775. EXPECT_TRUE(uc.port.empty());
  10776. EXPECT_EQ("/ws", uc.path);
  10777. }
  10778. }
  10779. TEST(ParseUrlTest, QueryOnly) {
  10780. detail::UrlComponents uc;
  10781. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  10782. EXPECT_TRUE(uc.host.empty());
  10783. EXPECT_TRUE(uc.path.empty());
  10784. EXPECT_EQ("?q=1&r=2", uc.query);
  10785. }
  10786. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  10787. detail::UrlComponents uc;
  10788. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  10789. EXPECT_TRUE(uc.scheme.empty());
  10790. EXPECT_EQ("example.com", uc.host);
  10791. EXPECT_EQ("443", uc.port);
  10792. EXPECT_EQ("/path", uc.path);
  10793. }
  10794. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10795. // If ipv6 regex working, regex match codepath is taken.
  10796. // else port will default to 80 in Client impl
  10797. int clientImplMagicPort = 80;
  10798. int port = 4321;
  10799. // above ports must be different to avoid false negative
  10800. EXPECT_NE(clientImplMagicPort, port);
  10801. std::string ipV6TestURL = "http://[ff06::c3]";
  10802. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10803. CLIENT_PRIVATE_KEY_FILE);
  10804. EXPECT_EQ(cli.port(), port);
  10805. }
  10806. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10807. auto file_path = "./www/dir/index.html";
  10808. auto dir_path = "./www/dir";
  10809. detail::FileStat stat_file(file_path);
  10810. EXPECT_TRUE(stat_file.is_file());
  10811. EXPECT_FALSE(stat_file.is_dir());
  10812. detail::FileStat stat_dir(dir_path);
  10813. EXPECT_FALSE(stat_dir.is_file());
  10814. EXPECT_TRUE(stat_dir.is_dir());
  10815. }
  10816. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10817. // IPv4 with default HTTP port (80)
  10818. EXPECT_EQ("example.com",
  10819. detail::make_host_and_port_string("example.com", 80, false));
  10820. // IPv4 with default HTTPS port (443)
  10821. EXPECT_EQ("example.com",
  10822. detail::make_host_and_port_string("example.com", 443, true));
  10823. // IPv4 with non-default HTTP port
  10824. EXPECT_EQ("example.com:8080",
  10825. detail::make_host_and_port_string("example.com", 8080, false));
  10826. // IPv4 with non-default HTTPS port
  10827. EXPECT_EQ("example.com:8443",
  10828. detail::make_host_and_port_string("example.com", 8443, true));
  10829. // IPv6 with default HTTP port (80)
  10830. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10831. // IPv6 with default HTTPS port (443)
  10832. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10833. // IPv6 with non-default HTTP port
  10834. EXPECT_EQ("[::1]:8080",
  10835. detail::make_host_and_port_string("::1", 8080, false));
  10836. // IPv6 with non-default HTTPS port
  10837. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10838. // IPv6 full address with default port
  10839. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10840. detail::make_host_and_port_string(
  10841. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10842. // IPv6 full address with non-default port
  10843. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10844. detail::make_host_and_port_string(
  10845. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10846. // IPv6 localhost with non-default port
  10847. EXPECT_EQ("[::1]:3000",
  10848. detail::make_host_and_port_string("::1", 3000, false));
  10849. // IPv6 with zone ID (link-local address) with default port
  10850. EXPECT_EQ("[fe80::1%eth0]",
  10851. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10852. // IPv6 with zone ID (link-local address) with non-default port
  10853. EXPECT_EQ("[fe80::1%eth0]:8080",
  10854. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10855. // Edge case: Port 443 with is_ssl=false (should add port)
  10856. EXPECT_EQ("example.com:443",
  10857. detail::make_host_and_port_string("example.com", 443, false));
  10858. // Edge case: Port 80 with is_ssl=true (should add port)
  10859. EXPECT_EQ("example.com:80",
  10860. detail::make_host_and_port_string("example.com", 80, true));
  10861. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10862. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10863. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10864. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10865. // Security fix: Already bracketed IPv6 should not get double brackets
  10866. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10867. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10868. EXPECT_EQ("[::1]:8080",
  10869. detail::make_host_and_port_string("[::1]", 8080, false));
  10870. EXPECT_EQ("[2001:db8::1]:8080",
  10871. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10872. EXPECT_EQ("[fe80::1%eth0]",
  10873. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10874. EXPECT_EQ("[fe80::1%eth0]:8080",
  10875. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10876. // Edge case: Empty host (should return as-is)
  10877. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10878. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10879. // This is a known limitation but shouldn't crash
  10880. EXPECT_EQ("[host:name]",
  10881. detail::make_host_and_port_string("host:name", 80, false));
  10882. // Port number edge cases (no validation, but should not crash)
  10883. EXPECT_EQ("example.com:0",
  10884. detail::make_host_and_port_string("example.com", 0, false));
  10885. EXPECT_EQ("example.com:-1",
  10886. detail::make_host_and_port_string("example.com", -1, false));
  10887. EXPECT_EQ("example.com:65535",
  10888. detail::make_host_and_port_string("example.com", 65535, false));
  10889. EXPECT_EQ("example.com:65536",
  10890. detail::make_host_and_port_string("example.com", 65536, false));
  10891. }
  10892. #ifdef CPPHTTPLIB_SSL_ENABLED
  10893. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10894. httplib::SSLClient cli("roblox.com", 443);
  10895. cli.set_follow_location(true);
  10896. auto res = cli.Get("/");
  10897. ASSERT_TRUE(res);
  10898. EXPECT_EQ(StatusCode::OK_200, res->status);
  10899. }
  10900. #endif
  10901. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10902. Server svr;
  10903. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10904. EXPECT_EQ(res.status, 400);
  10905. });
  10906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10907. auto se = detail::scope_exit([&] {
  10908. svr.stop();
  10909. thread.join();
  10910. ASSERT_FALSE(svr.is_running());
  10911. });
  10912. svr.wait_until_ready();
  10913. Client cli(HOST, PORT);
  10914. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10915. }
  10916. TEST(InvalidHeaderCharsTest, is_field_name) {
  10917. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10918. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10919. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10920. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10921. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10922. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10923. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10924. EXPECT_FALSE(detail::fields::is_field_name(""));
  10925. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10926. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10927. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10928. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10929. }
  10930. TEST(InvalidHeaderCharsTest, is_field_value) {
  10931. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10932. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10933. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10934. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10935. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10936. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10937. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10938. EXPECT_TRUE(detail::fields::is_field_value(""));
  10939. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10940. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10941. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10942. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10943. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10944. }
  10945. TEST(InvalidHeaderCharsTest, OnServer) {
  10946. Server svr;
  10947. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10948. std::string header = "Not Set";
  10949. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10950. res.set_header(header, "value");
  10951. res.set_content("Page Content Page Content", "text/plain");
  10952. });
  10953. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10954. std::string header = "Not Set";
  10955. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10956. res.set_header("X-Test", header);
  10957. res.set_content("Page Content Page Content", "text/plain");
  10958. });
  10959. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10960. auto se = detail::scope_exit([&] {
  10961. svr.stop();
  10962. thread.join();
  10963. ASSERT_FALSE(svr.is_running());
  10964. });
  10965. svr.wait_until_ready();
  10966. Client cli(HOST, PORT);
  10967. {
  10968. auto res = cli.Get(
  10969. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10970. ASSERT_TRUE(res);
  10971. EXPECT_EQ("Page Content Page Content", res->body);
  10972. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10973. }
  10974. {
  10975. auto res = cli.Get(
  10976. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10977. ASSERT_TRUE(res);
  10978. EXPECT_EQ("Page Content Page Content", res->body);
  10979. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10980. }
  10981. }
  10982. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10983. auto handled = false;
  10984. Server svr;
  10985. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10986. thread t = thread([&] { svr.listen(HOST, PORT); });
  10987. auto se = detail::scope_exit([&] {
  10988. svr.stop();
  10989. t.join();
  10990. ASSERT_FALSE(svr.is_running());
  10991. ASSERT_FALSE(handled);
  10992. });
  10993. svr.wait_until_ready();
  10994. auto req = "POST /test HTTP/1.1\r\n"
  10995. "Content-Length: x\r\n"
  10996. "\r\n";
  10997. std::string response;
  10998. ASSERT_TRUE(send_request(1, req, &response));
  10999. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11000. response.substr(0, response.find("\r\n")));
  11001. }
  11002. #ifndef _WIN32
  11003. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11004. static constexpr char reject[] = "Unauthorized";
  11005. static constexpr char accept[] = "Upload accepted";
  11006. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11007. Server svr;
  11008. svr.set_expect_100_continue_handler(
  11009. [](const Request & /*req*/, Response &res) {
  11010. res.status = StatusCode::Unauthorized_401;
  11011. res.set_content(reject, "text/plain");
  11012. return res.status;
  11013. });
  11014. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11015. res.set_content(accept, "text/plain");
  11016. });
  11017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11018. auto se = detail::scope_exit([&] {
  11019. svr.stop();
  11020. thread.join();
  11021. ASSERT_FALSE(svr.is_running());
  11022. });
  11023. svr.wait_until_ready();
  11024. {
  11025. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11026. curl_easy_init(), &curl_easy_cleanup};
  11027. ASSERT_NE(curl, nullptr);
  11028. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11029. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11030. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11031. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11032. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11033. &curl_slist_free_all};
  11034. ASSERT_NE(list, nullptr);
  11035. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11036. struct read_data {
  11037. size_t read_size;
  11038. size_t total_size;
  11039. } data = {0, total_size};
  11040. using read_callback_t =
  11041. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11042. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11043. void *userdata) -> size_t {
  11044. read_data *d = (read_data *)userdata;
  11045. if (!userdata || d->read_size >= d->total_size) { return 0; }
  11046. std::fill_n(ptr, size * nmemb, 'A');
  11047. d->read_size += size * nmemb;
  11048. return size * nmemb;
  11049. };
  11050. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11051. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11052. std::vector<char> buffer;
  11053. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11054. using write_callback_t =
  11055. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11056. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11057. void *userdata) -> size_t {
  11058. std::vector<char> *buf = (std::vector<char> *)userdata;
  11059. buf->reserve(buf->size() + size * nmemb + 1);
  11060. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11061. return size * nmemb;
  11062. };
  11063. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11064. {
  11065. const auto res = curl_easy_perform(curl.get());
  11066. ASSERT_EQ(res, CURLE_OK);
  11067. }
  11068. {
  11069. auto response_code = long{};
  11070. const auto res =
  11071. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11072. ASSERT_EQ(res, CURLE_OK);
  11073. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11074. }
  11075. {
  11076. auto dl = curl_off_t{};
  11077. const auto res =
  11078. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11079. ASSERT_EQ(res, CURLE_OK);
  11080. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11081. }
  11082. {
  11083. buffer.push_back('\0');
  11084. ASSERT_STRCASEEQ(buffer.data(), reject);
  11085. }
  11086. }
  11087. }
  11088. #endif
  11089. template <typename S, typename C>
  11090. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11091. svr.Get("/stream", [&](const Request &, Response &res) {
  11092. auto data = new std::string("01234567890123456789");
  11093. res.set_content_provider(
  11094. data->size(), "text/plain",
  11095. [&, data](size_t offset, size_t length, DataSink &sink) {
  11096. const size_t DATA_CHUNK_SIZE = 4;
  11097. const auto &d = *data;
  11098. std::this_thread::sleep_for(std::chrono::seconds(1));
  11099. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11100. return true;
  11101. },
  11102. [data](bool success) {
  11103. EXPECT_FALSE(success);
  11104. delete data;
  11105. });
  11106. });
  11107. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11108. auto i = new size_t(0);
  11109. res.set_content_provider(
  11110. "text/plain",
  11111. [i](size_t, DataSink &sink) {
  11112. if (*i < 5) {
  11113. std::this_thread::sleep_for(std::chrono::seconds(1));
  11114. sink.write("abcd", 4);
  11115. (*i)++;
  11116. } else {
  11117. sink.done();
  11118. }
  11119. return true;
  11120. },
  11121. [i](bool success) {
  11122. EXPECT_FALSE(success);
  11123. delete i;
  11124. });
  11125. });
  11126. svr.Get("/chunked", [&](const Request &, Response &res) {
  11127. auto i = new size_t(0);
  11128. res.set_chunked_content_provider(
  11129. "text/plain",
  11130. [i](size_t, DataSink &sink) {
  11131. if (*i < 5) {
  11132. std::this_thread::sleep_for(std::chrono::seconds(1));
  11133. sink.os << "abcd";
  11134. (*i)++;
  11135. } else {
  11136. sink.done();
  11137. }
  11138. return true;
  11139. },
  11140. [i](bool success) {
  11141. EXPECT_FALSE(success);
  11142. delete i;
  11143. });
  11144. });
  11145. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11146. auto se = detail::scope_exit([&] {
  11147. svr.stop();
  11148. listen_thread.join();
  11149. ASSERT_FALSE(svr.is_running());
  11150. });
  11151. svr.wait_until_ready();
  11152. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11153. {
  11154. auto start = std::chrono::steady_clock::now();
  11155. auto res = cli.Get("/stream");
  11156. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11157. std::chrono::steady_clock::now() - start)
  11158. .count();
  11159. ASSERT_FALSE(res);
  11160. EXPECT_EQ(Error::Read, res.error());
  11161. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11162. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11163. }
  11164. {
  11165. auto start = std::chrono::steady_clock::now();
  11166. auto res = cli.Get("/stream_without_length");
  11167. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11168. std::chrono::steady_clock::now() - start)
  11169. .count();
  11170. ASSERT_FALSE(res);
  11171. EXPECT_EQ(Error::Read, res.error());
  11172. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11173. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11174. }
  11175. {
  11176. auto start = std::chrono::steady_clock::now();
  11177. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11178. EXPECT_EQ("abcd", string(data, data_length));
  11179. return true;
  11180. });
  11181. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11182. std::chrono::steady_clock::now() - start)
  11183. .count();
  11184. ASSERT_FALSE(res);
  11185. EXPECT_EQ(Error::Read, res.error());
  11186. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11187. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11188. }
  11189. }
  11190. TEST(MaxTimeoutTest, ContentStream) {
  11191. time_t timeout = 2000;
  11192. time_t threshold = 200;
  11193. Server svr;
  11194. Client cli("localhost", PORT);
  11195. max_timeout_test(svr, cli, timeout, threshold);
  11196. }
  11197. #ifdef CPPHTTPLIB_SSL_ENABLED
  11198. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11199. time_t timeout = 2000;
  11200. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11202. SSLClient cli("localhost", PORT);
  11203. cli.enable_server_certificate_verification(false);
  11204. max_timeout_test(svr, cli, timeout, threshold);
  11205. }
  11206. #endif
  11207. class EventDispatcher {
  11208. public:
  11209. EventDispatcher() {}
  11210. bool wait_event(DataSink *sink) {
  11211. unique_lock<mutex> lk(m_);
  11212. int id = id_;
  11213. // Wait with timeout to prevent hanging if client disconnects
  11214. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11215. [&] { return cid_ == id; })) {
  11216. return false; // Timeout occurred
  11217. }
  11218. sink->write(message_.data(), message_.size());
  11219. return true;
  11220. }
  11221. void send_event(const string &message) {
  11222. lock_guard<mutex> lk(m_);
  11223. cid_ = id_++;
  11224. message_ = message;
  11225. cv_.notify_all();
  11226. }
  11227. private:
  11228. mutex m_;
  11229. condition_variable cv_;
  11230. atomic_int id_{0};
  11231. atomic_int cid_{-1};
  11232. string message_;
  11233. };
  11234. TEST(ClientInThreadTest, Issue2068) {
  11235. EventDispatcher ed;
  11236. Server svr;
  11237. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11238. res.set_chunked_content_provider("text/event-stream",
  11239. [&](size_t /*offset*/, DataSink &sink) {
  11240. return ed.wait_event(&sink);
  11241. });
  11242. });
  11243. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11244. svr.wait_until_ready();
  11245. thread event_thread([&] {
  11246. int id = 0;
  11247. while (svr.is_running()) {
  11248. this_thread::sleep_for(chrono::milliseconds(500));
  11249. std::stringstream ss;
  11250. ss << "data: " << id << "\n\n";
  11251. ed.send_event(ss.str());
  11252. id++;
  11253. }
  11254. });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. listen_thread.join();
  11258. event_thread.join();
  11259. ASSERT_FALSE(svr.is_running());
  11260. });
  11261. {
  11262. auto client = detail::make_unique<Client>(HOST, PORT);
  11263. client->set_read_timeout(std::chrono::minutes(10));
  11264. std::atomic<bool> stop{false};
  11265. std::thread t([&] {
  11266. client->Get("/event1",
  11267. [&](const char *, size_t) -> bool { return !stop; });
  11268. });
  11269. std::this_thread::sleep_for(std::chrono::seconds(2));
  11270. stop = true;
  11271. client->stop();
  11272. t.join();
  11273. // Reset client after thread has finished
  11274. client.reset();
  11275. }
  11276. }
  11277. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11278. auto handled = false;
  11279. Server svr;
  11280. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11281. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11282. auto se = detail::scope_exit([&] {
  11283. svr.stop();
  11284. t.join();
  11285. ASSERT_FALSE(svr.is_running());
  11286. ASSERT_FALSE(handled);
  11287. });
  11288. svr.wait_until_ready();
  11289. // Two Content-Length headers with different values — must be rejected
  11290. auto req = "POST /test HTTP/1.1\r\n"
  11291. "Content-Length: 5\r\n"
  11292. "Content-Length: 10\r\n"
  11293. "\r\n"
  11294. "hello";
  11295. std::string response;
  11296. ASSERT_TRUE(send_request(1, req, &response));
  11297. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11298. response.substr(0, response.find("\r\n")));
  11299. }
  11300. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11301. auto handled = false;
  11302. Server svr;
  11303. svr.Post("/test", [&](const Request &, Response &res) {
  11304. handled = true;
  11305. res.set_content("ok", "text/plain");
  11306. });
  11307. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11308. auto se = detail::scope_exit([&] {
  11309. svr.stop();
  11310. t.join();
  11311. ASSERT_FALSE(svr.is_running());
  11312. ASSERT_TRUE(handled);
  11313. });
  11314. svr.wait_until_ready();
  11315. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11316. auto req = "POST /test HTTP/1.1\r\n"
  11317. "Content-Length: 5\r\n"
  11318. "Content-Length: 5\r\n"
  11319. "\r\n"
  11320. "hello";
  11321. std::string response;
  11322. ASSERT_TRUE(send_request(1, req, &response));
  11323. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11324. }
  11325. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11326. Server svr;
  11327. svr.Get("/", [](const Request &req, Response &res) {
  11328. EXPECT_EQ(2U, req.trailers.size());
  11329. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11330. // Denied
  11331. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11332. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11333. // Accepted
  11334. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11335. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11336. EXPECT_TRUE(req.has_trailer("X-World"));
  11337. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11338. res.set_content("ok", "text/plain");
  11339. });
  11340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11341. auto se = detail::scope_exit([&] {
  11342. svr.stop();
  11343. t.join();
  11344. ASSERT_FALSE(svr.is_running());
  11345. });
  11346. svr.wait_until_ready();
  11347. const std::string req = "GET / HTTP/1.1\r\n"
  11348. "Transfer-Encoding: chunked\r\n"
  11349. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11350. "\r\n"
  11351. "0\r\n"
  11352. "Content-Length: 10\r\n"
  11353. "Host: internal.local\r\n"
  11354. "Content-Type: malicious/content\r\n"
  11355. "Cookie: any\r\n"
  11356. "Set-Cookie: any\r\n"
  11357. "X-Forwarded-For: attacker.com\r\n"
  11358. "X-Real-Ip: 1.1.1.1\r\n"
  11359. "X-Hello: hello\r\n"
  11360. "X-World: world\r\n"
  11361. "\r\n";
  11362. std::string res;
  11363. ASSERT_TRUE(send_request(1, req, &res));
  11364. }
  11365. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11366. Server svr;
  11367. std::string observed_remote_addr;
  11368. std::string observed_xff;
  11369. svr.Get("/ip", [&](const Request &req, Response &res) {
  11370. observed_remote_addr = req.remote_addr;
  11371. observed_xff = req.get_header_value("X-Forwarded-For");
  11372. res.set_content("ok", "text/plain");
  11373. });
  11374. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11375. auto se = detail::scope_exit([&] {
  11376. svr.stop();
  11377. t.join();
  11378. ASSERT_FALSE(svr.is_running());
  11379. });
  11380. svr.wait_until_ready();
  11381. Client cli(HOST, PORT);
  11382. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11383. ASSERT_TRUE(res);
  11384. EXPECT_EQ(StatusCode::OK_200, res->status);
  11385. EXPECT_EQ(observed_xff, "203.0.113.66");
  11386. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11387. observed_remote_addr == "127.0.0.1");
  11388. }
  11389. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11390. Server svr;
  11391. svr.set_trusted_proxies({"203.0.113.66"});
  11392. std::string observed_remote_addr;
  11393. std::string observed_xff;
  11394. svr.Get("/ip", [&](const Request &req, Response &res) {
  11395. observed_remote_addr = req.remote_addr;
  11396. observed_xff = req.get_header_value("X-Forwarded-For");
  11397. res.set_content("ok", "text/plain");
  11398. });
  11399. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11400. auto se = detail::scope_exit([&] {
  11401. svr.stop();
  11402. t.join();
  11403. ASSERT_FALSE(svr.is_running());
  11404. });
  11405. svr.wait_until_ready();
  11406. Client cli(HOST, PORT);
  11407. auto res = cli.Get("/ip");
  11408. ASSERT_TRUE(res);
  11409. EXPECT_EQ(StatusCode::OK_200, res->status);
  11410. EXPECT_EQ(observed_xff, "");
  11411. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11412. observed_remote_addr == "127.0.0.1");
  11413. }
  11414. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11415. Server svr;
  11416. svr.set_trusted_proxies({"203.0.113.66"});
  11417. std::string observed_remote_addr;
  11418. std::string observed_xff;
  11419. svr.Get("/ip", [&](const Request &req, Response &res) {
  11420. observed_remote_addr = req.remote_addr;
  11421. observed_xff = req.get_header_value("X-Forwarded-For");
  11422. res.set_content("ok", "text/plain");
  11423. });
  11424. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11425. auto se = detail::scope_exit([&] {
  11426. svr.stop();
  11427. t.join();
  11428. ASSERT_FALSE(svr.is_running());
  11429. });
  11430. svr.wait_until_ready();
  11431. Client cli(HOST, PORT);
  11432. auto res =
  11433. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11434. ASSERT_TRUE(res);
  11435. EXPECT_EQ(StatusCode::OK_200, res->status);
  11436. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11437. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11438. }
  11439. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11440. Server svr;
  11441. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11442. std::string observed_remote_addr;
  11443. std::string observed_xff;
  11444. svr.Get("/ip", [&](const Request &req, Response &res) {
  11445. observed_remote_addr = req.remote_addr;
  11446. observed_xff = req.get_header_value("X-Forwarded-For");
  11447. res.set_content("ok", "text/plain");
  11448. });
  11449. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11450. auto se = detail::scope_exit([&] {
  11451. svr.stop();
  11452. t.join();
  11453. ASSERT_FALSE(svr.is_running());
  11454. });
  11455. svr.wait_until_ready();
  11456. Client cli(HOST, PORT);
  11457. auto res = cli.Get(
  11458. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11459. ASSERT_TRUE(res);
  11460. EXPECT_EQ(StatusCode::OK_200, res->status);
  11461. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11462. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11463. }
  11464. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11465. Server svr;
  11466. svr.set_trusted_proxies({"192.0.2.45"});
  11467. std::string observed_remote_addr;
  11468. std::string observed_xff;
  11469. svr.Get("/ip", [&](const Request &req, Response &res) {
  11470. observed_remote_addr = req.remote_addr;
  11471. observed_xff = req.get_header_value("X-Forwarded-For");
  11472. res.set_content("ok", "text/plain");
  11473. });
  11474. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11475. auto se = detail::scope_exit([&] {
  11476. svr.stop();
  11477. t.join();
  11478. ASSERT_FALSE(svr.is_running());
  11479. });
  11480. svr.wait_until_ready();
  11481. Client cli(HOST, PORT);
  11482. auto res =
  11483. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11484. ASSERT_TRUE(res);
  11485. EXPECT_EQ(StatusCode::OK_200, res->status);
  11486. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11487. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11488. }
  11489. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11490. Server svr;
  11491. svr.set_trusted_proxies({"192.0.2.45"});
  11492. std::string observed_remote_addr;
  11493. std::string observed_xff;
  11494. svr.Get("/ip", [&](const Request &req, Response &res) {
  11495. observed_remote_addr = req.remote_addr;
  11496. observed_xff = req.get_header_value("X-Forwarded-For");
  11497. res.set_content("ok", "text/plain");
  11498. });
  11499. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11500. auto se = detail::scope_exit([&] {
  11501. svr.stop();
  11502. t.join();
  11503. ASSERT_FALSE(svr.is_running());
  11504. });
  11505. svr.wait_until_ready();
  11506. Client cli(HOST, PORT);
  11507. auto res = cli.Get(
  11508. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11509. ASSERT_TRUE(res);
  11510. EXPECT_EQ(StatusCode::OK_200, res->status);
  11511. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11512. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11513. }
  11514. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11515. Server svr;
  11516. svr.set_trusted_proxies({"192.0.2.45"});
  11517. std::string observed_remote_addr;
  11518. std::string observed_xff;
  11519. svr.Get("/ip", [&](const Request &req, Response &res) {
  11520. observed_remote_addr = req.remote_addr;
  11521. observed_xff = req.get_header_value("X-Forwarded-For");
  11522. res.set_content("ok", "text/plain");
  11523. });
  11524. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11525. auto se = detail::scope_exit([&] {
  11526. svr.stop();
  11527. t.join();
  11528. ASSERT_FALSE(svr.is_running());
  11529. });
  11530. svr.wait_until_ready();
  11531. std::string raw_req =
  11532. "GET /ip HTTP/1.1\r\n"
  11533. "Host: localhost\r\n"
  11534. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11535. "Connection: close\r\n"
  11536. "\r\n";
  11537. std::string out;
  11538. ASSERT_TRUE(send_request(5, raw_req, &out));
  11539. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11540. // Header parser trims surrounding whitespace of the header value
  11541. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11542. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11543. }
  11544. #ifndef _WIN32
  11545. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11546. Server svr;
  11547. svr.Post("/post", [&](const Request &req, Response &res) {
  11548. res.set_content(req.body, "text/plain");
  11549. });
  11550. svr.Put("/put", [&](const Request &req, Response &res) {
  11551. res.set_content(req.body, "text/plain");
  11552. });
  11553. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11554. res.set_content(req.body, "text/plain");
  11555. });
  11556. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11557. res.set_content(req.body, "text/plain");
  11558. });
  11559. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11560. auto se = detail::scope_exit([&] {
  11561. svr.stop();
  11562. t.join();
  11563. ASSERT_FALSE(svr.is_running());
  11564. });
  11565. svr.wait_until_ready();
  11566. std::string resp;
  11567. // POST without Content-Length
  11568. ASSERT_TRUE(send_request(5,
  11569. "POST /post HTTP/1.1\r\n"
  11570. "Host: localhost\r\n"
  11571. "Connection: close\r\n"
  11572. "\r\n",
  11573. &resp));
  11574. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11575. // PUT without Content-Length
  11576. resp.clear();
  11577. ASSERT_TRUE(send_request(5,
  11578. "PUT /put HTTP/1.1\r\n"
  11579. "Host: localhost\r\n"
  11580. "Connection: close\r\n"
  11581. "\r\n",
  11582. &resp));
  11583. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11584. // PATCH without Content-Length
  11585. resp.clear();
  11586. ASSERT_TRUE(send_request(5,
  11587. "PATCH /patch HTTP/1.1\r\n"
  11588. "Host: localhost\r\n"
  11589. "Connection: close\r\n"
  11590. "\r\n",
  11591. &resp));
  11592. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11593. // DELETE without Content-Length
  11594. resp.clear();
  11595. ASSERT_TRUE(send_request(5,
  11596. "DELETE /delete HTTP/1.1\r\n"
  11597. "Host: localhost\r\n"
  11598. "Connection: close\r\n"
  11599. "\r\n",
  11600. &resp));
  11601. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11602. }
  11603. #endif
  11604. //==============================================================================
  11605. // open_stream() Tests
  11606. //==============================================================================
  11607. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11608. std::string result;
  11609. char buf[8192];
  11610. ssize_t n;
  11611. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11612. result.append(buf, static_cast<size_t>(n));
  11613. }
  11614. return result;
  11615. }
  11616. // Mock stream for unit tests
  11617. class MockStream : public Stream {
  11618. public:
  11619. std::string data;
  11620. size_t pos = 0;
  11621. ssize_t error_after = -1; // -1 = no error
  11622. explicit MockStream(const std::string &d, ssize_t err = -1)
  11623. : data(d), error_after(err) {}
  11624. bool is_readable() const override { return true; }
  11625. bool wait_readable() const override { return true; }
  11626. bool wait_writable() const override { return true; }
  11627. ssize_t read(char *ptr, size_t size) override {
  11628. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11629. if (pos >= data.size()) return 0;
  11630. size_t limit =
  11631. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11632. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11633. std::memcpy(ptr, data.data() + pos, to_read);
  11634. pos += to_read;
  11635. return static_cast<ssize_t>(to_read);
  11636. }
  11637. ssize_t write(const char *, size_t) override { return -1; }
  11638. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11639. ip = "127.0.0.1";
  11640. port = 0;
  11641. }
  11642. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11643. ip = "127.0.0.1";
  11644. port = 0;
  11645. }
  11646. socket_t socket() const override { return INVALID_SOCKET; }
  11647. time_t duration() const override { return 0; }
  11648. };
  11649. TEST(StreamHandleTest, Basic) {
  11650. ClientImpl::StreamHandle handle;
  11651. EXPECT_FALSE(handle.is_valid());
  11652. handle.response = detail::make_unique<Response>();
  11653. handle.error = Error::Connection;
  11654. EXPECT_FALSE(handle.is_valid());
  11655. handle.error = Error::Success;
  11656. EXPECT_TRUE(handle.is_valid());
  11657. }
  11658. TEST(BodyReaderTest, Basic) {
  11659. MockStream stream("Hello, World!");
  11660. detail::BodyReader reader;
  11661. reader.stream = &stream;
  11662. reader.content_length = 13;
  11663. char buf[32];
  11664. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11665. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11666. EXPECT_TRUE(reader.eof);
  11667. }
  11668. TEST(BodyReaderTest, NoStream) {
  11669. detail::BodyReader reader;
  11670. char buf[32];
  11671. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11672. EXPECT_EQ(Error::Connection, reader.last_error);
  11673. }
  11674. TEST(BodyReaderTest, Error) {
  11675. MockStream stream("Hello, World!", 5);
  11676. detail::BodyReader reader;
  11677. reader.stream = &stream;
  11678. reader.content_length = 13;
  11679. char buf[32];
  11680. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11681. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11682. EXPECT_EQ(Error::Read, reader.last_error);
  11683. }
  11684. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11685. // Mock-based StreamHandle tests relying on private internals are removed.
  11686. class OpenStreamTest : public ::testing::Test {
  11687. protected:
  11688. void SetUp() override {
  11689. svr_.Get("/hello", [](const Request &, Response &res) {
  11690. res.set_content("Hello World!", "text/plain");
  11691. });
  11692. svr_.Get("/large", [](const Request &, Response &res) {
  11693. res.set_content(std::string(10000, 'X'), "text/plain");
  11694. });
  11695. svr_.Get("/chunked", [](const Request &, Response &res) {
  11696. res.set_chunked_content_provider("text/plain",
  11697. [](size_t offset, DataSink &sink) {
  11698. if (offset < 15) {
  11699. sink.write("chunk", 5);
  11700. return true;
  11701. }
  11702. sink.done();
  11703. return true;
  11704. });
  11705. });
  11706. svr_.Get("/compressible", [](const Request &, Response &res) {
  11707. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11708. DataSink &sink) {
  11709. if (offset < 100 * 1024) {
  11710. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11711. sink.write(chunk.data(), chunk.size());
  11712. return true;
  11713. }
  11714. sink.done();
  11715. return true;
  11716. });
  11717. });
  11718. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11719. [](const Request & /*req*/, Response &res) {
  11720. auto i = new int(0);
  11721. res.set_header("Trailer", "Content-Length, X-Allowed");
  11722. res.set_chunked_content_provider(
  11723. "text/plain",
  11724. [i](size_t /*offset*/, DataSink &sink) {
  11725. switch (*i) {
  11726. case 0: sink.os << "123"; break;
  11727. case 1: sink.os << "456"; break;
  11728. case 2: sink.os << "789"; break;
  11729. case 3: {
  11730. sink.done_with_trailer(
  11731. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11732. } break;
  11733. }
  11734. (*i)++;
  11735. return true;
  11736. },
  11737. [i](bool success) {
  11738. EXPECT_TRUE(success);
  11739. delete i;
  11740. });
  11741. });
  11742. // Echo headers endpoint for header-related tests
  11743. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11744. std::string body;
  11745. for (const auto &h : req.headers) {
  11746. body.append(h.first);
  11747. body.push_back(':');
  11748. body.append(h.second);
  11749. body.push_back('\n');
  11750. }
  11751. res.set_content(body, "text/plain");
  11752. });
  11753. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11754. std::string body;
  11755. for (const auto &h : req.headers) {
  11756. body.append(h.first);
  11757. body.push_back(':');
  11758. body.append(h.second);
  11759. body.push_back('\n');
  11760. }
  11761. res.set_content(body, "text/plain");
  11762. });
  11763. port_ = svr_.bind_to_any_port("127.0.0.1");
  11764. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11765. svr_.wait_until_ready();
  11766. }
  11767. void TearDown() override {
  11768. svr_.stop();
  11769. if (thread_.joinable()) thread_.join();
  11770. }
  11771. Server svr_;
  11772. std::thread thread_;
  11773. int port_ = 0;
  11774. };
  11775. TEST_F(OpenStreamTest, Basic) {
  11776. Client cli("127.0.0.1", port_);
  11777. auto handle = cli.open_stream("GET", "/hello");
  11778. EXPECT_TRUE(handle.is_valid());
  11779. EXPECT_EQ("Hello World!", read_all(handle));
  11780. }
  11781. TEST_F(OpenStreamTest, SmallBuffer) {
  11782. Client cli("127.0.0.1", port_);
  11783. auto handle = cli.open_stream("GET", "/hello");
  11784. std::string result;
  11785. char buf[4];
  11786. ssize_t n;
  11787. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11788. result.append(buf, static_cast<size_t>(n));
  11789. EXPECT_EQ("Hello World!", result);
  11790. }
  11791. TEST_F(OpenStreamTest, DefaultHeaders) {
  11792. Client cli("127.0.0.1", port_);
  11793. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11794. {
  11795. auto handle = cli.open_stream("GET", "/echo-headers");
  11796. ASSERT_TRUE(handle.is_valid());
  11797. auto body = read_all(handle);
  11798. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11799. std::string::npos);
  11800. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11801. std::string::npos);
  11802. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11803. }
  11804. // open_stream POST with body and no explicit content_type should NOT add
  11805. // text/plain Content-Type (behavior differs from non-streaming path), but
  11806. // should include Content-Length
  11807. {
  11808. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11809. ASSERT_TRUE(handle.is_valid());
  11810. auto body = read_all(handle);
  11811. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11812. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11813. }
  11814. // open_stream POST with explicit Content-Type should preserve it
  11815. {
  11816. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11817. {{"Content-Type", "application/custom"}},
  11818. "{}", "application/custom");
  11819. ASSERT_TRUE(handle.is_valid());
  11820. auto body = read_all(handle);
  11821. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11822. }
  11823. // User-specified User-Agent must not be overwritten for stream API
  11824. {
  11825. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11826. {{"User-Agent", "MyAgent/1.2"}});
  11827. ASSERT_TRUE(handle.is_valid());
  11828. auto body = read_all(handle);
  11829. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11830. }
  11831. }
  11832. TEST_F(OpenStreamTest, Large) {
  11833. Client cli("127.0.0.1", port_);
  11834. auto handle = cli.open_stream("GET", "/large");
  11835. EXPECT_EQ(10000u, read_all(handle).size());
  11836. }
  11837. TEST_F(OpenStreamTest, ConnectionError) {
  11838. Client cli("127.0.0.1", 9999);
  11839. auto handle = cli.open_stream("GET", "/hello");
  11840. EXPECT_FALSE(handle.is_valid());
  11841. }
  11842. TEST_F(OpenStreamTest, Chunked) {
  11843. Client cli("127.0.0.1", port_);
  11844. auto handle = cli.open_stream("GET", "/chunked");
  11845. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11846. "Transfer-Encoding") == "chunked");
  11847. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11848. }
  11849. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11850. Client cli("127.0.0.1", port_);
  11851. auto handle =
  11852. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11853. ASSERT_TRUE(handle.is_valid());
  11854. // Consume body to allow trailers to be received/parsed
  11855. auto body = read_all(handle);
  11856. // Explicitly parse trailers (ensure trailers are available for assertion)
  11857. handle.parse_trailers_if_needed();
  11858. EXPECT_EQ(std::string("123456789"), body);
  11859. // The response should include a Trailer header declaring both names
  11860. ASSERT_TRUE(handle.response);
  11861. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11862. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11863. handle.response->get_header_value("Trailer"));
  11864. // Prohibited trailer must not be present
  11865. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11866. // Allowed trailer should be present
  11867. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11868. EXPECT_EQ(std::string("yes"),
  11869. handle.response->get_trailer_value("X-Allowed"));
  11870. // Verify trailers are NOT present as regular headers
  11871. EXPECT_EQ(std::string(""),
  11872. handle.response->get_header_value("Content-Length"));
  11873. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11874. }
  11875. static std::thread serve_single_response(std::promise<int> &port_promise,
  11876. const std::string &response) {
  11877. return std::thread([&port_promise, response] {
  11878. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11879. default_socket_options(srv);
  11880. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11882. sockaddr_in addr{};
  11883. addr.sin_family = AF_INET;
  11884. addr.sin_port = htons(0); // Let OS assign a free port
  11885. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11886. int opt = 1;
  11887. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11888. #ifdef _WIN32
  11889. reinterpret_cast<const char *>(&opt),
  11890. #else
  11891. &opt,
  11892. #endif
  11893. sizeof(opt));
  11894. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11895. ::listen(srv, 1) != 0) {
  11896. port_promise.set_value(-1);
  11897. detail::close_socket(srv);
  11898. return;
  11899. }
  11900. socklen_t addr_len = sizeof(addr);
  11901. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11902. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11903. sockaddr_in cli_addr{};
  11904. socklen_t cli_len = sizeof(cli_addr);
  11905. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11906. if (cli != INVALID_SOCKET) {
  11907. char buf[4096];
  11908. ::recv(cli, buf, sizeof(buf), 0);
  11909. ::send(cli,
  11910. #ifdef _WIN32
  11911. static_cast<const char *>(response.c_str()),
  11912. static_cast<int>(response.size()),
  11913. #else
  11914. response.c_str(), response.size(),
  11915. #endif
  11916. 0);
  11917. detail::close_socket(cli);
  11918. }
  11919. detail::close_socket(srv);
  11920. });
  11921. }
  11922. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11923. #ifndef _WIN32
  11924. signal(SIGPIPE, SIG_IGN);
  11925. #endif
  11926. std::promise<int> port_promise;
  11927. auto port_future = port_promise.get_future();
  11928. auto server_thread =
  11929. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11930. "Content-Type: text/plain\r\n"
  11931. "Content-Length: not-a-number\r\n"
  11932. "Connection: close\r\n"
  11933. "\r\n"
  11934. "hello");
  11935. auto port = port_future.get();
  11936. ASSERT_GT(port, 0);
  11937. Client cli("127.0.0.1", port);
  11938. auto handle = cli.open_stream("GET", "/");
  11939. EXPECT_FALSE(handle.is_valid());
  11940. server_thread.join();
  11941. }
  11942. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11943. #ifndef _WIN32
  11944. signal(SIGPIPE, SIG_IGN);
  11945. #endif
  11946. std::promise<int> port_promise;
  11947. auto port_future = port_promise.get_future();
  11948. auto server_thread = serve_single_response(
  11949. port_promise, "HTTP/1.1 200 OK\r\n"
  11950. "Content-Type: text/plain\r\n"
  11951. "Content-Length: 99999999999999999999999999\r\n"
  11952. "Connection: close\r\n"
  11953. "\r\n"
  11954. "hello");
  11955. auto port = port_future.get();
  11956. ASSERT_GT(port, 0);
  11957. // Before the fix, std::stoull would throw std::out_of_range here and
  11958. // crash the process. After the fix, strtoull silently clamps to
  11959. // ULLONG_MAX so the stream opens without crashing. The important thing
  11960. // is that the process does NOT terminate.
  11961. Client cli("127.0.0.1", port);
  11962. auto handle = cli.open_stream("GET", "/");
  11963. EXPECT_TRUE(handle.is_valid());
  11964. server_thread.join();
  11965. }
  11966. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11967. TEST_F(OpenStreamTest, Gzip) {
  11968. Client cli("127.0.0.1", port_);
  11969. auto handle = cli.open_stream("GET", "/compressible", {},
  11970. {{"Accept-Encoding", "gzip"}});
  11971. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11972. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11973. }
  11974. #endif
  11975. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11976. TEST_F(OpenStreamTest, Brotli) {
  11977. Client cli("127.0.0.1", port_);
  11978. auto handle =
  11979. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11980. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11981. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11982. }
  11983. #endif
  11984. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11985. TEST_F(OpenStreamTest, Zstd) {
  11986. Client cli("127.0.0.1", port_);
  11987. auto handle = cli.open_stream("GET", "/compressible", {},
  11988. {{"Accept-Encoding", "zstd"}});
  11989. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11990. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11991. }
  11992. #endif
  11993. #ifdef CPPHTTPLIB_SSL_ENABLED
  11994. class SSLOpenStreamTest : public ::testing::Test {
  11995. protected:
  11996. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11997. void SetUp() override {
  11998. svr_.Get("/hello", [](const Request &, Response &res) {
  11999. res.set_content("Hello SSL World!", "text/plain");
  12000. });
  12001. svr_.Get("/chunked", [](const Request &, Response &res) {
  12002. res.set_chunked_content_provider("text/plain",
  12003. [](size_t offset, DataSink &sink) {
  12004. if (offset < 15) {
  12005. sink.write("chunk", 5);
  12006. return true;
  12007. }
  12008. sink.done();
  12009. return true;
  12010. });
  12011. });
  12012. svr_.Post("/echo", [](const Request &req, Response &res) {
  12013. res.set_content(req.body, req.get_header_value("Content-Type"));
  12014. });
  12015. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12016. std::string body = req.body;
  12017. res.set_chunked_content_provider(
  12018. "text/plain", [body](size_t offset, DataSink &sink) {
  12019. if (offset < body.size()) {
  12020. sink.write(body.data() + offset, body.size() - offset);
  12021. }
  12022. sink.done();
  12023. return true;
  12024. });
  12025. });
  12026. port_ = svr_.bind_to_any_port("127.0.0.1");
  12027. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12028. svr_.wait_until_ready();
  12029. }
  12030. void TearDown() override {
  12031. svr_.stop();
  12032. if (thread_.joinable()) thread_.join();
  12033. }
  12034. SSLServer svr_;
  12035. std::thread thread_;
  12036. int port_ = 0;
  12037. };
  12038. TEST_F(SSLOpenStreamTest, Basic) {
  12039. SSLClient cli("127.0.0.1", port_);
  12040. cli.enable_server_certificate_verification(false);
  12041. auto handle = cli.open_stream("GET", "/hello");
  12042. ASSERT_TRUE(handle.is_valid());
  12043. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12044. }
  12045. TEST_F(SSLOpenStreamTest, Chunked) {
  12046. SSLClient cli("127.0.0.1", port_);
  12047. cli.enable_server_certificate_verification(false);
  12048. auto handle = cli.open_stream("GET", "/chunked");
  12049. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12050. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12051. "Transfer-Encoding") == "chunked");
  12052. auto body = read_all(handle);
  12053. EXPECT_EQ("chunkchunkchunk", body);
  12054. }
  12055. TEST_F(SSLOpenStreamTest, Post) {
  12056. SSLClient cli("127.0.0.1", port_);
  12057. cli.enable_server_certificate_verification(false);
  12058. auto handle =
  12059. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12060. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12061. EXPECT_EQ(200, handle.response->status);
  12062. auto body = read_all(handle);
  12063. EXPECT_EQ("Hello SSL POST", body);
  12064. }
  12065. TEST_F(SSLOpenStreamTest, PostChunked) {
  12066. SSLClient cli("127.0.0.1", port_);
  12067. cli.enable_server_certificate_verification(false);
  12068. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12069. "Chunked SSL Data", "text/plain");
  12070. ASSERT_TRUE(handle.is_valid());
  12071. EXPECT_EQ(200, handle.response->status);
  12072. auto body = read_all(handle);
  12073. EXPECT_EQ("Chunked SSL Data", body);
  12074. }
  12075. #endif // CPPHTTPLIB_SSL_ENABLED
  12076. //==============================================================================
  12077. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12078. // results for various scenarios.
  12079. //==============================================================================
  12080. TEST(ParityTest, GetVsOpenStream) {
  12081. Server svr;
  12082. const std::string path = "/parity";
  12083. const std::string content = "Parity test content: hello world";
  12084. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12085. res.set_content(content, "text/plain");
  12086. });
  12087. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12088. auto se = detail::scope_exit([&] {
  12089. svr.stop();
  12090. t.join();
  12091. ASSERT_FALSE(svr.is_running());
  12092. });
  12093. svr.wait_until_ready();
  12094. Client cli(HOST, PORT);
  12095. // Non-stream path
  12096. auto r1 = cli.Get(path);
  12097. ASSERT_TRUE(r1);
  12098. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12099. // Stream path
  12100. auto h = cli.open_stream("GET", path);
  12101. ASSERT_TRUE(h.is_valid());
  12102. EXPECT_EQ(r1->body, read_all(h));
  12103. }
  12104. // Helper to compress data with provided compressor type T
  12105. template <typename Compressor>
  12106. static std::string compress_payload_for_parity(const std::string &in) {
  12107. std::string out;
  12108. Compressor compressor;
  12109. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12110. [&](const char *data, size_t n) {
  12111. out.append(data, n);
  12112. return true;
  12113. });
  12114. EXPECT_TRUE(ok);
  12115. return out;
  12116. }
  12117. // Helper function for compression parity tests
  12118. template <typename Compressor>
  12119. static void test_compression_parity(const std::string &original,
  12120. const std::string &path,
  12121. const std::string &encoding) {
  12122. const std::string compressed =
  12123. compress_payload_for_parity<Compressor>(original);
  12124. Server svr;
  12125. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12126. res.set_content(compressed, "application/octet-stream");
  12127. res.set_header("Content-Encoding", encoding);
  12128. });
  12129. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12130. auto se = detail::scope_exit([&] {
  12131. svr.stop();
  12132. t.join();
  12133. ASSERT_FALSE(svr.is_running());
  12134. });
  12135. svr.wait_until_ready();
  12136. Client cli(HOST, PORT);
  12137. // Non-streaming
  12138. {
  12139. auto res = cli.Get(path);
  12140. ASSERT_TRUE(res);
  12141. EXPECT_EQ(StatusCode::OK_200, res->status);
  12142. EXPECT_EQ(original, res->body);
  12143. }
  12144. // Streaming
  12145. {
  12146. auto h = cli.open_stream("GET", path);
  12147. ASSERT_TRUE(h.is_valid());
  12148. EXPECT_EQ(original, read_all(h));
  12149. }
  12150. }
  12151. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12152. TEST(ParityTest, Gzip) {
  12153. test_compression_parity<detail::gzip_compressor>(
  12154. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12155. }
  12156. #endif
  12157. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12158. TEST(ParityTest, Brotli) {
  12159. test_compression_parity<detail::brotli_compressor>(
  12160. "Hello, brotli parity test payload", "/parity-br", "br");
  12161. }
  12162. #endif
  12163. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12164. TEST(ParityTest, Zstd) {
  12165. test_compression_parity<detail::zstd_compressor>(
  12166. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12167. }
  12168. #endif
  12169. //==============================================================================
  12170. // New Stream API Tests
  12171. //==============================================================================
  12172. inline std::string read_body(httplib::stream::Result &result) {
  12173. std::string body;
  12174. while (result.next()) {
  12175. body.append(result.data(), result.size());
  12176. }
  12177. return body;
  12178. }
  12179. TEST(ClientConnectionTest, Basic) {
  12180. httplib::ClientConnection conn;
  12181. EXPECT_FALSE(conn.is_open());
  12182. conn.sock = 1;
  12183. EXPECT_TRUE(conn.is_open());
  12184. httplib::ClientConnection conn2(std::move(conn));
  12185. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12186. conn2.sock = INVALID_SOCKET;
  12187. }
  12188. // Unified test server for all stream::* tests
  12189. class StreamApiTest : public ::testing::Test {
  12190. protected:
  12191. void SetUp() override {
  12192. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12193. res.set_content("Hello World!", "text/plain");
  12194. });
  12195. svr_.Get("/echo-params",
  12196. [](const httplib::Request &req, httplib::Response &res) {
  12197. std::string r;
  12198. for (const auto &p : req.params) {
  12199. if (!r.empty()) r += "&";
  12200. r += p.first + "=" + p.second;
  12201. }
  12202. res.set_content(r, "text/plain");
  12203. });
  12204. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12205. res.set_content(req.body, req.get_header_value("Content-Type"));
  12206. });
  12207. svr_.Post("/echo-headers",
  12208. [](const httplib::Request &req, httplib::Response &res) {
  12209. std::string r;
  12210. for (const auto &h : req.headers)
  12211. r += h.first + ": " + h.second + "\n";
  12212. res.set_content(r, "text/plain");
  12213. });
  12214. svr_.Post("/echo-params",
  12215. [](const httplib::Request &req, httplib::Response &res) {
  12216. std::string r = "params:";
  12217. for (const auto &p : req.params)
  12218. r += p.first + "=" + p.second + ";";
  12219. res.set_content(r + " body:" + req.body, "text/plain");
  12220. });
  12221. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12222. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12223. });
  12224. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12225. res.set_content("PUT:" + req.body, "text/plain");
  12226. });
  12227. svr_.Patch("/echo",
  12228. [](const httplib::Request &req, httplib::Response &res) {
  12229. res.set_content("PATCH:" + req.body, "text/plain");
  12230. });
  12231. svr_.Delete(
  12232. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12233. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12234. "text/plain");
  12235. });
  12236. svr_.Get("/head-test",
  12237. [](const httplib::Request &, httplib::Response &res) {
  12238. res.set_content("body for HEAD", "text/plain");
  12239. });
  12240. svr_.Options("/options",
  12241. [](const httplib::Request &, httplib::Response &res) {
  12242. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12243. });
  12244. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12245. svr_.wait_until_ready();
  12246. }
  12247. void TearDown() override {
  12248. svr_.stop();
  12249. if (thread_.joinable()) thread_.join();
  12250. }
  12251. httplib::Server svr_;
  12252. std::thread thread_;
  12253. };
  12254. // stream::Get tests
  12255. TEST_F(StreamApiTest, GetBasic) {
  12256. httplib::Client cli(HOST, PORT);
  12257. auto result = httplib::stream::Get(cli, "/hello");
  12258. ASSERT_TRUE(result.is_valid());
  12259. EXPECT_EQ(200, result.status());
  12260. EXPECT_EQ("Hello World!", read_body(result));
  12261. }
  12262. TEST_F(StreamApiTest, GetWithParams) {
  12263. httplib::Client cli(HOST, PORT);
  12264. httplib::Params params{{"foo", "bar"}};
  12265. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12266. ASSERT_TRUE(result.is_valid());
  12267. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12268. }
  12269. TEST_F(StreamApiTest, GetConnectionError) {
  12270. httplib::Client cli(HOST, 9999);
  12271. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12272. }
  12273. TEST_F(StreamApiTest, Get404) {
  12274. httplib::Client cli(HOST, PORT);
  12275. auto result = httplib::stream::Get(cli, "/nonexistent");
  12276. EXPECT_TRUE(result.is_valid());
  12277. EXPECT_EQ(404, result.status());
  12278. }
  12279. // stream::Post tests
  12280. TEST_F(StreamApiTest, PostBasic) {
  12281. httplib::Client cli(HOST, PORT);
  12282. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12283. "application/json");
  12284. ASSERT_TRUE(result.is_valid());
  12285. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12286. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12287. }
  12288. TEST_F(StreamApiTest, PostWithHeaders) {
  12289. httplib::Client cli(HOST, PORT);
  12290. httplib::Headers headers{{"X-Custom", "value"}};
  12291. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12292. "text/plain");
  12293. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12294. }
  12295. TEST_F(StreamApiTest, PostWithParams) {
  12296. httplib::Client cli(HOST, PORT);
  12297. httplib::Params params{{"k", "v"}};
  12298. auto result =
  12299. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12300. auto body = read_body(result);
  12301. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12302. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12303. }
  12304. TEST_F(StreamApiTest, PostLarge) {
  12305. httplib::Client cli(HOST, PORT);
  12306. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12307. size_t total = 0;
  12308. while (result.next()) {
  12309. total += result.size();
  12310. }
  12311. EXPECT_EQ(100u * 1024u, total);
  12312. }
  12313. // stream::Put/Patch tests
  12314. TEST_F(StreamApiTest, PutAndPatch) {
  12315. httplib::Client cli(HOST, PORT);
  12316. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12317. EXPECT_EQ("PUT:test", read_body(put));
  12318. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12319. EXPECT_EQ("PATCH:test", read_body(patch));
  12320. }
  12321. // stream::Delete tests
  12322. TEST_F(StreamApiTest, Delete) {
  12323. httplib::Client cli(HOST, PORT);
  12324. auto del1 = httplib::stream::Delete(cli, "/resource");
  12325. EXPECT_EQ("Deleted", read_body(del1));
  12326. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12327. EXPECT_EQ("Deleted:data", read_body(del2));
  12328. }
  12329. // stream::Head/Options tests
  12330. TEST_F(StreamApiTest, HeadAndOptions) {
  12331. httplib::Client cli(HOST, PORT);
  12332. auto head = httplib::stream::Head(cli, "/head-test");
  12333. EXPECT_TRUE(head.is_valid());
  12334. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12335. auto opts = httplib::stream::Options(cli, "/options");
  12336. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12337. }
  12338. // SSL stream::* tests
  12339. #ifdef CPPHTTPLIB_SSL_ENABLED
  12340. class SSLStreamApiTest : public ::testing::Test {
  12341. protected:
  12342. void SetUp() override {
  12343. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12344. res.set_content("Hello SSL!", "text/plain");
  12345. });
  12346. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12347. res.set_content(req.body, "text/plain");
  12348. });
  12349. port_ = svr_.bind_to_any_port("127.0.0.1");
  12350. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12351. svr_.wait_until_ready();
  12352. }
  12353. void TearDown() override {
  12354. svr_.stop();
  12355. if (thread_.joinable()) thread_.join();
  12356. }
  12357. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12358. std::thread thread_;
  12359. int port_ = 0;
  12360. };
  12361. TEST_F(SSLStreamApiTest, GetAndPost) {
  12362. httplib::SSLClient cli("127.0.0.1", port_);
  12363. cli.enable_server_certificate_verification(false);
  12364. auto get = httplib::stream::Get(cli, "/hello");
  12365. EXPECT_EQ("Hello SSL!", read_body(get));
  12366. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12367. EXPECT_EQ("test", read_body(post));
  12368. }
  12369. #endif
  12370. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12371. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12372. // BodyReader
  12373. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12374. // Test that read timeout during streaming is detected
  12375. // Use a large content-length response where server delays mid-stream
  12376. Server svr;
  12377. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12378. // Send a large response with delay in the middle
  12379. res.set_content_provider(
  12380. 1000, // content_length
  12381. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12382. if (offset < 100) {
  12383. // Send first 100 bytes immediately
  12384. std::string data(100, 'A');
  12385. sink.write(data.c_str(), data.size());
  12386. return true;
  12387. }
  12388. // Then delay longer than client timeout
  12389. std::this_thread::sleep_for(std::chrono::seconds(3));
  12390. std::string data(900, 'B');
  12391. sink.write(data.c_str(), data.size());
  12392. return true;
  12393. });
  12394. });
  12395. auto port = 8091;
  12396. std::thread t([&]() { svr.listen("localhost", port); });
  12397. svr.wait_until_ready();
  12398. Client cli("localhost", port);
  12399. cli.set_read_timeout(1, 0); // 1 second timeout
  12400. auto handle = cli.open_stream("GET", "/slow-stream");
  12401. ASSERT_TRUE(handle.is_valid());
  12402. char buf[256];
  12403. ssize_t total = 0;
  12404. ssize_t n;
  12405. bool got_error = false;
  12406. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12407. total += n;
  12408. }
  12409. if (n < 0) {
  12410. got_error = true;
  12411. // Should be timeout or read error
  12412. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12413. handle.get_read_error() == Error::Read)
  12414. << "Actual error: " << to_string(handle.get_read_error());
  12415. }
  12416. // Either we got an error, or we got less data than expected
  12417. EXPECT_TRUE(got_error || total < 1000)
  12418. << "Expected timeout but got all " << total << " bytes";
  12419. svr.stop();
  12420. t.join();
  12421. }
  12422. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12423. // Test connection closed detection via BodyReader
  12424. Server svr;
  12425. std::atomic<bool> close_now{false};
  12426. svr.Get("/will-close", [&](const Request &, Response &res) {
  12427. res.set_content_provider(
  12428. 10000, // Large content_length that we won't fully send
  12429. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12430. if (offset < 100) {
  12431. std::string data(100, 'X');
  12432. sink.write(data.c_str(), data.size());
  12433. return true;
  12434. }
  12435. // Wait for signal then abort
  12436. while (!close_now) {
  12437. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12438. }
  12439. return false; // Abort - server will close connection
  12440. });
  12441. });
  12442. auto port = 8092;
  12443. std::thread t([&]() { svr.listen("localhost", port); });
  12444. svr.wait_until_ready();
  12445. Client cli("localhost", port);
  12446. auto handle = cli.open_stream("GET", "/will-close");
  12447. ASSERT_TRUE(handle.is_valid());
  12448. char buf[256];
  12449. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12450. EXPECT_GT(n, 0) << "First read should succeed";
  12451. // Signal server to close
  12452. close_now = true;
  12453. // Keep reading until error or EOF
  12454. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12455. // Keep reading
  12456. }
  12457. // Should get an error since content_length wasn't satisfied
  12458. if (n < 0) {
  12459. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12460. handle.get_read_error() == Error::Read)
  12461. << "Actual error: " << to_string(handle.get_read_error());
  12462. }
  12463. svr.stop();
  12464. t.join();
  12465. }
  12466. #ifdef CPPHTTPLIB_SSL_ENABLED
  12467. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12468. // Test that read timeout during SSL streaming is detected
  12469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12470. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12471. res.set_content_provider(
  12472. 1000, "text/plain",
  12473. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12474. if (offset < 100) {
  12475. std::string data(100, 'A');
  12476. sink.write(data.c_str(), data.size());
  12477. return true;
  12478. }
  12479. std::this_thread::sleep_for(std::chrono::seconds(3));
  12480. std::string data(900, 'B');
  12481. sink.write(data.c_str(), data.size());
  12482. return true;
  12483. });
  12484. });
  12485. auto port = 8093;
  12486. std::thread t([&]() { svr.listen("localhost", port); });
  12487. svr.wait_until_ready();
  12488. SSLClient cli("localhost", port);
  12489. cli.enable_server_certificate_verification(false);
  12490. cli.set_read_timeout(1, 0); // 1 second timeout
  12491. auto handle = cli.open_stream("GET", "/slow-stream");
  12492. ASSERT_TRUE(handle.is_valid());
  12493. char buf[256];
  12494. ssize_t total = 0;
  12495. ssize_t n;
  12496. bool got_error = false;
  12497. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12498. total += n;
  12499. }
  12500. if (n < 0) {
  12501. got_error = true;
  12502. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12503. handle.get_read_error() == Error::Read)
  12504. << "Actual error: " << to_string(handle.get_read_error());
  12505. }
  12506. EXPECT_TRUE(got_error || total < 1000)
  12507. << "Expected timeout but got all " << total << " bytes";
  12508. svr.stop();
  12509. t.join();
  12510. }
  12511. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12512. // Test SSL connection closed detection
  12513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12514. std::atomic<bool> close_now{false};
  12515. svr.Get("/will-close", [&](const Request &, Response &res) {
  12516. res.set_content_provider(
  12517. 10000, "text/plain",
  12518. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12519. if (offset < 100) {
  12520. std::string data(100, 'X');
  12521. sink.write(data.c_str(), data.size());
  12522. return true;
  12523. }
  12524. while (!close_now) {
  12525. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12526. }
  12527. return false;
  12528. });
  12529. });
  12530. auto port = 8094;
  12531. std::thread t([&]() { svr.listen("localhost", port); });
  12532. svr.wait_until_ready();
  12533. SSLClient cli("localhost", port);
  12534. cli.enable_server_certificate_verification(false);
  12535. auto handle = cli.open_stream("GET", "/will-close");
  12536. ASSERT_TRUE(handle.is_valid());
  12537. char buf[256];
  12538. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12539. EXPECT_GT(n, 0);
  12540. // Signal server to close
  12541. close_now = true;
  12542. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12543. // Keep reading
  12544. }
  12545. if (n < 0) {
  12546. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12547. handle.get_read_error() == Error::Read)
  12548. << "Actual error: " << to_string(handle.get_read_error());
  12549. }
  12550. svr.stop();
  12551. t.join();
  12552. }
  12553. #endif
  12554. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12555. using namespace httplib;
  12556. // Create a test file
  12557. const char *fname = "etag_testfile.txt";
  12558. const char *content = "etag-content";
  12559. {
  12560. std::ofstream ofs(fname);
  12561. ofs << content;
  12562. ASSERT_TRUE(ofs.good());
  12563. }
  12564. Server svr;
  12565. svr.set_mount_point("/static", ".");
  12566. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12567. svr.wait_until_ready();
  12568. Client cli(HOST, PORT);
  12569. // First request: should get 200 with ETag header
  12570. auto res1 = cli.Get("/static/etag_testfile.txt");
  12571. ASSERT_TRUE(res1);
  12572. ASSERT_EQ(200, res1->status);
  12573. ASSERT_TRUE(res1->has_header("ETag"));
  12574. std::string etag = res1->get_header_value("ETag");
  12575. EXPECT_FALSE(etag.empty());
  12576. // Verify ETag format: W/"hex-hex"
  12577. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12578. EXPECT_EQ('W', etag[0]);
  12579. EXPECT_EQ('/', etag[1]);
  12580. EXPECT_EQ('"', etag[2]);
  12581. EXPECT_EQ('"', etag.back());
  12582. // Exact match: expect 304 Not Modified
  12583. Headers h2 = {{"If-None-Match", etag}};
  12584. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12585. ASSERT_TRUE(res2);
  12586. EXPECT_EQ(304, res2->status);
  12587. // Wildcard match: expect 304 Not Modified
  12588. Headers h3 = {{"If-None-Match", "*"}};
  12589. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12590. ASSERT_TRUE(res3);
  12591. EXPECT_EQ(304, res3->status);
  12592. // Non-matching ETag: expect 200
  12593. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12594. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12595. ASSERT_TRUE(res4);
  12596. EXPECT_EQ(200, res4->status);
  12597. // Multiple ETags with one matching: expect 304
  12598. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12599. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12600. ASSERT_TRUE(res5);
  12601. EXPECT_EQ(304, res5->status);
  12602. svr.stop();
  12603. t.join();
  12604. std::remove(fname);
  12605. }
  12606. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12607. using namespace httplib;
  12608. Server svr;
  12609. svr.set_mount_point("/static", ".");
  12610. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12611. svr.wait_until_ready();
  12612. Client cli(HOST, PORT);
  12613. // Send If-None-Match: * to a non-existent file
  12614. Headers h = {{"If-None-Match", "*"}};
  12615. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12616. ASSERT_TRUE(res);
  12617. EXPECT_EQ(404, res->status);
  12618. svr.stop();
  12619. t.join();
  12620. }
  12621. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12622. using namespace httplib;
  12623. // Create a test file
  12624. const char *fname = "etag_boundary_testfile.txt";
  12625. const char *content = "boundary-test";
  12626. {
  12627. std::ofstream ofs(fname);
  12628. ofs << content;
  12629. ASSERT_TRUE(ofs.good());
  12630. }
  12631. Server svr;
  12632. svr.set_mount_point("/static", ".");
  12633. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12634. svr.wait_until_ready();
  12635. Client cli(HOST, PORT);
  12636. // Get the actual ETag
  12637. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12638. ASSERT_TRUE(res1);
  12639. ASSERT_EQ(200, res1->status);
  12640. ASSERT_TRUE(res1->has_header("ETag"));
  12641. std::string etag = res1->get_header_value("ETag");
  12642. // Test 1: Very long ETag value (longer than actual ETag)
  12643. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12644. Headers h1 = {{"If-None-Match", "W/"
  12645. "\"very-long-etag-value-that-is-much-longer-"
  12646. "than-the-actual-etag-value\""}};
  12647. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12648. ASSERT_TRUE(res2);
  12649. EXPECT_EQ(200, res2->status); // Should not match
  12650. // Test 2: Long string followed by wildcard
  12651. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12652. // string)
  12653. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12654. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12655. ASSERT_TRUE(res3);
  12656. EXPECT_EQ(304, res3->status); // Should match on "*"
  12657. // Test 3: Wildcard followed by long string
  12658. // Should match on "*" immediately and return 304
  12659. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12660. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12661. ASSERT_TRUE(res4);
  12662. EXPECT_EQ(304, res4->status); // Should match on "*"
  12663. // Test 4: Multiple long non-matching values
  12664. // Should NOT match and return 200 (test that all comparisons are safe)
  12665. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12666. "W/\"second-long-non-matching-value\", "
  12667. "W/\"third-long-non-matching-value\""}};
  12668. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12669. ASSERT_TRUE(res5);
  12670. EXPECT_EQ(200, res5->status); // Should not match
  12671. // Test 5: Single character that is not "*" (edge case)
  12672. Headers h5 = {{"If-None-Match", "X"}};
  12673. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12674. ASSERT_TRUE(res6);
  12675. EXPECT_EQ(200, res6->status); // Should not match
  12676. svr.stop();
  12677. t.join();
  12678. std::remove(fname);
  12679. }
  12680. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12681. using namespace httplib;
  12682. // Create a test file
  12683. const char *fname = "ims_testfile.txt";
  12684. const char *content = "if-modified-since-test";
  12685. {
  12686. std::ofstream ofs(fname);
  12687. ofs << content;
  12688. ASSERT_TRUE(ofs.good());
  12689. }
  12690. Server svr;
  12691. svr.set_mount_point("/static", ".");
  12692. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12693. svr.wait_until_ready();
  12694. Client cli(HOST, PORT);
  12695. // First request: should get 200 with Last-Modified header
  12696. auto res1 = cli.Get("/static/ims_testfile.txt");
  12697. ASSERT_TRUE(res1);
  12698. ASSERT_EQ(200, res1->status);
  12699. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12700. std::string last_modified = res1->get_header_value("Last-Modified");
  12701. EXPECT_FALSE(last_modified.empty());
  12702. // If-Modified-Since with same time: expect 304
  12703. Headers h2 = {{"If-Modified-Since", last_modified}};
  12704. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12705. ASSERT_TRUE(res2);
  12706. EXPECT_EQ(304, res2->status);
  12707. // If-Modified-Since with future time: expect 304
  12708. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12709. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12710. ASSERT_TRUE(res3);
  12711. EXPECT_EQ(304, res3->status);
  12712. // If-Modified-Since with past time: expect 200
  12713. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12714. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12715. ASSERT_TRUE(res4);
  12716. EXPECT_EQ(200, res4->status);
  12717. // If-None-Match takes precedence over If-Modified-Since
  12718. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12719. ASSERT_TRUE(res1->has_header("ETag"));
  12720. std::string etag = res1->get_header_value("ETag");
  12721. Headers h5 = {{"If-None-Match", etag},
  12722. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12723. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12724. ASSERT_TRUE(res5);
  12725. EXPECT_EQ(304, res5->status);
  12726. svr.stop();
  12727. t.join();
  12728. std::remove(fname);
  12729. }
  12730. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12731. using namespace httplib;
  12732. Server svr;
  12733. // Endpoint that returns compressible content
  12734. svr.Get("/compressible", [](const Request &, Response &res) {
  12735. // Return a large enough body to trigger compression
  12736. std::string body(1000, 'a');
  12737. res.set_content(body, "text/plain");
  12738. });
  12739. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12740. svr.wait_until_ready();
  12741. Client cli(HOST, PORT);
  12742. // Request with gzip support: should get Vary header when compressed
  12743. cli.set_compress(true);
  12744. auto res1 = cli.Get("/compressible");
  12745. ASSERT_TRUE(res1);
  12746. EXPECT_EQ(200, res1->status);
  12747. // If Content-Encoding is set, Vary should also be set
  12748. if (res1->has_header("Content-Encoding")) {
  12749. EXPECT_TRUE(res1->has_header("Vary"));
  12750. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12751. }
  12752. // Request without Accept-Encoding header: should not have compression
  12753. Headers h_no_compress;
  12754. auto res2 = cli.Get("/compressible", h_no_compress);
  12755. ASSERT_TRUE(res2);
  12756. EXPECT_EQ(200, res2->status);
  12757. // Verify Vary header is present when compression is applied
  12758. // (the exact behavior depends on server configuration)
  12759. svr.stop();
  12760. t.join();
  12761. }
  12762. TEST(ETagTest, IfRangeWithETag) {
  12763. using namespace httplib;
  12764. // Create a test file with known content
  12765. const char *fname = "if_range_testfile.txt";
  12766. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12767. {
  12768. std::ofstream ofs(fname);
  12769. ofs << content;
  12770. ASSERT_TRUE(ofs.good());
  12771. }
  12772. Server svr;
  12773. svr.set_mount_point("/static", ".");
  12774. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12775. svr.wait_until_ready();
  12776. Client cli(HOST, PORT);
  12777. // First request: get ETag
  12778. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12779. ASSERT_TRUE(res1);
  12780. ASSERT_EQ(200, res1->status);
  12781. ASSERT_TRUE(res1->has_header("ETag"));
  12782. std::string etag = res1->get_header_value("ETag");
  12783. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12784. // Since our server generates weak ETags (W/"..."), If-Range with our
  12785. // ETag should NOT result in partial content - it should return full content.
  12786. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12787. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12788. ASSERT_TRUE(res2);
  12789. // Weak ETag in If-Range -> full content (200), not partial (206)
  12790. EXPECT_EQ(200, res2->status);
  12791. EXPECT_EQ(content, res2->body);
  12792. EXPECT_FALSE(res2->has_header("Content-Range"));
  12793. // Range request with non-matching If-Range (ETag): should get 200 (full
  12794. // content)
  12795. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12796. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12797. ASSERT_TRUE(res3);
  12798. EXPECT_EQ(200, res3->status);
  12799. EXPECT_EQ(content, res3->body);
  12800. EXPECT_FALSE(res3->has_header("Content-Range"));
  12801. // Range request with strong ETag (hypothetical - our server doesn't generate
  12802. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12803. // should return full content)
  12804. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12805. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12806. ASSERT_TRUE(res4);
  12807. EXPECT_EQ(200, res4->status);
  12808. EXPECT_EQ(content, res4->body);
  12809. EXPECT_FALSE(res4->has_header("Content-Range"));
  12810. svr.stop();
  12811. t.join();
  12812. std::remove(fname);
  12813. }
  12814. TEST(ETagTest, IfRangeWithDate) {
  12815. using namespace httplib;
  12816. // Create a test file
  12817. const char *fname = "if_range_date_testfile.txt";
  12818. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12819. {
  12820. std::ofstream ofs(fname);
  12821. ofs << content;
  12822. ASSERT_TRUE(ofs.good());
  12823. }
  12824. Server svr;
  12825. svr.set_mount_point("/static", ".");
  12826. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12827. svr.wait_until_ready();
  12828. Client cli(HOST, PORT);
  12829. // First request: get Last-Modified
  12830. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12831. ASSERT_TRUE(res1);
  12832. ASSERT_EQ(200, res1->status);
  12833. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12834. std::string last_modified = res1->get_header_value("Last-Modified");
  12835. // Range request with matching If-Range (date): should get 206
  12836. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12837. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12838. ASSERT_TRUE(res2);
  12839. EXPECT_EQ(206, res2->status);
  12840. EXPECT_EQ("FGHIJ", res2->body);
  12841. // Range request with old If-Range date: should get 200 (full content)
  12842. Headers h3 = {{"Range", "bytes=5-9"},
  12843. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12844. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12845. ASSERT_TRUE(res3);
  12846. EXPECT_EQ(200, res3->status);
  12847. EXPECT_EQ(content, res3->body);
  12848. // Range request with future If-Range date: should get 206
  12849. Headers h4 = {{"Range", "bytes=0-4"},
  12850. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12851. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12852. ASSERT_TRUE(res4);
  12853. EXPECT_EQ(206, res4->status);
  12854. EXPECT_EQ("ABCDE", res4->body);
  12855. svr.stop();
  12856. t.join();
  12857. std::remove(fname);
  12858. }
  12859. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12860. using namespace httplib;
  12861. const char *fname = "etag_malformed.txt";
  12862. const char *content = "malformed-etag";
  12863. {
  12864. std::ofstream ofs(fname);
  12865. ofs << content;
  12866. ASSERT_TRUE(ofs.good());
  12867. }
  12868. Server svr;
  12869. svr.set_mount_point("/static", ".");
  12870. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12871. svr.wait_until_ready();
  12872. Client cli(HOST, PORT);
  12873. // baseline: should get 200 and an ETag
  12874. auto res1 = cli.Get("/static/etag_malformed.txt");
  12875. ASSERT_TRUE(res1);
  12876. ASSERT_EQ(200, res1->status);
  12877. ASSERT_TRUE(res1->has_header("ETag"));
  12878. // Malformed ETag value (missing quotes) should be treated as non-matching
  12879. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12880. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12881. ASSERT_TRUE(res_bad);
  12882. EXPECT_EQ(200, res_bad->status);
  12883. // Whitespace-only header value should be considered invalid / non-matching
  12884. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12885. "Host: localhost\r\n"
  12886. "If-None-Match: \r\n"
  12887. "Connection: close\r\n"
  12888. "\r\n";
  12889. std::string out;
  12890. ASSERT_TRUE(send_request(5, raw_req, &out));
  12891. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12892. svr.stop();
  12893. t.join();
  12894. std::remove(fname);
  12895. }
  12896. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12897. using namespace httplib;
  12898. const char *fname = "ims_invalid_format.txt";
  12899. const char *content = "ims-bad-format";
  12900. {
  12901. std::ofstream ofs(fname);
  12902. ofs << content;
  12903. ASSERT_TRUE(ofs.good());
  12904. }
  12905. Server svr;
  12906. svr.set_mount_point("/static", ".");
  12907. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12908. svr.wait_until_ready();
  12909. Client cli(HOST, PORT);
  12910. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12911. ASSERT_TRUE(res1);
  12912. ASSERT_EQ(200, res1->status);
  12913. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12914. // If-Modified-Since with invalid format should not result in 304
  12915. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12916. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12917. ASSERT_TRUE(res_bad);
  12918. EXPECT_EQ(200, res_bad->status);
  12919. // If-Range with invalid date format should be treated as mismatch -> full
  12920. // content (200)
  12921. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12922. {"If-Range", "invalid-date"}};
  12923. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12924. ASSERT_TRUE(res_ifrange);
  12925. EXPECT_EQ(200, res_ifrange->status);
  12926. svr.stop();
  12927. t.join();
  12928. std::remove(fname);
  12929. }
  12930. TEST(ETagTest, IfRangeWithMalformedETag) {
  12931. using namespace httplib;
  12932. const char *fname = "ifrange_malformed.txt";
  12933. const std::string content = "0123456789";
  12934. {
  12935. std::ofstream ofs(fname);
  12936. ofs << content;
  12937. ASSERT_TRUE(ofs.good());
  12938. }
  12939. Server svr;
  12940. svr.set_mount_point("/static", ".");
  12941. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12942. svr.wait_until_ready();
  12943. Client cli(HOST, PORT);
  12944. // First request: get ETag
  12945. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12946. ASSERT_TRUE(res1);
  12947. ASSERT_EQ(200, res1->status);
  12948. ASSERT_TRUE(res1->has_header("ETag"));
  12949. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12950. // full content (200)
  12951. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12952. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12953. ASSERT_TRUE(res2);
  12954. EXPECT_EQ(200, res2->status);
  12955. EXPECT_EQ(content, res2->body);
  12956. svr.stop();
  12957. t.join();
  12958. std::remove(fname);
  12959. }
  12960. TEST(ETagTest, ExtremeLargeDateValues) {
  12961. using namespace httplib;
  12962. const char *fname = "ims_extreme_date.txt";
  12963. const char *content = "ims-extreme-date";
  12964. {
  12965. std::ofstream ofs(fname);
  12966. ofs << content;
  12967. ASSERT_TRUE(ofs.good());
  12968. }
  12969. Server svr;
  12970. svr.set_mount_point("/static", ".");
  12971. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12972. svr.wait_until_ready();
  12973. Client cli(HOST, PORT);
  12974. auto res1 = cli.Get(std::string("/static/") + fname);
  12975. ASSERT_TRUE(res1);
  12976. ASSERT_EQ(200, res1->status);
  12977. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12978. // Extremely large year that may overflow date parsing routines.
  12979. Headers h_large_date = {
  12980. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12981. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12982. ASSERT_TRUE(res_bad);
  12983. // Expect server to treat this as invalid/mismatch and return full content
  12984. EXPECT_EQ(200, res_bad->status);
  12985. // If-Range with extremely large date should be treated as mismatch -> full
  12986. // content (200)
  12987. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12988. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12989. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12990. ASSERT_TRUE(res_ifrange);
  12991. EXPECT_EQ(200, res_ifrange->status);
  12992. svr.stop();
  12993. t.join();
  12994. std::remove(fname);
  12995. }
  12996. TEST(ETagTest, NegativeFileModificationTime) {
  12997. using namespace httplib;
  12998. const char *fname = "ims_negative_mtime.txt";
  12999. const std::string content = "negative-mtime";
  13000. {
  13001. std::ofstream ofs(fname);
  13002. ofs << content;
  13003. ASSERT_TRUE(ofs.good());
  13004. }
  13005. // Try to set file mtime to a negative value. This may fail on some
  13006. // platforms/filesystems; if it fails, the test will still verify server
  13007. // behaves safely by performing a regular conditional request.
  13008. #if defined(__APPLE__) || defined(__linux__)
  13009. bool set_negative = false;
  13010. do {
  13011. struct timeval times[2];
  13012. // access time: now
  13013. times[0].tv_sec = time(nullptr);
  13014. times[0].tv_usec = 0;
  13015. // modification time: negative (e.g., -1)
  13016. times[1].tv_sec = -1;
  13017. times[1].tv_usec = 0;
  13018. if (utimes(fname, times) == 0) { set_negative = true; }
  13019. } while (0);
  13020. #else
  13021. bool set_negative = false;
  13022. #endif
  13023. Server svr;
  13024. svr.set_mount_point("/static", ".");
  13025. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13026. svr.wait_until_ready();
  13027. Client cli(HOST, PORT);
  13028. auto res1 = cli.Get(std::string("/static/") + fname);
  13029. ASSERT_TRUE(res1);
  13030. ASSERT_EQ(200, res1->status);
  13031. bool has_last_modified = res1->has_header("Last-Modified");
  13032. std::string last_modified;
  13033. if (has_last_modified) {
  13034. last_modified = res1->get_header_value("Last-Modified");
  13035. }
  13036. if (set_negative) {
  13037. // If we successfully set a negative mtime, ensure server returns a
  13038. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13039. // with an old date and ensure server handles it without crash.
  13040. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13041. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13042. ASSERT_TRUE(res2);
  13043. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13044. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13045. } else {
  13046. // Could not set negative mtime on this platform; fall back to verifying
  13047. // that normal invalid/malformed dates are treated safely (non-304).
  13048. Headers h_bad_date = {
  13049. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13050. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13051. ASSERT_TRUE(res_bad);
  13052. EXPECT_EQ(200, res_bad->status);
  13053. }
  13054. svr.stop();
  13055. t.join();
  13056. std::remove(fname);
  13057. }
  13058. //==============================================================================
  13059. // SSE Parsing Tests
  13060. //==============================================================================
  13061. class SSEParsingTest : public ::testing::Test {
  13062. protected:
  13063. // Test helper that mimics SSE parsing behavior
  13064. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13065. int &retry_ms) {
  13066. // Blank line signals end of event
  13067. if (line.empty() || line == "\r") { return true; }
  13068. // Lines starting with ':' are comments (ignored)
  13069. if (!line.empty() && line[0] == ':') { return false; }
  13070. // Find the colon separator
  13071. auto colon_pos = line.find(':');
  13072. if (colon_pos == std::string::npos) {
  13073. // Line with no colon is treated as field name with empty value
  13074. return false;
  13075. }
  13076. std::string field = line.substr(0, colon_pos);
  13077. std::string value;
  13078. // Value starts after colon, skip optional single space
  13079. if (colon_pos + 1 < line.size()) {
  13080. size_t value_start = colon_pos + 1;
  13081. if (line[value_start] == ' ') { value_start++; }
  13082. value = line.substr(value_start);
  13083. // Remove trailing \r if present
  13084. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13085. }
  13086. // Handle known fields
  13087. if (field == "event") {
  13088. msg.event = value;
  13089. } else if (field == "data") {
  13090. // Multiple data lines are concatenated with newlines
  13091. if (!msg.data.empty()) { msg.data += "\n"; }
  13092. msg.data += value;
  13093. } else if (field == "id") {
  13094. // Empty id is valid (clears the last event ID)
  13095. msg.id = value;
  13096. } else if (field == "retry") {
  13097. // Parse retry interval in milliseconds
  13098. {
  13099. int v = 0;
  13100. auto res =
  13101. detail::from_chars(value.data(), value.data() + value.size(), v);
  13102. if (res.ec == std::errc{}) { retry_ms = v; }
  13103. }
  13104. }
  13105. // Unknown fields are ignored per SSE spec
  13106. return false;
  13107. }
  13108. };
  13109. // Test: Single-line data
  13110. TEST_F(SSEParsingTest, SingleLineData) {
  13111. sse::SSEMessage msg;
  13112. int retry_ms = 3000;
  13113. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13114. EXPECT_EQ(msg.data, "hello");
  13115. EXPECT_EQ(msg.event, "message");
  13116. // Blank line ends event
  13117. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13118. }
  13119. // Test: Multi-line data
  13120. TEST_F(SSEParsingTest, MultiLineData) {
  13121. sse::SSEMessage msg;
  13122. int retry_ms = 3000;
  13123. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13124. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13125. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13126. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13127. }
  13128. // Test: Custom event types
  13129. TEST_F(SSEParsingTest, CustomEventType) {
  13130. sse::SSEMessage msg;
  13131. int retry_ms = 3000;
  13132. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13133. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13134. EXPECT_EQ(msg.event, "update");
  13135. EXPECT_EQ(msg.data, "payload");
  13136. }
  13137. // Test: Event ID handling
  13138. TEST_F(SSEParsingTest, EventIdHandling) {
  13139. sse::SSEMessage msg;
  13140. int retry_ms = 3000;
  13141. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13142. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13143. EXPECT_EQ(msg.id, "12345");
  13144. }
  13145. // Test: Empty event ID (clears last event ID)
  13146. TEST_F(SSEParsingTest, EmptyEventId) {
  13147. sse::SSEMessage msg;
  13148. msg.id = "previous";
  13149. int retry_ms = 3000;
  13150. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13151. EXPECT_EQ(msg.id, "");
  13152. }
  13153. // Test: Retry field parsing
  13154. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13155. sse::SSEMessage msg;
  13156. int retry_ms = 3000;
  13157. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13158. EXPECT_EQ(retry_ms, 5000);
  13159. }
  13160. // Test: Invalid retry value
  13161. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13162. sse::SSEMessage msg;
  13163. int retry_ms = 3000;
  13164. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13165. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13166. }
  13167. // Test: Comments (lines starting with :)
  13168. TEST_F(SSEParsingTest, CommentsIgnored) {
  13169. sse::SSEMessage msg;
  13170. int retry_ms = 3000;
  13171. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13172. EXPECT_EQ(msg.data, "");
  13173. EXPECT_EQ(msg.event, "message");
  13174. }
  13175. // Test: Colon in value
  13176. TEST_F(SSEParsingTest, ColonInValue) {
  13177. sse::SSEMessage msg;
  13178. int retry_ms = 3000;
  13179. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13180. EXPECT_EQ(msg.data, "hello:world:test");
  13181. }
  13182. // Test: Line with no colon (field name only)
  13183. TEST_F(SSEParsingTest, FieldNameOnly) {
  13184. sse::SSEMessage msg;
  13185. int retry_ms = 3000;
  13186. // According to SSE spec, this is treated as field name with empty value
  13187. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13188. // Since we don't recognize "data" without colon, data should be empty
  13189. EXPECT_EQ(msg.data, "");
  13190. }
  13191. // Test: Trailing \r handling
  13192. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13193. sse::SSEMessage msg;
  13194. int retry_ms = 3000;
  13195. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13196. EXPECT_EQ(msg.data, "hello");
  13197. }
  13198. // Test: Unknown fields ignored
  13199. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13200. sse::SSEMessage msg;
  13201. int retry_ms = 3000;
  13202. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13203. EXPECT_EQ(msg.data, "");
  13204. EXPECT_EQ(msg.event, "message");
  13205. }
  13206. // Test: Space after colon is optional
  13207. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13208. sse::SSEMessage msg1, msg2;
  13209. int retry_ms = 3000;
  13210. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13211. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13212. EXPECT_EQ(msg1.data, "hello");
  13213. EXPECT_EQ(msg2.data, "hello");
  13214. }
  13215. // Test: SSEMessage clear
  13216. TEST_F(SSEParsingTest, MessageClear) {
  13217. sse::SSEMessage msg;
  13218. msg.event = "custom";
  13219. msg.data = "some data";
  13220. msg.id = "123";
  13221. msg.clear();
  13222. EXPECT_EQ(msg.event, "message");
  13223. EXPECT_EQ(msg.data, "");
  13224. EXPECT_EQ(msg.id, "");
  13225. }
  13226. // Test: Complete event parsing
  13227. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13228. sse::SSEMessage msg;
  13229. int retry_ms = 3000;
  13230. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13231. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13232. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13233. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13234. // Blank line ends event
  13235. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13236. EXPECT_EQ(msg.event, "notification");
  13237. EXPECT_EQ(msg.id, "evt-42");
  13238. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13239. EXPECT_EQ(retry_ms, 1000);
  13240. }
  13241. //==============================================================================
  13242. // Integration Tests with Server
  13243. //==============================================================================
  13244. class SSEIntegrationTest : public ::testing::Test {
  13245. protected:
  13246. void SetUp() override {
  13247. stop_server_.store(false);
  13248. events_.clear();
  13249. server_ = httplib::detail::make_unique<Server>();
  13250. setup_server();
  13251. start_server();
  13252. }
  13253. void TearDown() override {
  13254. stop_server_.store(true);
  13255. event_cv_.notify_all();
  13256. server_->stop();
  13257. if (server_thread_.joinable()) { server_thread_.join(); }
  13258. }
  13259. void setup_server() {
  13260. // Simple SSE endpoint
  13261. server_->Get("/events", [this](const Request &req, Response &res) {
  13262. auto last_id = req.get_header_value("Last-Event-ID");
  13263. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13264. res.set_chunked_content_provider(
  13265. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13266. std::unique_lock<std::mutex> lock(event_mutex_);
  13267. if (event_cv_.wait_for(
  13268. lock, std::chrono::milliseconds(200), [this] {
  13269. return !events_.empty() || stop_server_.load();
  13270. })) {
  13271. if (stop_server_.load()) { return false; }
  13272. if (!events_.empty()) {
  13273. std::string event = events_.front();
  13274. events_.erase(events_.begin());
  13275. sink.write(event.data(), event.size());
  13276. return true;
  13277. }
  13278. }
  13279. return !stop_server_.load();
  13280. });
  13281. });
  13282. // Endpoint that returns error
  13283. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13284. res.status = 500;
  13285. res.set_content("Internal Server Error", "text/plain");
  13286. });
  13287. // Endpoint for custom event types
  13288. server_->Get("/custom-events", [](const Request &, Response &res) {
  13289. res.set_chunked_content_provider(
  13290. "text/event-stream", [](size_t offset, DataSink &sink) {
  13291. if (offset == 0) {
  13292. std::string event = "event: update\ndata: updated\n\n"
  13293. "event: delete\ndata: deleted\n\n";
  13294. sink.write(event.data(), event.size());
  13295. }
  13296. return false; // End stream after sending
  13297. });
  13298. });
  13299. }
  13300. void start_server() {
  13301. port_ = server_->bind_to_any_port(HOST);
  13302. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13303. // Wait for server to start
  13304. while (!server_->is_running()) {
  13305. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13306. }
  13307. }
  13308. int get_port() const { return port_; }
  13309. void send_event(const std::string &event) {
  13310. std::lock_guard<std::mutex> lock(event_mutex_);
  13311. events_.push_back(event);
  13312. event_cv_.notify_all();
  13313. }
  13314. std::unique_ptr<Server> server_;
  13315. std::thread server_thread_;
  13316. std::mutex event_mutex_;
  13317. std::condition_variable event_cv_;
  13318. std::vector<std::string> events_;
  13319. std::atomic<bool> stop_server_{false};
  13320. std::string last_received_event_id_;
  13321. int port_ = 0;
  13322. };
  13323. // Test: Successful connection and on_open callback
  13324. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13325. // Add a simple endpoint that sends one event and closes
  13326. server_->Get("/simple-event", [](const Request &, Response &res) {
  13327. res.set_chunked_content_provider(
  13328. "text/event-stream", [](size_t offset, DataSink &sink) {
  13329. if (offset == 0) {
  13330. std::string event = "data: hello\n\n";
  13331. sink.write(event.data(), event.size());
  13332. }
  13333. return false; // Close stream after sending
  13334. });
  13335. });
  13336. Client client("localhost", get_port());
  13337. sse::SSEClient sse(client, "/simple-event");
  13338. std::atomic<bool> open_called{false};
  13339. std::atomic<bool> message_received{false};
  13340. sse.on_open([&open_called]() { open_called.store(true); });
  13341. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13342. if (msg.data == "hello") { message_received.store(true); }
  13343. });
  13344. sse.set_reconnect_interval(100);
  13345. sse.set_max_reconnect_attempts(1);
  13346. // Start async
  13347. sse.start_async();
  13348. // Wait for message to be processed
  13349. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13350. sse.stop();
  13351. EXPECT_TRUE(open_called.load());
  13352. EXPECT_TRUE(message_received.load());
  13353. }
  13354. // Test: on_message callback
  13355. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13356. // Endpoint that sends multiple events then closes
  13357. server_->Get("/multi-event", [](const Request &, Response &res) {
  13358. res.set_chunked_content_provider(
  13359. "text/event-stream", [](size_t offset, DataSink &sink) {
  13360. if (offset == 0) {
  13361. std::string events = "data: message1\n\ndata: message2\n\n";
  13362. sink.write(events.data(), events.size());
  13363. }
  13364. return false;
  13365. });
  13366. });
  13367. Client client("localhost", get_port());
  13368. sse::SSEClient sse(client, "/multi-event");
  13369. std::vector<std::string> received_messages;
  13370. std::mutex messages_mutex;
  13371. sse.on_message([&](const sse::SSEMessage &msg) {
  13372. std::lock_guard<std::mutex> lock(messages_mutex);
  13373. received_messages.push_back(msg.data);
  13374. });
  13375. sse.set_reconnect_interval(100);
  13376. sse.set_max_reconnect_attempts(1);
  13377. sse.start_async();
  13378. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13379. sse.stop();
  13380. std::lock_guard<std::mutex> lock(messages_mutex);
  13381. EXPECT_GE(received_messages.size(), 2u);
  13382. if (received_messages.size() >= 2) {
  13383. EXPECT_EQ(received_messages[0], "message1");
  13384. EXPECT_EQ(received_messages[1], "message2");
  13385. }
  13386. }
  13387. // Test: on_event for specific types
  13388. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13389. Client client("localhost", get_port());
  13390. sse::SSEClient sse(client, "/custom-events");
  13391. std::atomic<bool> update_received{false};
  13392. std::atomic<bool> delete_received{false};
  13393. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13394. if (msg.data == "updated") { update_received.store(true); }
  13395. });
  13396. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13397. if (msg.data == "deleted") { delete_received.store(true); }
  13398. });
  13399. sse.set_max_reconnect_attempts(1);
  13400. sse.start_async();
  13401. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13402. sse.stop();
  13403. EXPECT_TRUE(update_received.load());
  13404. EXPECT_TRUE(delete_received.load());
  13405. }
  13406. // Test: on_error callback on connection failure
  13407. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13408. // Connect to a non-existent port
  13409. Client client("localhost", 59999);
  13410. sse::SSEClient sse(client, "/events");
  13411. std::atomic<bool> error_called{false};
  13412. Error received_error = Error::Success;
  13413. sse.on_error([&](Error err) {
  13414. error_called.store(true);
  13415. received_error = err;
  13416. });
  13417. sse.set_reconnect_interval(50);
  13418. sse.set_max_reconnect_attempts(1);
  13419. sse.start_async();
  13420. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13421. sse.stop();
  13422. EXPECT_TRUE(error_called.load());
  13423. EXPECT_NE(received_error, Error::Success);
  13424. }
  13425. // Test: Last-Event-ID header sent on reconnect
  13426. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13427. // Endpoint that sends event with ID
  13428. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13429. res.set_chunked_content_provider(
  13430. "text/event-stream", [](size_t offset, DataSink &sink) {
  13431. if (offset == 0) {
  13432. std::string event = "id: evt-123\ndata: test\n\n";
  13433. sink.write(event.data(), event.size());
  13434. }
  13435. return false;
  13436. });
  13437. });
  13438. Client client("localhost", get_port());
  13439. sse::SSEClient sse(client, "/event-with-id");
  13440. std::atomic<bool> id_received{false};
  13441. sse.on_message([&](const sse::SSEMessage &msg) {
  13442. if (!msg.id.empty()) { id_received.store(true); }
  13443. });
  13444. sse.set_reconnect_interval(100);
  13445. sse.set_max_reconnect_attempts(1);
  13446. sse.start_async();
  13447. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13448. sse.stop();
  13449. EXPECT_TRUE(id_received.load());
  13450. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13451. }
  13452. // Test: Manual stop
  13453. TEST_F(SSEIntegrationTest, ManualStop) {
  13454. // Endpoint that sends one event and stays open briefly
  13455. std::atomic<bool> handler_running{true};
  13456. server_->Get("/stay-open", [&handler_running](const Request &,
  13457. Response &res) {
  13458. res.set_chunked_content_provider(
  13459. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13460. if (offset == 0) {
  13461. std::string event = "data: connected\n\n";
  13462. sink.write(event.data(), event.size());
  13463. }
  13464. // Keep connection open while handler_running is true
  13465. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13466. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13467. }
  13468. return false;
  13469. });
  13470. });
  13471. Client client("localhost", get_port());
  13472. sse::SSEClient sse(client, "/stay-open");
  13473. std::atomic<bool> connected{false};
  13474. sse.on_open([&connected]() { connected.store(true); });
  13475. sse.set_reconnect_interval(100);
  13476. sse.set_max_reconnect_attempts(1);
  13477. sse.start_async();
  13478. // Wait for connection to establish
  13479. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13480. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13481. }
  13482. EXPECT_TRUE(connected.load());
  13483. EXPECT_TRUE(sse.is_connected());
  13484. // Signal handler to stop
  13485. handler_running.store(false);
  13486. // Stop SSE client
  13487. sse.stop();
  13488. EXPECT_FALSE(sse.is_connected());
  13489. }
  13490. // Test: SSEClient with custom headers
  13491. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13492. // Setup a server endpoint that checks for custom header
  13493. std::atomic<bool> header_received{false};
  13494. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13495. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13496. header_received.store(true);
  13497. }
  13498. res.set_chunked_content_provider("text/event-stream",
  13499. [](size_t, DataSink &) { return false; });
  13500. });
  13501. Client client("localhost", get_port());
  13502. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13503. sse::SSEClient sse(client, "/header-check", headers);
  13504. sse.set_max_reconnect_attempts(1);
  13505. sse.start_async();
  13506. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13507. sse.stop();
  13508. EXPECT_TRUE(header_received.load());
  13509. }
  13510. // Test: Reconnect interval configuration
  13511. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13512. Client client("localhost", get_port());
  13513. sse::SSEClient sse(client, "/events");
  13514. auto &result = sse.set_reconnect_interval(500);
  13515. // Builder pattern should return reference to self
  13516. EXPECT_EQ(&result, &sse);
  13517. }
  13518. // Test: Max reconnect attempts
  13519. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13520. // Connect to non-existent port to force reconnects
  13521. Client client("localhost", 59998);
  13522. sse::SSEClient sse(client, "/events");
  13523. std::atomic<int> error_count{0};
  13524. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13525. sse.set_reconnect_interval(50);
  13526. sse.set_max_reconnect_attempts(2);
  13527. auto start = std::chrono::steady_clock::now();
  13528. sse.start(); // Blocking call
  13529. auto end = std::chrono::steady_clock::now();
  13530. // Should have stopped after 2 failed attempts
  13531. EXPECT_GE(error_count.load(), 2);
  13532. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13533. auto duration =
  13534. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13535. #ifdef _WIN32
  13536. // Windows is much slower for socket connection failures
  13537. EXPECT_LT(duration.count(), 7000);
  13538. #else
  13539. EXPECT_LT(duration.count(), 1000);
  13540. #endif
  13541. }
  13542. // Test: Multi-line data in integration
  13543. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13544. // Endpoint with multi-line data
  13545. server_->Get("/multiline-data", [](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 event = "data: line1\ndata: line2\ndata: line3\n\n";
  13550. sink.write(event.data(), event.size());
  13551. }
  13552. return false;
  13553. });
  13554. });
  13555. Client client("localhost", get_port());
  13556. sse::SSEClient sse(client, "/multiline-data");
  13557. std::string received_data;
  13558. std::mutex data_mutex;
  13559. sse.on_message([&](const sse::SSEMessage &msg) {
  13560. std::lock_guard<std::mutex> lock(data_mutex);
  13561. received_data = 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(data_mutex);
  13569. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13570. }
  13571. // Test: Auto-reconnect after server disconnection
  13572. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13573. std::atomic<int> connection_count{0};
  13574. std::atomic<int> message_count{0};
  13575. // Endpoint that sends one event and closes, forcing reconnect
  13576. server_->Get("/reconnect-test",
  13577. [&connection_count](const Request &, Response &res) {
  13578. connection_count.fetch_add(1);
  13579. res.set_chunked_content_provider(
  13580. "text/event-stream", [](size_t offset, DataSink &sink) {
  13581. if (offset == 0) {
  13582. std::string event = "data: hello\n\n";
  13583. sink.write(event.data(), event.size());
  13584. }
  13585. return false; // Close connection after sending
  13586. });
  13587. });
  13588. Client client("localhost", get_port());
  13589. sse::SSEClient sse(client, "/reconnect-test");
  13590. sse.on_message([&message_count](const sse::SSEMessage &) {
  13591. message_count.fetch_add(1);
  13592. });
  13593. sse.set_reconnect_interval(100);
  13594. sse.set_max_reconnect_attempts(3);
  13595. sse.start_async();
  13596. // Wait long enough for multiple reconnects
  13597. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13598. sse.stop();
  13599. // Should have connected multiple times (initial + reconnects)
  13600. EXPECT_GE(connection_count.load(), 2);
  13601. // Should have received messages from multiple connections
  13602. EXPECT_GE(message_count.load(), 2);
  13603. }
  13604. // Test: Last-Event-ID sent on reconnect
  13605. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13606. std::atomic<int> connection_count{0};
  13607. std::vector<std::string> received_last_event_ids;
  13608. std::mutex id_mutex;
  13609. // Endpoint that checks Last-Event-ID header and sends event with ID
  13610. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13611. int conn = connection_count.fetch_add(1);
  13612. // Capture the Last-Event-ID header from each connection
  13613. {
  13614. std::lock_guard<std::mutex> lock(id_mutex);
  13615. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13616. }
  13617. res.set_chunked_content_provider(
  13618. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13619. if (offset == 0) {
  13620. std::string event =
  13621. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13622. sink.write(event.data(), event.size());
  13623. }
  13624. return false;
  13625. });
  13626. });
  13627. Client client("localhost", get_port());
  13628. sse::SSEClient sse(client, "/reconnect-with-id");
  13629. sse.set_reconnect_interval(100);
  13630. sse.set_max_reconnect_attempts(3);
  13631. sse.start_async();
  13632. // Wait for at least 2 connections
  13633. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13634. sse.stop();
  13635. // Verify behavior
  13636. std::lock_guard<std::mutex> lock(id_mutex);
  13637. EXPECT_GE(received_last_event_ids.size(), 2u);
  13638. // First connection should have no Last-Event-ID
  13639. if (!received_last_event_ids.empty()) {
  13640. EXPECT_EQ(received_last_event_ids[0], "");
  13641. }
  13642. // Second connection should have Last-Event-ID from first connection
  13643. if (received_last_event_ids.size() >= 2) {
  13644. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13645. }
  13646. }
  13647. // Test: set_headers updates headers used on reconnect
  13648. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13649. std::vector<std::string> received_tokens;
  13650. std::mutex token_mutex;
  13651. // Endpoint that captures Authorization header
  13652. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13653. {
  13654. std::lock_guard<std::mutex> lock(token_mutex);
  13655. received_tokens.push_back(req.get_header_value("Authorization"));
  13656. }
  13657. res.set_chunked_content_provider(
  13658. "text/event-stream", [](size_t offset, DataSink &sink) {
  13659. if (offset == 0) {
  13660. std::string event = "data: hello\n\n";
  13661. sink.write(event.data(), event.size());
  13662. }
  13663. return false; // Close connection to trigger reconnect
  13664. });
  13665. });
  13666. Client client("localhost", get_port());
  13667. Headers headers = {{"Authorization", "Bearer old-token"}};
  13668. sse::SSEClient sse(client, "/auth-check", headers);
  13669. // Update headers on each successful connection
  13670. sse.on_open(
  13671. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13672. sse.set_reconnect_interval(100);
  13673. sse.set_max_reconnect_attempts(3);
  13674. sse.start_async();
  13675. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13676. sse.stop();
  13677. std::lock_guard<std::mutex> lock(token_mutex);
  13678. ASSERT_GE(received_tokens.size(), 2u);
  13679. // First connection uses original header
  13680. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13681. // Second connection uses updated header from set_headers
  13682. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13683. }
  13684. // Test: 401 allows reconnection (so on_error can refresh headers)
  13685. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13686. std::atomic<int> connection_count{0};
  13687. // Endpoint: returns 401 on first attempt, 200 on second
  13688. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13689. int conn = connection_count.fetch_add(1);
  13690. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13691. res.status = StatusCode::Unauthorized_401;
  13692. res.set_content("Unauthorized", "text/plain");
  13693. return;
  13694. }
  13695. res.set_chunked_content_provider(
  13696. "text/event-stream", [](size_t offset, DataSink &sink) {
  13697. if (offset == 0) {
  13698. std::string event = "data: authenticated\n\n";
  13699. sink.write(event.data(), event.size());
  13700. }
  13701. return false;
  13702. });
  13703. });
  13704. Client client("localhost", get_port());
  13705. Headers headers = {{"Authorization", "Bearer expired"}};
  13706. sse::SSEClient sse(client, "/auth-retry", headers);
  13707. std::atomic<bool> message_received{false};
  13708. // Refresh token on error
  13709. sse.on_error(
  13710. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13711. sse.on_message([&](const sse::SSEMessage &msg) {
  13712. if (msg.data == "authenticated") { message_received.store(true); }
  13713. });
  13714. sse.set_reconnect_interval(100);
  13715. sse.set_max_reconnect_attempts(3);
  13716. sse.start_async();
  13717. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13718. sse.stop();
  13719. // Should have reconnected after 401 and succeeded with new token
  13720. EXPECT_GE(connection_count.load(), 2);
  13721. EXPECT_TRUE(message_received.load());
  13722. }
  13723. TEST(Issue2318Test, EmptyHostString) {
  13724. {
  13725. httplib::Client cli_empty("", PORT);
  13726. auto res = cli_empty.Get("/");
  13727. ASSERT_FALSE(res);
  13728. EXPECT_EQ(httplib::Error::Connection, res.error());
  13729. }
  13730. {
  13731. httplib::Client cli(" ", PORT);
  13732. auto res = cli.Get("/");
  13733. ASSERT_FALSE(res);
  13734. EXPECT_EQ(httplib::Error::Connection, res.error());
  13735. }
  13736. }
  13737. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13738. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13739. Server svr;
  13740. // Set a small payload limit (1KB)
  13741. svr.set_payload_max_length(1024);
  13742. svr.Post("/test", [&](const Request &req, Response &res) {
  13743. res.set_content("Body size: " + std::to_string(req.body.size()),
  13744. "text/plain");
  13745. });
  13746. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13747. auto se = detail::scope_exit([&] {
  13748. svr.stop();
  13749. listen_thread.join();
  13750. });
  13751. svr.wait_until_ready();
  13752. // Create data that compresses well but exceeds limit when decompressed
  13753. // 8KB of repeated null bytes compresses to a very small size
  13754. std::string original_data(8 * 1024, '\0');
  13755. // Compress the data using gzip
  13756. std::string compressed_data;
  13757. detail::gzip_compressor compressor;
  13758. compressor.compress(original_data.data(), original_data.size(), true,
  13759. [&](const char *data, size_t size) {
  13760. compressed_data.append(data, size);
  13761. return true;
  13762. });
  13763. // Verify compression worked (compressed should be much smaller)
  13764. ASSERT_LT(compressed_data.size(), original_data.size());
  13765. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13766. // Send compressed data with Content-Encoding: gzip
  13767. Client cli(HOST, PORT);
  13768. Headers headers = {{"Content-Encoding", "gzip"}};
  13769. auto res =
  13770. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13771. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13772. ASSERT_TRUE(res);
  13773. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13774. }
  13775. #endif
  13776. // ============================================================================
  13777. // OpenSSL-Specific Tests
  13778. // ============================================================================
  13779. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13780. X509 *readCertificate(const std::string &strFileName) {
  13781. std::ifstream inStream(strFileName);
  13782. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13783. std::istreambuf_iterator<char>());
  13784. if (strCertPEM.empty()) return (nullptr);
  13785. BIO *pbCert = BIO_new(BIO_s_mem());
  13786. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13787. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13788. BIO_free(pbCert);
  13789. return (pCert);
  13790. }
  13791. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13792. std::ifstream inStream(strFileName);
  13793. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13794. std::istreambuf_iterator<char>());
  13795. if (strPrivateKeyPEM.empty()) return (nullptr);
  13796. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13797. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13798. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13799. BIO_free(pbPrivKey);
  13800. return (pPrivateKey);
  13801. }
  13802. TEST(BindServerTest, UpdateCerts) {
  13803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13804. int port = svr.bind_to_any_port("0.0.0.0");
  13805. ASSERT_TRUE(svr.is_valid());
  13806. ASSERT_TRUE(port > 0);
  13807. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13808. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13809. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13810. ASSERT_TRUE(cert != nullptr);
  13811. ASSERT_TRUE(ca_cert != nullptr);
  13812. ASSERT_TRUE(key != nullptr);
  13813. X509_STORE *cert_store = X509_STORE_new();
  13814. X509_STORE_add_cert(cert_store, ca_cert);
  13815. // svr.update_certs(cert, key, cert_store); // deprecated
  13816. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13817. CLIENT_CA_CERT_FILE);
  13818. ASSERT_TRUE(svr.is_valid());
  13819. svr.stop();
  13820. X509_STORE_free(cert_store);
  13821. X509_free(cert);
  13822. X509_free(ca_cert);
  13823. EVP_PKEY_free(key);
  13824. }
  13825. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13826. // client CA list correctly for TLS handshake
  13827. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13828. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13829. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13830. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13831. ASSERT_TRUE(cert != nullptr);
  13832. ASSERT_TRUE(ca_cert != nullptr);
  13833. ASSERT_TRUE(key != nullptr);
  13834. X509_STORE *cert_store = X509_STORE_new();
  13835. X509_STORE_add_cert(cert_store, ca_cert);
  13836. // Use X509-based constructor (deprecated but should still work correctly)
  13837. #pragma GCC diagnostic push
  13838. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13839. SSLServer svr(cert, key, cert_store);
  13840. #pragma GCC diagnostic pop
  13841. ASSERT_TRUE(svr.is_valid());
  13842. // Verify that client CA list is set in SSL_CTX
  13843. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13844. ASSERT_TRUE(ssl_ctx != nullptr);
  13845. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13846. ASSERT_TRUE(ca_list != nullptr);
  13847. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13848. X509_free(cert);
  13849. X509_free(ca_cert);
  13850. EVP_PKEY_free(key);
  13851. }
  13852. // Test that update_certs() updates client CA list correctly
  13853. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13854. // Start with file-based constructor
  13855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13856. ASSERT_TRUE(svr.is_valid());
  13857. // Initially no client CA list should be set
  13858. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13859. ASSERT_TRUE(ssl_ctx != nullptr);
  13860. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13861. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13862. EXPECT_EQ(0, count_before);
  13863. // Now update with client CA (PEM string)
  13864. std::string cert_pem, key_pem, ca_pem;
  13865. read_file(SERVER_CERT_FILE, cert_pem);
  13866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13867. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13868. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13869. ASSERT_TRUE(svr.is_valid());
  13870. // Now client CA list should be set
  13871. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13872. ASSERT_TRUE(ca_list_after != nullptr);
  13873. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13874. }
  13875. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13876. // Test that the file-path SSLServer constructor properly sets the client CA
  13877. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13878. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13879. ASSERT_TRUE(svr.is_valid());
  13880. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13881. ASSERT_TRUE(ssl_ctx != nullptr);
  13882. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13883. ASSERT_TRUE(ca_list != nullptr);
  13884. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13885. }
  13886. #endif
  13887. // ============================================================================
  13888. // MbedTLS-Specific Tests
  13889. // ============================================================================
  13890. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13891. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13892. using namespace httplib::tls;
  13893. // Track if callback was invoked
  13894. bool callback_invoked = false;
  13895. // The callback receives void* ctx which is actually MbedTlsContext*
  13896. // We can access the mbedtls_ssl_config via the context
  13897. auto setup_callback = [&callback_invoked](void *ctx) {
  13898. callback_invoked = true;
  13899. // Cast to MbedTlsContext* to access the ssl config
  13900. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13901. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13902. // Use static variables to hold certificate data (simplified for test)
  13903. static mbedtls_x509_crt own_cert;
  13904. static mbedtls_pk_context own_key;
  13905. static mbedtls_x509_crt ca_chain;
  13906. static bool initialized = false;
  13907. if (!initialized) {
  13908. mbedtls_x509_crt_init(&own_cert);
  13909. mbedtls_pk_init(&own_key);
  13910. mbedtls_x509_crt_init(&ca_chain);
  13911. // Load server certificate
  13912. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13913. return false;
  13914. }
  13915. // Load server private key
  13916. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13917. #if MBEDTLS_VERSION_MAJOR >= 3
  13918. ,
  13919. mbedtls_ctr_drbg_random, nullptr
  13920. #endif
  13921. ) != 0) {
  13922. return false;
  13923. }
  13924. // Load CA chain for client verification
  13925. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13926. return false;
  13927. }
  13928. initialized = true;
  13929. }
  13930. // Configure the SSL config
  13931. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13932. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13933. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13934. // Set minimum TLS version using mbedTLS native API
  13935. #if MBEDTLS_VERSION_MAJOR >= 3
  13936. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13937. #else
  13938. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13939. MBEDTLS_SSL_MINOR_VERSION_3);
  13940. #endif
  13941. return true;
  13942. };
  13943. SSLServer svr(setup_callback);
  13944. ASSERT_TRUE(svr.is_valid());
  13945. ASSERT_TRUE(callback_invoked);
  13946. svr.Get("/test", [&](const Request &req, Response &res) {
  13947. res.set_content("test", "text/plain");
  13948. auto cert = req.peer_cert();
  13949. ASSERT_TRUE(static_cast<bool>(cert));
  13950. auto common_name = cert.subject_cn();
  13951. EXPECT_EQ("Common Name", common_name);
  13952. });
  13953. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13954. auto se = detail::scope_exit([&] {
  13955. svr.stop();
  13956. t.join();
  13957. ASSERT_FALSE(svr.is_running());
  13958. });
  13959. svr.wait_until_ready();
  13960. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13961. cli.enable_server_certificate_verification(false);
  13962. cli.set_connection_timeout(30);
  13963. auto res = cli.Get("/test");
  13964. ASSERT_TRUE(res);
  13965. ASSERT_EQ(StatusCode::OK_200, res->status);
  13966. }
  13967. #endif
  13968. // WebSocket Tests
  13969. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13970. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13971. // defining the meaning of these bits has been negotiated.
  13972. auto make_frame = [](uint8_t first_byte) {
  13973. std::string frame;
  13974. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13975. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13976. frame += "Hello";
  13977. return frame;
  13978. };
  13979. // RSV1 set (0x40)
  13980. {
  13981. detail::BufferStream strm;
  13982. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13983. ws::Opcode opcode;
  13984. std::string payload;
  13985. bool fin;
  13986. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13987. false, 1024));
  13988. }
  13989. // RSV2 set (0x20)
  13990. {
  13991. detail::BufferStream strm;
  13992. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13993. ws::Opcode opcode;
  13994. std::string payload;
  13995. bool fin;
  13996. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13997. false, 1024));
  13998. }
  13999. // RSV3 set (0x10)
  14000. {
  14001. detail::BufferStream strm;
  14002. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14003. ws::Opcode opcode;
  14004. std::string payload;
  14005. bool fin;
  14006. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14007. false, 1024));
  14008. }
  14009. // No RSV bits set - should succeed
  14010. {
  14011. detail::BufferStream strm;
  14012. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14013. ws::Opcode opcode;
  14014. std::string payload;
  14015. bool fin;
  14016. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14017. false, 1024));
  14018. EXPECT_EQ(ws::Opcode::Text, opcode);
  14019. EXPECT_EQ("Hello", payload);
  14020. EXPECT_TRUE(fin);
  14021. }
  14022. }
  14023. TEST(WebSocketTest, ControlFrameValidation) {
  14024. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14025. // payload length <= 125.
  14026. // Ping with FIN=0 - must be rejected
  14027. {
  14028. detail::BufferStream strm;
  14029. std::string frame;
  14030. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14031. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14032. strm.write(frame.data(), frame.size());
  14033. ws::Opcode opcode;
  14034. std::string payload;
  14035. bool fin;
  14036. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14037. false, 1024));
  14038. }
  14039. // Close with FIN=0 - must be rejected
  14040. {
  14041. detail::BufferStream strm;
  14042. std::string frame;
  14043. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14044. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14045. strm.write(frame.data(), frame.size());
  14046. ws::Opcode opcode;
  14047. std::string payload;
  14048. bool fin;
  14049. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14050. false, 1024));
  14051. }
  14052. // Ping with payload_len=126 (extended length) - must be rejected
  14053. {
  14054. detail::BufferStream strm;
  14055. std::string frame;
  14056. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14057. frame += static_cast<char>(126); // payload_len=126 (>125)
  14058. frame += static_cast<char>(0x00); // extended length high byte
  14059. frame += static_cast<char>(126); // extended length low byte
  14060. frame += std::string(126, 'x');
  14061. strm.write(frame.data(), frame.size());
  14062. ws::Opcode opcode;
  14063. std::string payload;
  14064. bool fin;
  14065. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14066. false, 1024));
  14067. }
  14068. // Ping with FIN=1 and payload_len=125 - should succeed
  14069. {
  14070. detail::BufferStream strm;
  14071. std::string frame;
  14072. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14073. frame += static_cast<char>(125); // payload_len=125
  14074. frame += std::string(125, 'x');
  14075. strm.write(frame.data(), frame.size());
  14076. ws::Opcode opcode;
  14077. std::string payload;
  14078. bool fin;
  14079. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14080. false, 1024));
  14081. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14082. EXPECT_EQ(125u, payload.size());
  14083. EXPECT_TRUE(fin);
  14084. }
  14085. }
  14086. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14087. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14088. // length MUST be 0.
  14089. // MSB set - must be rejected
  14090. {
  14091. detail::BufferStream strm;
  14092. std::string frame;
  14093. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14094. frame += static_cast<char>(127); // 64-bit extended length
  14095. frame += static_cast<char>(0x80); // MSB set (invalid)
  14096. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14097. strm.write(frame.data(), frame.size());
  14098. ws::Opcode opcode;
  14099. std::string payload;
  14100. bool fin;
  14101. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14102. false, 1024));
  14103. }
  14104. // MSB clear - should pass length parsing (will be rejected by max_len,
  14105. // but that's a different check; use a small length to verify)
  14106. {
  14107. detail::BufferStream strm;
  14108. std::string frame;
  14109. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14110. frame += static_cast<char>(127); // 64-bit extended length
  14111. frame += std::string(7, '\0'); // high bytes = 0
  14112. frame += static_cast<char>(0x03); // length = 3
  14113. frame += "abc";
  14114. strm.write(frame.data(), frame.size());
  14115. ws::Opcode opcode;
  14116. std::string payload;
  14117. bool fin;
  14118. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14119. false, 1024));
  14120. EXPECT_EQ(ws::Opcode::Text, opcode);
  14121. EXPECT_EQ("abc", payload);
  14122. }
  14123. }
  14124. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14125. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14126. // Valid UTF-8
  14127. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14128. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14129. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14130. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14131. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14132. // Invalid UTF-8
  14133. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14134. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14135. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14136. EXPECT_FALSE(
  14137. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14138. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14139. }
  14140. TEST(WebSocketTest, ConnectAndDisconnect) {
  14141. Server svr;
  14142. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14143. std::string msg;
  14144. while (ws.read(msg)) {}
  14145. });
  14146. auto port = svr.bind_to_any_port(HOST);
  14147. std::thread t([&]() { svr.listen_after_bind(); });
  14148. svr.wait_until_ready();
  14149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14150. ASSERT_TRUE(client.connect());
  14151. EXPECT_TRUE(client.is_open());
  14152. client.close();
  14153. EXPECT_FALSE(client.is_open());
  14154. svr.stop();
  14155. t.join();
  14156. }
  14157. TEST(WebSocketTest, ValidURL) {
  14158. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14159. EXPECT_TRUE(ws1.is_valid());
  14160. ws::WebSocketClient ws2("ws://example.com/path");
  14161. EXPECT_TRUE(ws2.is_valid());
  14162. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14163. EXPECT_TRUE(ws3.is_valid());
  14164. #ifdef CPPHTTPLIB_SSL_ENABLED
  14165. ws::WebSocketClient wss1("wss://example.com/path");
  14166. EXPECT_TRUE(wss1.is_valid());
  14167. ws::WebSocketClient wss2("wss://example.com:443/path");
  14168. EXPECT_TRUE(wss2.is_valid());
  14169. #endif
  14170. }
  14171. TEST(WebSocketTest, InvalidURL) {
  14172. // No scheme
  14173. ws::WebSocketClient ws1("localhost:8080/path");
  14174. EXPECT_FALSE(ws1.is_valid());
  14175. // No path
  14176. ws::WebSocketClient ws2("ws://localhost:8080");
  14177. EXPECT_FALSE(ws2.is_valid());
  14178. // Empty string
  14179. ws::WebSocketClient ws3("");
  14180. EXPECT_FALSE(ws3.is_valid());
  14181. // Missing host
  14182. ws::WebSocketClient ws4("ws://:8080/path");
  14183. EXPECT_FALSE(ws4.is_valid());
  14184. // Port number overflow — should not crash
  14185. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14186. EXPECT_FALSE(ws5.is_valid());
  14187. // Port out of range
  14188. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14189. EXPECT_FALSE(ws6.is_valid());
  14190. }
  14191. TEST(WebSocketTest, UnsupportedScheme) {
  14192. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14193. ws::WebSocketClient ws1("http://localhost:8080/path");
  14194. EXPECT_FALSE(ws1.is_valid());
  14195. ws::WebSocketClient ws2("https://localhost:8080/path");
  14196. EXPECT_FALSE(ws2.is_valid());
  14197. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14198. EXPECT_FALSE(ws3.is_valid());
  14199. #else
  14200. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14201. std::invalid_argument);
  14202. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14203. std::invalid_argument);
  14204. #endif
  14205. }
  14206. TEST(WebSocketTest, ConnectWhenInvalid) {
  14207. ws::WebSocketClient ws("not a valid url");
  14208. EXPECT_FALSE(ws.is_valid());
  14209. EXPECT_FALSE(ws.connect());
  14210. }
  14211. TEST(WebSocketTest, DefaultPort) {
  14212. ws::WebSocketClient ws1("ws://example.com/path");
  14213. EXPECT_TRUE(ws1.is_valid());
  14214. // ws:// defaults to port 80 (verified by successful parse)
  14215. #ifdef CPPHTTPLIB_SSL_ENABLED
  14216. ws::WebSocketClient ws2("wss://example.com/path");
  14217. EXPECT_TRUE(ws2.is_valid());
  14218. // wss:// defaults to port 443 (verified by successful parse)
  14219. #endif
  14220. }
  14221. TEST(WebSocketTest, IPv6LiteralAddress) {
  14222. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14223. EXPECT_TRUE(ws1.is_valid());
  14224. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14225. EXPECT_TRUE(ws2.is_valid());
  14226. }
  14227. TEST(WebSocketTest, ComplexPath) {
  14228. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14229. EXPECT_TRUE(ws1.is_valid());
  14230. ws::WebSocketClient ws2("ws://localhost:8080/");
  14231. EXPECT_TRUE(ws2.is_valid());
  14232. }
  14233. class WebSocketIntegrationTest : public ::testing::Test {
  14234. protected:
  14235. void SetUp() override {
  14236. server_ = httplib::detail::make_unique<Server>();
  14237. setup_server();
  14238. start_server();
  14239. }
  14240. void TearDown() override {
  14241. server_->stop();
  14242. if (server_thread_.joinable()) { server_thread_.join(); }
  14243. }
  14244. void setup_server() {
  14245. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14246. std::string msg;
  14247. ws::ReadResult ret;
  14248. while ((ret = ws.read(msg))) {
  14249. if (ret == ws::Binary) {
  14250. ws.send(msg.data(), msg.size());
  14251. } else {
  14252. ws.send(msg);
  14253. }
  14254. }
  14255. });
  14256. server_->WebSocket("/ws-echo-string",
  14257. [](const Request &, ws::WebSocket &ws) {
  14258. std::string msg;
  14259. while (ws.read(msg)) {
  14260. ws.send("echo: " + msg);
  14261. }
  14262. });
  14263. server_->WebSocket(
  14264. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14265. // Echo back request metadata
  14266. ws.send("path:" + req.path);
  14267. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14268. std::string msg;
  14269. while (ws.read(msg)) {}
  14270. });
  14271. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14272. std::string msg;
  14273. ws.read(msg); // wait for a message
  14274. ws.close();
  14275. });
  14276. server_->WebSocket("/ws-close-status",
  14277. [](const Request &, ws::WebSocket &ws) {
  14278. std::string msg;
  14279. ws.read(msg); // wait for a message
  14280. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14281. });
  14282. server_->WebSocket(
  14283. "/ws-subprotocol",
  14284. [](const Request &, ws::WebSocket &ws) {
  14285. std::string msg;
  14286. while (ws.read(msg)) {
  14287. ws.send(msg);
  14288. }
  14289. },
  14290. [](const std::vector<std::string> &protocols) -> std::string {
  14291. for (const auto &p : protocols) {
  14292. if (p == "graphql-ws") { return p; }
  14293. }
  14294. return "";
  14295. });
  14296. }
  14297. void start_server() {
  14298. port_ = server_->bind_to_any_port(HOST);
  14299. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14300. server_->wait_until_ready();
  14301. }
  14302. std::unique_ptr<Server> server_;
  14303. std::thread server_thread_;
  14304. int port_ = 0;
  14305. };
  14306. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14307. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14308. "/ws-echo");
  14309. ASSERT_TRUE(client.connect());
  14310. ASSERT_TRUE(client.is_open());
  14311. ASSERT_TRUE(client.send("Hello WebSocket"));
  14312. std::string msg;
  14313. EXPECT_EQ(ws::Text, client.read(msg));
  14314. EXPECT_EQ("Hello WebSocket", msg);
  14315. client.close();
  14316. }
  14317. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14318. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14319. "/ws-echo");
  14320. ASSERT_TRUE(client.connect());
  14321. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14322. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14323. std::string msg;
  14324. EXPECT_EQ(ws::Binary, client.read(msg));
  14325. EXPECT_EQ(binary_data, msg);
  14326. client.close();
  14327. }
  14328. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14329. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14330. "/ws-echo");
  14331. ASSERT_TRUE(client.connect());
  14332. for (int i = 0; i < 10; i++) {
  14333. auto text = "message " + std::to_string(i);
  14334. ASSERT_TRUE(client.send(text));
  14335. std::string msg;
  14336. ASSERT_TRUE(client.read(msg));
  14337. EXPECT_EQ(text, msg);
  14338. }
  14339. client.close();
  14340. }
  14341. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14342. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14343. "/ws-close");
  14344. ASSERT_TRUE(client.connect());
  14345. // Send a message to trigger the server to close
  14346. ASSERT_TRUE(client.send("trigger close"));
  14347. // The server will close, so read should return false
  14348. std::string msg;
  14349. EXPECT_FALSE(client.read(msg));
  14350. EXPECT_FALSE(client.is_open());
  14351. }
  14352. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14353. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14354. "/ws-echo");
  14355. ASSERT_TRUE(client.connect());
  14356. // 128KB message
  14357. std::string large_data(128 * 1024, 'X');
  14358. ASSERT_TRUE(client.send(large_data));
  14359. std::string msg;
  14360. ASSERT_TRUE(client.read(msg));
  14361. EXPECT_EQ(large_data, msg);
  14362. client.close();
  14363. }
  14364. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14365. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14366. "/ws-echo");
  14367. ASSERT_TRUE(client.connect());
  14368. const int num_threads = 4;
  14369. std::vector<std::thread> threads;
  14370. std::atomic<int> send_count{0};
  14371. for (int t = 0; t < num_threads; t++) {
  14372. threads.emplace_back([&client, &send_count, t]() {
  14373. for (int i = 0; i < 5; i++) {
  14374. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14375. if (client.send(text)) { send_count++; }
  14376. }
  14377. });
  14378. }
  14379. for (auto &th : threads) {
  14380. th.join();
  14381. }
  14382. int received = 0;
  14383. std::string msg;
  14384. while (received < send_count.load()) {
  14385. if (!client.read(msg)) { break; }
  14386. received++;
  14387. }
  14388. EXPECT_EQ(send_count.load(), received);
  14389. client.close();
  14390. }
  14391. TEST_F(WebSocketIntegrationTest, ReadString) {
  14392. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14393. "/ws-echo-string");
  14394. ASSERT_TRUE(client.connect());
  14395. ASSERT_TRUE(client.send("hello"));
  14396. std::string msg;
  14397. ASSERT_TRUE(client.read(msg));
  14398. EXPECT_EQ("echo: hello", msg);
  14399. ASSERT_TRUE(client.send("world"));
  14400. ASSERT_TRUE(client.read(msg));
  14401. EXPECT_EQ("echo: world", msg);
  14402. client.close();
  14403. }
  14404. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14405. Headers headers = {{"X-Test-Header", "test-value"}};
  14406. ws::WebSocketClient client(
  14407. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14408. ASSERT_TRUE(client.connect());
  14409. std::string msg;
  14410. ASSERT_TRUE(client.read(msg));
  14411. EXPECT_EQ("path:/ws-request-info", msg);
  14412. ASSERT_TRUE(client.read(msg));
  14413. EXPECT_EQ("header:test-value", msg);
  14414. client.close();
  14415. }
  14416. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14417. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14418. "/ws-echo");
  14419. client.set_read_timeout(1, 0); // 1 second
  14420. ASSERT_TRUE(client.connect());
  14421. // Don't send anything — server echo handler waits for a message,
  14422. // so read() should time out and return false.
  14423. std::string msg;
  14424. EXPECT_FALSE(client.read(msg));
  14425. }
  14426. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14428. "/ws-echo");
  14429. client.set_read_timeout(5, 0);
  14430. ASSERT_TRUE(client.connect());
  14431. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14432. // The server should reject it and close the connection.
  14433. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14434. client.send(oversized);
  14435. // The server's read() should have failed due to payload limit,
  14436. // so our read() should return false (connection closed).
  14437. std::string msg;
  14438. EXPECT_FALSE(client.read(msg));
  14439. }
  14440. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14441. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14442. "/ws-echo");
  14443. client.set_read_timeout(10, 0);
  14444. ASSERT_TRUE(client.connect());
  14445. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14446. // This should succeed.
  14447. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14448. ASSERT_TRUE(client.send(at_limit));
  14449. std::string msg;
  14450. ASSERT_TRUE(client.read(msg));
  14451. EXPECT_EQ(at_limit.size(), msg.size());
  14452. client.close();
  14453. }
  14454. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14455. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14456. "/nonexistent");
  14457. EXPECT_FALSE(client.connect());
  14458. EXPECT_FALSE(client.is_open());
  14459. }
  14460. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14461. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14462. "/ws-echo");
  14463. ASSERT_TRUE(client.connect());
  14464. ASSERT_TRUE(client.send(""));
  14465. std::string msg;
  14466. EXPECT_EQ(ws::Text, client.read(msg));
  14467. EXPECT_EQ("", msg);
  14468. client.close();
  14469. }
  14470. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14471. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14472. "/ws-echo");
  14473. // First connection
  14474. ASSERT_TRUE(client.connect());
  14475. ASSERT_TRUE(client.send("first"));
  14476. std::string msg;
  14477. ASSERT_TRUE(client.read(msg));
  14478. EXPECT_EQ("first", msg);
  14479. client.close();
  14480. EXPECT_FALSE(client.is_open());
  14481. // Reconnect using the same client object
  14482. ASSERT_TRUE(client.connect());
  14483. ASSERT_TRUE(client.is_open());
  14484. ASSERT_TRUE(client.send("second"));
  14485. ASSERT_TRUE(client.read(msg));
  14486. EXPECT_EQ("second", msg);
  14487. client.close();
  14488. }
  14489. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14491. "/ws-close-status");
  14492. ASSERT_TRUE(client.connect());
  14493. // Trigger the server to close with GoingAway status
  14494. ASSERT_TRUE(client.send("trigger"));
  14495. // read() should return false after receiving the close frame
  14496. std::string msg;
  14497. EXPECT_FALSE(client.read(msg));
  14498. EXPECT_FALSE(client.is_open());
  14499. }
  14500. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14501. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14502. "/ws-echo");
  14503. ASSERT_TRUE(client.connect());
  14504. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14505. EXPECT_FALSE(client.is_open());
  14506. }
  14507. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14508. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14509. ws::WebSocketClient client(
  14510. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14511. ASSERT_TRUE(client.connect());
  14512. // Server should have selected graphql-ws
  14513. EXPECT_EQ("graphql-ws", client.subprotocol());
  14514. client.close();
  14515. }
  14516. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14517. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14518. ws::WebSocketClient client(
  14519. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14520. ASSERT_TRUE(client.connect());
  14521. // Server should not have selected any subprotocol
  14522. EXPECT_TRUE(client.subprotocol().empty());
  14523. client.close();
  14524. }
  14525. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14526. // Connect without requesting any subprotocol
  14527. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14528. "/ws-subprotocol");
  14529. ASSERT_TRUE(client.connect());
  14530. EXPECT_TRUE(client.subprotocol().empty());
  14531. client.close();
  14532. }
  14533. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14534. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14535. "/ws-echo");
  14536. client.set_tcp_nodelay(true);
  14537. client.set_connection_timeout(3, 0);
  14538. bool socket_options_called = false;
  14539. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14540. ASSERT_TRUE(client.connect());
  14541. ASSERT_TRUE(client.is_open());
  14542. EXPECT_TRUE(socket_options_called);
  14543. ASSERT_TRUE(client.send("hello"));
  14544. std::string msg;
  14545. auto result = client.read(msg);
  14546. EXPECT_EQ(result, ws::ReadResult::Text);
  14547. EXPECT_EQ(msg, "hello");
  14548. client.close();
  14549. }
  14550. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14551. Server svr;
  14552. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14553. if (!req.has_header("Authorization")) {
  14554. res.status = StatusCode::Unauthorized_401;
  14555. res.set_content("Unauthorized", "text/plain");
  14556. return Server::HandlerResponse::Handled;
  14557. }
  14558. return Server::HandlerResponse::Unhandled;
  14559. });
  14560. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14561. std::string msg;
  14562. while (ws.read(msg)) {
  14563. ws.send(msg);
  14564. }
  14565. });
  14566. auto port = svr.bind_to_any_port("localhost");
  14567. std::thread t([&]() { svr.listen_after_bind(); });
  14568. svr.wait_until_ready();
  14569. // Without Authorization header - should be rejected before upgrade
  14570. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14571. EXPECT_FALSE(client1.connect());
  14572. // With Authorization header - should succeed
  14573. Headers headers = {{"Authorization", "Bearer token123"}};
  14574. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14575. headers);
  14576. ASSERT_TRUE(client2.connect());
  14577. ASSERT_TRUE(client2.send("hello"));
  14578. std::string msg;
  14579. ASSERT_TRUE(client2.read(msg));
  14580. EXPECT_EQ("hello", msg);
  14581. client2.close();
  14582. svr.stop();
  14583. t.join();
  14584. }
  14585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14586. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14587. protected:
  14588. void SetUp() override {
  14589. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14590. SERVER_PRIVATE_KEY_FILE);
  14591. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14592. std::string msg;
  14593. ws::ReadResult ret;
  14594. while ((ret = ws.read(msg))) {
  14595. if (ret == ws::Binary) {
  14596. ws.send(msg.data(), msg.size());
  14597. } else {
  14598. ws.send(msg);
  14599. }
  14600. }
  14601. });
  14602. port_ = server_->bind_to_any_port(HOST);
  14603. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14604. server_->wait_until_ready();
  14605. }
  14606. void TearDown() override {
  14607. server_->stop();
  14608. if (server_thread_.joinable()) { server_thread_.join(); }
  14609. }
  14610. std::unique_ptr<SSLServer> server_;
  14611. std::thread server_thread_;
  14612. int port_ = 0;
  14613. };
  14614. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14615. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14616. "/ws-echo");
  14617. client.enable_server_certificate_verification(false);
  14618. ASSERT_TRUE(client.connect());
  14619. ASSERT_TRUE(client.is_open());
  14620. ASSERT_TRUE(client.send("Hello WSS"));
  14621. std::string msg;
  14622. EXPECT_EQ(ws::Text, client.read(msg));
  14623. EXPECT_EQ("Hello WSS", msg);
  14624. client.close();
  14625. }
  14626. #endif
  14627. #if !defined(_WIN32)
  14628. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14629. auto secret_dir = std::string("./symlink_test_secret");
  14630. auto served_dir = std::string("./symlink_test_served");
  14631. auto secret_file = secret_dir + "/secret.txt";
  14632. auto symlink_path = served_dir + "/escape";
  14633. // Setup: create directories and files
  14634. mkdir(secret_dir.c_str(), 0755);
  14635. mkdir(served_dir.c_str(), 0755);
  14636. {
  14637. std::ofstream ofs(secret_file);
  14638. ofs << "SECRET_DATA";
  14639. }
  14640. // Create symlink using absolute path so it resolves correctly
  14641. char abs_secret[PATH_MAX];
  14642. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14643. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14644. auto se = detail::scope_exit([&] {
  14645. unlink(symlink_path.c_str());
  14646. unlink(secret_file.c_str());
  14647. rmdir(served_dir.c_str());
  14648. rmdir(secret_dir.c_str());
  14649. });
  14650. Server svr;
  14651. svr.set_mount_point("/", served_dir);
  14652. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14653. auto se2 = detail::scope_exit([&] {
  14654. svr.stop();
  14655. listen_thread.join();
  14656. });
  14657. svr.wait_until_ready();
  14658. Client cli("localhost", PORT);
  14659. // Symlink pointing outside base dir should be blocked
  14660. auto res = cli.Get("/escape/secret.txt");
  14661. ASSERT_TRUE(res);
  14662. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14663. }
  14664. #endif
  14665. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14666. // A GET request with Content-Length to a static file handler must have its
  14667. // body drained before the keep-alive connection is reused. Otherwise the
  14668. // unread body bytes are interpreted as the next HTTP request.
  14669. //
  14670. // The body is sent AFTER receiving the first response (as in the original
  14671. // PoC) so that the stream_line_reader cannot buffer it together with the
  14672. // headers of the first request.
  14673. Server svr;
  14674. svr.set_mount_point("/", "./www");
  14675. std::atomic<int> smuggled_count(0);
  14676. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14677. smuggled_count++;
  14678. res.set_content("oops", "text/plain");
  14679. });
  14680. auto port = svr.bind_to_any_port("localhost");
  14681. thread t = thread([&] { svr.listen_after_bind(); });
  14682. auto se = detail::scope_exit([&] {
  14683. svr.stop();
  14684. t.join();
  14685. });
  14686. svr.wait_until_ready();
  14687. auto error = Error::Success;
  14688. auto sock = detail::create_client_socket(
  14689. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14690. /*connection_timeout_sec=*/2, 0,
  14691. /*read_timeout_sec=*/2, 0,
  14692. /*write_timeout_sec=*/2, 0, std::string(), error);
  14693. ASSERT_NE(INVALID_SOCKET, sock);
  14694. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14695. // The "smuggled" request will be sent as the body of the outer GET
  14696. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14697. "Host: localhost\r\n"
  14698. "Connection: close\r\n"
  14699. "\r\n";
  14700. // Step 1: Send only the outer request headers (no body yet)
  14701. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14702. "Host: localhost\r\n"
  14703. "Content-Length: " +
  14704. std::to_string(smuggled.size()) +
  14705. "\r\n"
  14706. "\r\n";
  14707. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  14708. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14709. // Step 2: Read the first response (server serves file without reading body)
  14710. std::string first_response;
  14711. char buf[4096];
  14712. for (;;) {
  14713. auto n = recv(sock, buf, sizeof(buf), 0);
  14714. if (n <= 0) break;
  14715. first_response.append(buf, static_cast<size_t>(n));
  14716. // Stop once we have a complete response (headers + body)
  14717. auto hdr_end = first_response.find("\r\n\r\n");
  14718. if (hdr_end != std::string::npos) {
  14719. // Check for Content-Length to know when the body is complete
  14720. auto cl_pos = first_response.find("Content-Length:");
  14721. if (cl_pos != std::string::npos) {
  14722. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14723. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14724. auto cl = std::stoul(
  14725. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14726. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14727. } else {
  14728. break; // No Content-Length, assume headers-only response
  14729. }
  14730. }
  14731. }
  14732. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14733. // Step 3: Now send the body, which looks like a new HTTP request.
  14734. // On a vulnerable server the keep-alive loop reads this as a second request.
  14735. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  14736. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14737. // Step 4: Try to read a second response (should NOT exist after fix)
  14738. std::string second_response;
  14739. for (;;) {
  14740. auto n = recv(sock, buf, sizeof(buf), 0);
  14741. if (n <= 0) break;
  14742. second_response.append(buf, static_cast<size_t>(n));
  14743. }
  14744. // The smuggled request must NOT have been processed
  14745. EXPECT_EQ(0, smuggled_count.load());
  14746. }
  14747. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14748. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14749. // must be rejected with 400 Bad Request.
  14750. Server svr;
  14751. svr.Post("/test", [&](const Request &, Response &res) {
  14752. res.set_content("ok", "text/plain");
  14753. });
  14754. thread t = thread([&] { svr.listen(HOST, PORT); });
  14755. auto se = detail::scope_exit([&] {
  14756. svr.stop();
  14757. t.join();
  14758. ASSERT_FALSE(svr.is_running());
  14759. });
  14760. svr.wait_until_ready();
  14761. // Exact "chunked"
  14762. {
  14763. auto req = "POST /test HTTP/1.1\r\n"
  14764. "Host: localhost\r\n"
  14765. "Content-Length: 5\r\n"
  14766. "Transfer-Encoding: chunked\r\n"
  14767. "Connection: close\r\n"
  14768. "\r\n"
  14769. "hello";
  14770. std::string response;
  14771. ASSERT_TRUE(send_request(1, req, &response));
  14772. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14773. response.substr(0, response.find("\r\n")));
  14774. }
  14775. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  14776. {
  14777. auto req = "POST /test HTTP/1.1\r\n"
  14778. "Host: localhost\r\n"
  14779. "Content-Length: 5\r\n"
  14780. "Transfer-Encoding: gzip, chunked\r\n"
  14781. "Connection: close\r\n"
  14782. "\r\n"
  14783. "hello";
  14784. std::string response;
  14785. ASSERT_TRUE(send_request(1, req, &response));
  14786. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14787. response.substr(0, response.find("\r\n")));
  14788. }
  14789. }