test.cc 543 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731
  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. .Post("/validate-no-multiple-headers",
  3218. [&](const Request &req, Response & /*res*/) {
  3219. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3220. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3221. })
  3222. .Post("/content_receiver",
  3223. [&](const Request &req, Response &res,
  3224. const ContentReader &content_reader) {
  3225. if (req.is_multipart_form_data()) {
  3226. std::vector<FormData> items;
  3227. content_reader(
  3228. [&](const FormData &file) {
  3229. items.push_back(file);
  3230. return true;
  3231. },
  3232. [&](const char *data, size_t data_length) {
  3233. items.back().content.append(data, data_length);
  3234. return true;
  3235. });
  3236. EXPECT_EQ(5u, items.size());
  3237. {
  3238. const auto &file = get_file_value(items, "text1");
  3239. EXPECT_TRUE(file.filename.empty());
  3240. EXPECT_EQ("text default", file.content);
  3241. }
  3242. {
  3243. const auto &file = get_file_value(items, "text2");
  3244. EXPECT_TRUE(file.filename.empty());
  3245. EXPECT_EQ("aωb", file.content);
  3246. }
  3247. {
  3248. const auto &file = get_file_value(items, "file1");
  3249. EXPECT_EQ("hello.txt", file.filename);
  3250. EXPECT_EQ("text/plain", file.content_type);
  3251. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3252. }
  3253. {
  3254. const auto &file = get_file_value(items, "file2");
  3255. EXPECT_EQ("world.json", file.filename);
  3256. EXPECT_EQ("application/json", file.content_type);
  3257. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3258. }
  3259. {
  3260. const auto &file = get_file_value(items, "file3");
  3261. EXPECT_TRUE(file.filename.empty());
  3262. EXPECT_EQ("application/octet-stream", file.content_type);
  3263. EXPECT_EQ(0u, file.content.size());
  3264. }
  3265. } else {
  3266. std::string body;
  3267. content_reader([&](const char *data, size_t data_length) {
  3268. EXPECT_EQ(7U, data_length);
  3269. body.append(data, data_length);
  3270. return true;
  3271. });
  3272. EXPECT_EQ(body, "content");
  3273. res.set_content(body, "text/plain");
  3274. }
  3275. })
  3276. .Put("/content_receiver",
  3277. [&](const Request & /*req*/, Response &res,
  3278. const ContentReader &content_reader) {
  3279. std::string body;
  3280. content_reader([&](const char *data, size_t data_length) {
  3281. body.append(data, data_length);
  3282. return true;
  3283. });
  3284. EXPECT_EQ(body, "content");
  3285. res.set_content(body, "text/plain");
  3286. })
  3287. .Patch("/content_receiver",
  3288. [&](const Request & /*req*/, Response &res,
  3289. const ContentReader &content_reader) {
  3290. std::string body;
  3291. content_reader([&](const char *data, size_t data_length) {
  3292. body.append(data, data_length);
  3293. return true;
  3294. });
  3295. EXPECT_EQ(body, "content");
  3296. res.set_content(body, "text/plain");
  3297. })
  3298. .Post("/query-string-and-body",
  3299. [&](const Request &req, Response & /*res*/) {
  3300. ASSERT_TRUE(req.has_param("key"));
  3301. EXPECT_EQ(req.get_param_value("key"), "value");
  3302. EXPECT_EQ(req.body, "content");
  3303. })
  3304. .Get("/last-request",
  3305. [&](const Request &req, Response & /*res*/) {
  3306. EXPECT_EQ("close", req.get_header_value("Connection"));
  3307. })
  3308. .Get(R"(/redirect/(\d+))",
  3309. [&](const Request &req, Response &res) {
  3310. auto num = std::stoi(req.matches[1]) + 1;
  3311. std::string url = "/redirect/" + std::to_string(num);
  3312. res.set_redirect(url);
  3313. })
  3314. .Post("/binary",
  3315. [&](const Request &req, Response &res) {
  3316. EXPECT_EQ(4U, req.body.size());
  3317. EXPECT_EQ("application/octet-stream",
  3318. req.get_header_value("Content-Type"));
  3319. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3320. res.set_content(req.body, "application/octet-stream");
  3321. })
  3322. .Put("/binary",
  3323. [&](const Request &req, Response &res) {
  3324. EXPECT_EQ(4U, req.body.size());
  3325. EXPECT_EQ("application/octet-stream",
  3326. req.get_header_value("Content-Type"));
  3327. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3328. res.set_content(req.body, "application/octet-stream");
  3329. })
  3330. .Patch("/binary",
  3331. [&](const Request &req, Response &res) {
  3332. EXPECT_EQ(4U, req.body.size());
  3333. EXPECT_EQ("application/octet-stream",
  3334. req.get_header_value("Content-Type"));
  3335. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3336. res.set_content(req.body, "application/octet-stream");
  3337. })
  3338. .Delete("/binary",
  3339. [&](const Request &req, Response &res) {
  3340. EXPECT_EQ(4U, req.body.size());
  3341. EXPECT_EQ("application/octet-stream",
  3342. req.get_header_value("Content-Type"));
  3343. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3344. res.set_content(req.body, "application/octet-stream");
  3345. })
  3346. .Get("/issue1772",
  3347. [&](const Request & /*req*/, Response &res) {
  3348. res.status = 401;
  3349. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3350. })
  3351. .Delete("/issue609",
  3352. [](const httplib::Request &, httplib::Response &res,
  3353. const httplib::ContentReader &) {
  3354. res.set_content("ok", "text/plain");
  3355. })
  3356. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3357. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3358. .Get("/compress",
  3359. [&](const Request & /*req*/, Response &res) {
  3360. res.set_content(
  3361. "12345678901234567890123456789012345678901234567890123456789"
  3362. "01234567890123456789012345678901234567890",
  3363. "text/plain");
  3364. })
  3365. .Get("/compress-with-charset",
  3366. [&](const Request & /*req*/, Response &res) {
  3367. res.set_content(
  3368. "12345678901234567890123456789012345678901234567890123456789"
  3369. "01234567890123456789012345678901234567890",
  3370. "application/json; charset=utf-8");
  3371. })
  3372. .Get("/nocompress",
  3373. [&](const Request & /*req*/, Response &res) {
  3374. res.set_content(
  3375. "12345678901234567890123456789012345678901234567890123456789"
  3376. "01234567890123456789012345678901234567890",
  3377. "application/octet-stream");
  3378. })
  3379. .Post("/compress-multipart",
  3380. [&](const Request &req, Response & /*res*/) {
  3381. EXPECT_EQ(2u, req.form.fields.size());
  3382. ASSERT_TRUE(!req.form.has_field("???"));
  3383. {
  3384. const auto &text = req.form.get_field("key1");
  3385. EXPECT_EQ("test", text);
  3386. }
  3387. {
  3388. const auto &text = req.form.get_field("key2");
  3389. EXPECT_EQ("--abcdefg123", text);
  3390. }
  3391. })
  3392. #endif
  3393. ;
  3394. persons_["john"] = "programmer";
  3395. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3396. svr_.wait_until_ready();
  3397. }
  3398. virtual void TearDown() {
  3399. svr_.stop();
  3400. if (!request_threads_.empty()) {
  3401. std::this_thread::sleep_for(std::chrono::seconds(1));
  3402. for (auto &t : request_threads_) {
  3403. t.join();
  3404. }
  3405. }
  3406. t_.join();
  3407. }
  3408. map<string, string> persons_;
  3409. #ifdef CPPHTTPLIB_SSL_ENABLED
  3410. SSLClient cli_;
  3411. SSLServer svr_;
  3412. #else
  3413. Client cli_;
  3414. Server svr_;
  3415. #endif
  3416. thread t_;
  3417. std::vector<thread> request_threads_;
  3418. };
  3419. TEST_F(ServerTest, GetMethod200) {
  3420. auto res = cli_.Get("/hi");
  3421. ASSERT_TRUE(res);
  3422. EXPECT_EQ("HTTP/1.1", res->version);
  3423. EXPECT_EQ(StatusCode::OK_200, res->status);
  3424. EXPECT_EQ("OK", res->reason);
  3425. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3426. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3427. EXPECT_EQ("Hello World!", res->body);
  3428. }
  3429. TEST_F(ServerTest, GetEmptyFile) {
  3430. auto res = cli_.Get("/empty_file");
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ(StatusCode::OK_200, res->status);
  3433. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3434. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3435. EXPECT_EQ("", res->body);
  3436. }
  3437. TEST_F(ServerTest, GetFileContent) {
  3438. auto res = cli_.Get("/file_content");
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ(StatusCode::OK_200, res->status);
  3441. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3442. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3443. EXPECT_EQ("test.html", res->body);
  3444. }
  3445. TEST_F(ServerTest, GetFileContentWithRange) {
  3446. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3447. ASSERT_TRUE(res);
  3448. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3449. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3450. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3451. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3452. EXPECT_EQ("est", res->body);
  3453. }
  3454. TEST_F(ServerTest, GetFileContentWithContentType) {
  3455. auto res = cli_.Get("/file_content_with_content_type");
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::OK_200, res->status);
  3458. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3459. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3460. EXPECT_EQ("file\n", res->body);
  3461. }
  3462. TEST_F(ServerTest, GetInvalidFileContent) {
  3463. auto res = cli_.Get("/invalid_file_content");
  3464. ASSERT_TRUE(res);
  3465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3466. }
  3467. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3468. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ("HTTP/1.1", res->version);
  3471. EXPECT_EQ(StatusCode::OK_200, res->status);
  3472. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3473. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3474. EXPECT_EQ("Hello World!", res->body);
  3475. }
  3476. TEST_F(ServerTest, GetMethod302) {
  3477. auto res = cli_.Get("/");
  3478. ASSERT_TRUE(res);
  3479. EXPECT_EQ(StatusCode::Found_302, res->status);
  3480. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3481. }
  3482. TEST_F(ServerTest, GetMethod302Redirect) {
  3483. cli_.set_follow_location(true);
  3484. auto res = cli_.Get("/");
  3485. ASSERT_TRUE(res);
  3486. EXPECT_EQ(StatusCode::OK_200, res->status);
  3487. EXPECT_EQ("Hello World!", res->body);
  3488. EXPECT_EQ("/hi", res->location);
  3489. }
  3490. TEST_F(ServerTest, GetMethod404) {
  3491. auto res = cli_.Get("/invalid");
  3492. ASSERT_TRUE(res);
  3493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3494. }
  3495. TEST_F(ServerTest, HeadMethod200) {
  3496. auto res = cli_.Head("/hi");
  3497. ASSERT_TRUE(res);
  3498. EXPECT_EQ(StatusCode::OK_200, res->status);
  3499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3500. EXPECT_TRUE(res->body.empty());
  3501. }
  3502. TEST_F(ServerTest, HeadMethod200Static) {
  3503. auto res = cli_.Head("/mount/dir/index.html");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::OK_200, res->status);
  3506. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3507. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3508. EXPECT_TRUE(res->body.empty());
  3509. }
  3510. TEST_F(ServerTest, HeadMethod404) {
  3511. auto res = cli_.Head("/invalid");
  3512. ASSERT_TRUE(res);
  3513. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3514. EXPECT_TRUE(res->body.empty());
  3515. }
  3516. TEST_F(ServerTest, GetMethodPersonJohn) {
  3517. auto res = cli_.Get("/person/john");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3521. EXPECT_EQ("programmer", res->body);
  3522. }
  3523. TEST_F(ServerTest, PostMethod1) {
  3524. auto res = cli_.Get("/person/john1");
  3525. ASSERT_TRUE(res);
  3526. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3527. res = cli_.Post("/person", "name=john1&note=coder",
  3528. "application/x-www-form-urlencoded");
  3529. ASSERT_TRUE(res);
  3530. ASSERT_EQ(StatusCode::OK_200, res->status);
  3531. res = cli_.Get("/person/john1");
  3532. ASSERT_TRUE(res);
  3533. ASSERT_EQ(StatusCode::OK_200, res->status);
  3534. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3535. ASSERT_EQ("coder", res->body);
  3536. }
  3537. TEST_F(ServerTest, PostMethod2) {
  3538. auto res = cli_.Get("/person/john2");
  3539. ASSERT_TRUE(res);
  3540. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3541. Params params;
  3542. params.emplace("name", "john2");
  3543. params.emplace("note", "coder");
  3544. res = cli_.Post("/person", params);
  3545. ASSERT_TRUE(res);
  3546. ASSERT_EQ(StatusCode::OK_200, res->status);
  3547. res = cli_.Get("/person/john2");
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3551. ASSERT_EQ("coder", res->body);
  3552. }
  3553. TEST_F(ServerTest, PutMethod3) {
  3554. auto res = cli_.Get("/person/john3");
  3555. ASSERT_TRUE(res);
  3556. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3557. Params params;
  3558. params.emplace("name", "john3");
  3559. params.emplace("note", "coder");
  3560. res = cli_.Put("/person", params);
  3561. ASSERT_TRUE(res);
  3562. ASSERT_EQ(StatusCode::OK_200, res->status);
  3563. res = cli_.Get("/person/john3");
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3567. ASSERT_EQ("coder", res->body);
  3568. }
  3569. TEST_F(ServerTest, DeleteMethod1) {
  3570. auto res = cli_.Get("/person/john4");
  3571. ASSERT_TRUE(res);
  3572. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3573. Params params;
  3574. params.emplace("name", "john4");
  3575. params.emplace("note", "coder");
  3576. res = cli_.Post("/person", params);
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::OK_200, res->status);
  3579. res = cli_.Get("/person/john4");
  3580. ASSERT_TRUE(res);
  3581. ASSERT_EQ(StatusCode::OK_200, res->status);
  3582. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3583. ASSERT_EQ("coder", res->body);
  3584. Params delete_params;
  3585. delete_params.emplace("name", "john4");
  3586. res = cli_.Delete("/person", delete_params);
  3587. ASSERT_TRUE(res);
  3588. ASSERT_EQ(StatusCode::OK_200, res->status);
  3589. ASSERT_EQ("DELETED", res->body);
  3590. res = cli_.Get("/person/john4");
  3591. ASSERT_TRUE(res);
  3592. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3593. }
  3594. TEST_F(ServerTest, DeleteMethod2) {
  3595. auto res = cli_.Get("/person/john5");
  3596. ASSERT_TRUE(res);
  3597. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3598. Params params;
  3599. params.emplace("name", "john5");
  3600. params.emplace("note", "developer");
  3601. res = cli_.Post("/person", params);
  3602. ASSERT_TRUE(res);
  3603. ASSERT_EQ(StatusCode::OK_200, res->status);
  3604. res = cli_.Get("/person/john5");
  3605. ASSERT_TRUE(res);
  3606. ASSERT_EQ(StatusCode::OK_200, res->status);
  3607. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3608. ASSERT_EQ("developer", res->body);
  3609. Params delete_params;
  3610. delete_params.emplace("name", "john5");
  3611. Headers headers;
  3612. headers.emplace("Custom-Header", "test-value");
  3613. res = cli_.Delete("/person", headers, delete_params);
  3614. ASSERT_TRUE(res);
  3615. ASSERT_EQ(StatusCode::OK_200, res->status);
  3616. ASSERT_EQ("DELETED", res->body);
  3617. res = cli_.Get("/person/john5");
  3618. ASSERT_TRUE(res);
  3619. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3620. }
  3621. TEST_F(ServerTest, DeleteMethod3) {
  3622. auto res = cli_.Get("/person/john6");
  3623. ASSERT_TRUE(res);
  3624. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3625. Params params;
  3626. params.emplace("name", "john6");
  3627. params.emplace("note", "tester");
  3628. res = cli_.Post("/person", params);
  3629. ASSERT_TRUE(res);
  3630. ASSERT_EQ(StatusCode::OK_200, res->status);
  3631. res = cli_.Get("/person/john6");
  3632. ASSERT_TRUE(res);
  3633. ASSERT_EQ(StatusCode::OK_200, res->status);
  3634. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3635. ASSERT_EQ("tester", res->body);
  3636. Params delete_params;
  3637. delete_params.emplace("name", "john6");
  3638. Headers headers;
  3639. headers.emplace("Custom-Header", "test-value");
  3640. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3641. ASSERT_TRUE(res);
  3642. ASSERT_EQ(StatusCode::OK_200, res->status);
  3643. ASSERT_EQ("DELETED", res->body);
  3644. res = cli_.Get("/person/john6");
  3645. ASSERT_TRUE(res);
  3646. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3647. }
  3648. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3649. Params params;
  3650. params.emplace("json", JSON_DATA);
  3651. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3652. ASSERT_TRUE(res);
  3653. ASSERT_EQ(StatusCode::OK_200, res->status);
  3654. ASSERT_EQ(JSON_DATA, res->body);
  3655. }
  3656. TEST_F(ServerTest, PostEmptyContent) {
  3657. auto res = cli_.Post("/empty", "", "text/plain");
  3658. ASSERT_TRUE(res);
  3659. ASSERT_EQ(StatusCode::OK_200, res->status);
  3660. ASSERT_EQ("empty", res->body);
  3661. }
  3662. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3663. auto res = cli_.Post("/empty-no-content-type");
  3664. ASSERT_TRUE(res);
  3665. ASSERT_EQ(StatusCode::OK_200, res->status);
  3666. ASSERT_EQ("empty-no-content-type", res->body);
  3667. }
  3668. TEST_F(ServerTest, PostPathOnly) {
  3669. auto res = cli_.Post("/path-only");
  3670. ASSERT_TRUE(res);
  3671. ASSERT_EQ(StatusCode::OK_200, res->status);
  3672. ASSERT_EQ("path-only", res->body);
  3673. }
  3674. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3675. auto res = cli_.Post("/path-headers-only",
  3676. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3677. ASSERT_TRUE(res);
  3678. ASSERT_EQ(StatusCode::OK_200, res->status);
  3679. ASSERT_EQ("path-headers-only", res->body);
  3680. }
  3681. TEST_F(ServerTest, PostLarge) {
  3682. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3683. ASSERT_TRUE(res);
  3684. ASSERT_EQ(StatusCode::OK_200, res->status);
  3685. EXPECT_EQ(LARGE_DATA, res->body);
  3686. }
  3687. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3688. auto res = cli_.Put("/empty-no-content-type");
  3689. ASSERT_TRUE(res);
  3690. ASSERT_EQ(StatusCode::OK_200, res->status);
  3691. ASSERT_EQ("empty-no-content-type", res->body);
  3692. }
  3693. TEST_F(ServerTest, GetMethodDir) {
  3694. auto res = cli_.Get("/dir/");
  3695. ASSERT_TRUE(res);
  3696. EXPECT_EQ(StatusCode::OK_200, res->status);
  3697. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3698. auto body = R"(<html>
  3699. <head>
  3700. </head>
  3701. <body>
  3702. <a href="/dir/test.html">Test</a>
  3703. <a href="/hi">hi</a>
  3704. </body>
  3705. </html>
  3706. )";
  3707. EXPECT_EQ(body, res->body);
  3708. }
  3709. TEST_F(ServerTest, GetMethodDirTest) {
  3710. auto res = cli_.Get("/dir/test.html");
  3711. ASSERT_TRUE(res);
  3712. EXPECT_EQ(StatusCode::OK_200, res->status);
  3713. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3714. EXPECT_EQ("test.html", res->body);
  3715. }
  3716. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3717. auto res = cli_.Get("/dir/../dir/test.html");
  3718. ASSERT_TRUE(res);
  3719. EXPECT_EQ(StatusCode::OK_200, res->status);
  3720. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3721. EXPECT_EQ("test.html", res->body);
  3722. }
  3723. TEST_F(ServerTest, GetMethodInvalidPath) {
  3724. auto res = cli_.Get("/dir/../test.html");
  3725. ASSERT_TRUE(res);
  3726. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3727. }
  3728. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3729. auto res = cli_.Get("/../www/dir/test.html");
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3732. }
  3733. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3734. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3737. }
  3738. TEST_F(ServerTest, GetMethodDirMountTest) {
  3739. auto res = cli_.Get("/mount/dir/test.html");
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::OK_200, res->status);
  3742. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3743. EXPECT_EQ("test.html", res->body);
  3744. }
  3745. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3746. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3747. ASSERT_TRUE(res);
  3748. EXPECT_EQ(StatusCode::OK_200, res->status);
  3749. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3750. EXPECT_EQ("test.html", res->body);
  3751. }
  3752. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3753. auto res = cli_.Get("/mount/dir/../test.html");
  3754. ASSERT_TRUE(res);
  3755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3756. }
  3757. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3758. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3761. }
  3762. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3763. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3766. }
  3767. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3768. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3769. ASSERT_TRUE(res);
  3770. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3771. }
  3772. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3773. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3774. ASSERT_TRUE(res);
  3775. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3776. }
  3777. TEST_F(ServerTest, PostMethod303) {
  3778. auto res = cli_.Post("/1", "body", "text/plain");
  3779. ASSERT_TRUE(res);
  3780. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3781. EXPECT_EQ("/2", res->get_header_value("Location"));
  3782. }
  3783. TEST_F(ServerTest, PostMethod303Redirect) {
  3784. cli_.set_follow_location(true);
  3785. auto res = cli_.Post("/1", "body", "text/plain");
  3786. ASSERT_TRUE(res);
  3787. EXPECT_EQ(StatusCode::OK_200, res->status);
  3788. EXPECT_EQ("redirected.", res->body);
  3789. EXPECT_EQ("/2", res->location);
  3790. }
  3791. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3792. auto res = cli_.Get("/dir/test.abcde");
  3793. ASSERT_TRUE(res);
  3794. EXPECT_EQ(StatusCode::OK_200, res->status);
  3795. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3796. EXPECT_EQ("abcde", res->body);
  3797. }
  3798. TEST_F(ServerTest, StaticFileRange) {
  3799. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3800. ASSERT_TRUE(res);
  3801. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3802. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3803. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3804. EXPECT_EQ(true, res->has_header("Content-Range"));
  3805. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3806. EXPECT_EQ(std::string("cd"), res->body);
  3807. }
  3808. TEST_F(ServerTest, StaticFileRanges) {
  3809. auto res =
  3810. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3811. ASSERT_TRUE(res);
  3812. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3813. EXPECT_TRUE(
  3814. res->get_header_value("Content-Type")
  3815. .find(
  3816. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3817. 0);
  3818. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3819. }
  3820. TEST_F(ServerTest, StaticFileRangeHead) {
  3821. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3822. ASSERT_TRUE(res);
  3823. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3824. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3825. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3826. EXPECT_EQ(true, res->has_header("Content-Range"));
  3827. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3828. }
  3829. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3830. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3831. ASSERT_TRUE(res);
  3832. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3834. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3835. EXPECT_EQ(true, res->has_header("Content-Range"));
  3836. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3837. res->get_header_value("Content-Range"));
  3838. EXPECT_EQ("LAST\n", res->body);
  3839. }
  3840. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3841. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3844. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3845. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3846. EXPECT_EQ(true, res->has_header("Content-Range"));
  3847. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3848. }
  3849. TEST_F(ServerTest, StaticFileBigFile) {
  3850. auto res = cli_.Get("/dir/1MB.txt");
  3851. ASSERT_TRUE(res);
  3852. EXPECT_EQ(StatusCode::OK_200, res->status);
  3853. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3854. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3855. }
  3856. TEST_F(ServerTest, InvalidBaseDirMount) {
  3857. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3858. }
  3859. TEST_F(ServerTest, Binary) {
  3860. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3861. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3862. "application/octet-stream");
  3863. ASSERT_TRUE(res);
  3864. ASSERT_EQ(StatusCode::OK_200, res->status);
  3865. ASSERT_EQ(4U, res->body.size());
  3866. res = cli_.Put("/binary", binary.data(), binary.size(),
  3867. "application/octet-stream");
  3868. ASSERT_TRUE(res);
  3869. ASSERT_EQ(StatusCode::OK_200, res->status);
  3870. ASSERT_EQ(4U, res->body.size());
  3871. res = cli_.Patch("/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_.Delete("/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. }
  3882. TEST_F(ServerTest, BinaryString) {
  3883. auto binary = std::string("\x00\x01\x02\x03", 4);
  3884. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3885. ASSERT_TRUE(res);
  3886. ASSERT_EQ(StatusCode::OK_200, res->status);
  3887. ASSERT_EQ(4U, res->body.size());
  3888. res = cli_.Put("/binary", binary, "application/octet-stream");
  3889. ASSERT_TRUE(res);
  3890. ASSERT_EQ(StatusCode::OK_200, res->status);
  3891. ASSERT_EQ(4U, res->body.size());
  3892. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3893. ASSERT_TRUE(res);
  3894. ASSERT_EQ(StatusCode::OK_200, res->status);
  3895. ASSERT_EQ(4U, res->body.size());
  3896. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3897. ASSERT_TRUE(res);
  3898. ASSERT_EQ(StatusCode::OK_200, res->status);
  3899. ASSERT_EQ(4U, res->body.size());
  3900. }
  3901. TEST_F(ServerTest, EmptyRequest) {
  3902. auto res = cli_.Get("");
  3903. ASSERT_TRUE(!res);
  3904. EXPECT_EQ(Error::Connection, res.error());
  3905. }
  3906. TEST_F(ServerTest, LongRequest) {
  3907. std::string request;
  3908. for (size_t i = 0; i < 545; i++) {
  3909. request += "/TooLongRequest";
  3910. }
  3911. request += "OK";
  3912. auto res = cli_.Get(request.c_str());
  3913. ASSERT_TRUE(res);
  3914. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3915. }
  3916. TEST_F(ServerTest, TooLongRequest) {
  3917. std::string request;
  3918. for (size_t i = 0; i < 546; i++) {
  3919. request += "/TooLongRequest";
  3920. }
  3921. request += "_NG";
  3922. auto start = std::chrono::high_resolution_clock::now();
  3923. cli_.set_keep_alive(true);
  3924. auto res = cli_.Get(request.c_str());
  3925. auto end = std::chrono::high_resolution_clock::now();
  3926. auto elapsed =
  3927. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3928. .count();
  3929. ASSERT_TRUE(res);
  3930. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3931. EXPECT_LE(elapsed, 1000);
  3932. EXPECT_EQ("close", res->get_header_value("Connection"));
  3933. EXPECT_FALSE(cli_.is_socket_open());
  3934. }
  3935. TEST_F(ServerTest, AlmostTooLongRequest) {
  3936. // test for #2046 - URI length check shouldn't include other content on req
  3937. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3938. // leading /, space, HTTP/1.1)
  3939. std::string request =
  3940. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3941. auto res = cli_.Get(request.c_str());
  3942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3944. }
  3945. TEST_F(ServerTest, LongHeader) {
  3946. Request req;
  3947. req.method = "GET";
  3948. req.path = "/hi";
  3949. std::string host_and_port;
  3950. host_and_port += HOST;
  3951. host_and_port += ":";
  3952. host_and_port += std::to_string(PORT);
  3953. req.headers.emplace("Host", host_and_port.c_str());
  3954. req.headers.emplace("Accept", "*/*");
  3955. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3956. req.headers.emplace(
  3957. "Header-Name",
  3958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@");
  3987. auto res = std::make_shared<Response>();
  3988. auto error = Error::Success;
  3989. auto ret = cli_.send(req, *res, error);
  3990. ASSERT_TRUE(ret);
  3991. EXPECT_EQ(StatusCode::OK_200, res->status);
  3992. }
  3993. TEST_F(ServerTest, LongQueryValue) {
  3994. auto start = std::chrono::high_resolution_clock::now();
  3995. cli_.set_keep_alive(true);
  3996. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3997. auto end = std::chrono::high_resolution_clock::now();
  3998. auto elapsed =
  3999. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4000. .count();
  4001. ASSERT_TRUE(res);
  4002. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4003. EXPECT_LE(elapsed, 1000);
  4004. EXPECT_EQ("close", res->get_header_value("Connection"));
  4005. EXPECT_FALSE(cli_.is_socket_open());
  4006. }
  4007. TEST_F(ServerTest, TooLongQueryValue) {
  4008. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4009. ASSERT_FALSE(res);
  4010. EXPECT_EQ(Error::Read, res.error());
  4011. }
  4012. TEST_F(ServerTest, TooLongHeader) {
  4013. Request req;
  4014. req.method = "GET";
  4015. req.path = "/hi";
  4016. std::string host_and_port;
  4017. host_and_port += HOST;
  4018. host_and_port += ":";
  4019. host_and_port += std::to_string(PORT);
  4020. req.headers.emplace("Host", host_and_port.c_str());
  4021. req.headers.emplace("Accept", "*/*");
  4022. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4023. req.headers.emplace(
  4024. "Header-Name",
  4025. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4053. "@@@@@@@@@@@@@@@@@");
  4054. auto res = std::make_shared<Response>();
  4055. auto error = Error::Success;
  4056. auto ret = cli_.send(req, *res, error);
  4057. ASSERT_TRUE(ret);
  4058. EXPECT_EQ(StatusCode::OK_200, res->status);
  4059. }
  4060. TEST_F(ServerTest, HeaderCountAtLimit) {
  4061. // Test with headers just under the 100 limit
  4062. httplib::Headers headers;
  4063. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4064. // This should keep us just under the 100 header limit
  4065. for (int i = 0; i < 95; i++) {
  4066. std::string name = "X-Test-Header-" + std::to_string(i);
  4067. std::string value = "value" + std::to_string(i);
  4068. headers.emplace(name, value);
  4069. }
  4070. // This should work fine as we're under the limit
  4071. auto res = cli_.Get("/hi", headers);
  4072. EXPECT_TRUE(res);
  4073. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4074. }
  4075. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4076. // Test with many headers to exceed the 100 limit
  4077. httplib::Headers headers;
  4078. // Add 150 headers to definitely exceed the 100 limit
  4079. for (int i = 0; i < 150; i++) {
  4080. std::string name = "X-Test-Header-" + std::to_string(i);
  4081. std::string value = "value" + std::to_string(i);
  4082. headers.emplace(name, value);
  4083. }
  4084. // This should fail due to exceeding header count limit
  4085. cli_.set_keep_alive(true);
  4086. auto res = cli_.Get("/hi", headers);
  4087. // The server should respond with 400 Bad Request
  4088. ASSERT_TRUE(res);
  4089. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4090. EXPECT_EQ("close", res->get_header_value("Connection"));
  4091. EXPECT_FALSE(cli_.is_socket_open());
  4092. }
  4093. TEST_F(ServerTest, PercentEncoding) {
  4094. auto res = cli_.Get("/e%6edwith%");
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ(StatusCode::OK_200, res->status);
  4097. }
  4098. TEST_F(ServerTest, PercentEncodingUnicode) {
  4099. auto res = cli_.Get("/e%u006edwith%");
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::OK_200, res->status);
  4102. }
  4103. TEST_F(ServerTest, InvalidPercentEncoding) {
  4104. auto res = cli_.Get("/%endwith%");
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4107. }
  4108. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4109. auto res = cli_.Get("/%uendwith%");
  4110. ASSERT_TRUE(res);
  4111. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4112. }
  4113. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4114. auto res = cli_.Get("/hello?aaa=bbb%");
  4115. ASSERT_TRUE(res);
  4116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4117. }
  4118. TEST_F(ServerTest, PlusSignEncoding) {
  4119. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4120. ASSERT_TRUE(res);
  4121. EXPECT_EQ(StatusCode::OK_200, res->status);
  4122. EXPECT_EQ("a +b", res->body);
  4123. }
  4124. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4125. // This test simulates a potential DoS attack using many headers
  4126. // to verify our security fix prevents memory exhaustion
  4127. httplib::Headers attack_headers;
  4128. // Attempt to add many headers like an attacker would (200 headers to far
  4129. // exceed limit)
  4130. for (int i = 0; i < 200; i++) {
  4131. std::string name = "X-Attack-Header-" + std::to_string(i);
  4132. std::string value = "attack_payload_" + std::to_string(i);
  4133. attack_headers.emplace(name, value);
  4134. }
  4135. // Try to POST with excessive headers
  4136. cli_.set_keep_alive(true);
  4137. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4138. // Should either fail or return 400 Bad Request due to security limit
  4139. if (res) {
  4140. // If we get a response, it should be 400 Bad Request
  4141. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4142. EXPECT_EQ("close", res->get_header_value("Connection"));
  4143. }
  4144. EXPECT_FALSE(cli_.is_socket_open());
  4145. }
  4146. TEST_F(ServerTest, MultipartFormData) {
  4147. UploadFormDataItems items = {
  4148. {"text1", "text default", "", ""},
  4149. {"text2", "aωb", "", ""},
  4150. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4151. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4152. {"file3", "", "", "application/octet-stream"},
  4153. {"file4", "", "", " application/json tmp-string "}};
  4154. auto res = cli_.Post("/multipart", items);
  4155. ASSERT_TRUE(res);
  4156. EXPECT_EQ(StatusCode::OK_200, res->status);
  4157. }
  4158. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4159. UploadFormDataItems items = {
  4160. {"text", "default text", "", ""},
  4161. {"multi_text1", "aaaaa", "", ""},
  4162. {"multi_text1", "bbbbb", "", ""},
  4163. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4164. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4165. "application/json"},
  4166. };
  4167. auto res = cli_.Post("/multipart/multi_file_values", items);
  4168. ASSERT_TRUE(res);
  4169. EXPECT_EQ(StatusCode::OK_200, res->status);
  4170. }
  4171. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4172. auto res = cli_.Get("/hi");
  4173. ASSERT_TRUE(res);
  4174. EXPECT_EQ(StatusCode::OK_200, res->status);
  4175. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4176. EXPECT_EQ("Hello World!", res->body);
  4177. }
  4178. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4179. Request req;
  4180. req.method = "POST";
  4181. req.path = "/chunked";
  4182. std::string host_and_port;
  4183. host_and_port += HOST;
  4184. host_and_port += ":";
  4185. host_and_port += std::to_string(PORT);
  4186. req.headers.emplace("Host", host_and_port.c_str());
  4187. req.headers.emplace("Accept", "*/*");
  4188. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4189. req.headers.emplace("Content-Type", "text/plain");
  4190. req.headers.emplace("Content-Length", "0");
  4191. req.headers.emplace(
  4192. "Transfer-Encoding",
  4193. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4194. // Client does not chunk, so make a chunked body manually.
  4195. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4196. auto res = std::make_shared<Response>();
  4197. auto error = Error::Success;
  4198. auto ret = cli_.send(req, *res, error);
  4199. ASSERT_TRUE(ret);
  4200. EXPECT_EQ(StatusCode::OK_200, res->status);
  4201. }
  4202. TEST_F(ServerTest, GetStreamed2) {
  4203. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4204. ASSERT_TRUE(res);
  4205. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4206. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4207. EXPECT_EQ(true, res->has_header("Content-Range"));
  4208. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4209. EXPECT_EQ(std::string("ab"), res->body);
  4210. }
  4211. TEST_F(ServerTest, GetStreamed) {
  4212. auto res = cli_.Get("/streamed");
  4213. ASSERT_TRUE(res);
  4214. EXPECT_EQ(StatusCode::OK_200, res->status);
  4215. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4216. EXPECT_EQ(std::string("aaabbb"), res->body);
  4217. }
  4218. TEST_F(ServerTest, GetStreamedWithRange1) {
  4219. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4220. ASSERT_TRUE(res);
  4221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4222. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4223. EXPECT_EQ(true, res->has_header("Content-Range"));
  4224. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4225. EXPECT_EQ(std::string("def"), res->body);
  4226. }
  4227. TEST_F(ServerTest, GetStreamedWithRange2) {
  4228. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4229. ASSERT_TRUE(res);
  4230. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4231. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4232. EXPECT_EQ(true, res->has_header("Content-Range"));
  4233. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4234. EXPECT_EQ(std::string("bcdefg"), res->body);
  4235. }
  4236. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4237. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4238. ASSERT_TRUE(res);
  4239. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4240. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4241. EXPECT_EQ(true, res->has_header("Content-Range"));
  4242. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4243. EXPECT_EQ(std::string("efg"), res->body);
  4244. }
  4245. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4246. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4249. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4250. EXPECT_EQ(false, res->has_header("Content-Range"));
  4251. EXPECT_EQ(0U, res->body.size());
  4252. }
  4253. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4254. auto res = cli_.Get("/streamed-with-range",
  4255. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4256. "92233720368547758079223372036854775807"}});
  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, GetRangeWithMaxLongLength) {
  4264. auto res = cli_.Get(
  4265. "/with-range",
  4266. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4267. {"Accept-Encoding", ""}});
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4270. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4271. EXPECT_EQ(true, res->has_header("Content-Range"));
  4272. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4273. EXPECT_EQ(std::string("abcdefg"), res->body);
  4274. }
  4275. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4276. auto res = cli_.Get("/with-range", {
  4277. {"Range", "bytes=0-"},
  4278. {"Accept-Encoding", ""},
  4279. });
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4282. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4283. EXPECT_EQ(true, res->has_header("Content-Range"));
  4284. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4285. EXPECT_EQ(std::string("abcdefg"), res->body);
  4286. }
  4287. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4288. auto res =
  4289. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4292. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4293. EXPECT_EQ(false, res->has_header("Content-Range"));
  4294. EXPECT_EQ(267U, res->body.size());
  4295. // Check that both range contents are present
  4296. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4297. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4298. // Check that Content-Range headers are present for both ranges
  4299. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4300. std::string::npos);
  4301. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4302. std::string::npos);
  4303. }
  4304. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4305. Ranges ranges;
  4306. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4307. ranges.emplace_back(0, -1);
  4308. }
  4309. auto res =
  4310. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4311. ASSERT_TRUE(res);
  4312. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4313. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4314. EXPECT_EQ(false, res->has_header("Content-Range"));
  4315. EXPECT_EQ(0U, res->body.size());
  4316. }
  4317. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4318. auto res =
  4319. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4320. ASSERT_TRUE(res);
  4321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4322. EXPECT_EQ(5U, res->body.size());
  4323. // Check that overlapping ranges are coalesced into a single range
  4324. EXPECT_EQ("bcdef", res->body);
  4325. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4326. // Should be single range, not multipart
  4327. EXPECT_TRUE(res->has_header("Content-Range"));
  4328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4329. }
  4330. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4331. auto res =
  4332. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4333. ASSERT_TRUE(res);
  4334. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4335. EXPECT_EQ(268U, res->body.size());
  4336. // Check that both range contents are present
  4337. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4338. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4339. // Check that Content-Range headers are present for both ranges
  4340. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4341. std::string::npos);
  4342. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4343. std::string::npos);
  4344. }
  4345. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4346. auto res =
  4347. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4350. EXPECT_EQ(269U, res->body.size());
  4351. // Check that both duplicate range contents are present
  4352. size_t first_abc = res->body.find("abc\r\n");
  4353. EXPECT_TRUE(first_abc != std::string::npos);
  4354. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4355. EXPECT_TRUE(second_abc != std::string::npos);
  4356. // Check that Content-Range headers are present for both ranges
  4357. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4358. EXPECT_TRUE(first_range != std::string::npos);
  4359. size_t second_range =
  4360. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4361. EXPECT_TRUE(second_range != std::string::npos);
  4362. }
  4363. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4364. auto res = cli_.Get("/streamed-with-range?error",
  4365. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4368. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4369. EXPECT_EQ(false, res->has_header("Content-Range"));
  4370. EXPECT_EQ(0U, res->body.size());
  4371. }
  4372. TEST_F(ServerTest, GetStreamedEndless) {
  4373. uint64_t offset = 0;
  4374. auto res = cli_.Get("/streamed-cancel",
  4375. [&](const char * /*data*/, uint64_t data_length) {
  4376. if (offset < 100) {
  4377. offset += data_length;
  4378. return true;
  4379. }
  4380. return false;
  4381. });
  4382. ASSERT_TRUE(!res);
  4383. EXPECT_EQ(Error::Canceled, res.error());
  4384. }
  4385. TEST_F(ServerTest, ClientStop) {
  4386. std::atomic_size_t count{4};
  4387. std::vector<std::thread> threads;
  4388. for (auto i = count.load(); i != 0; --i) {
  4389. threads.emplace_back([&]() {
  4390. auto res = cli_.Get("/streamed-cancel",
  4391. [&](const char *, uint64_t) { return true; });
  4392. --count;
  4393. ASSERT_TRUE(!res);
  4394. EXPECT_TRUE(res.error() == Error::Canceled ||
  4395. res.error() == Error::Read || res.error() == Error::Write);
  4396. });
  4397. }
  4398. std::this_thread::sleep_for(std::chrono::seconds(2));
  4399. while (count != 0) {
  4400. cli_.stop();
  4401. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4402. }
  4403. for (auto &t : threads) {
  4404. t.join();
  4405. }
  4406. }
  4407. TEST_F(ServerTest, GetWithRange1) {
  4408. auto res = cli_.Get("/with-range", {
  4409. make_range_header({{3, 5}}),
  4410. {"Accept-Encoding", ""},
  4411. });
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4414. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4415. EXPECT_EQ(true, res->has_header("Content-Range"));
  4416. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4417. EXPECT_EQ(std::string("def"), res->body);
  4418. }
  4419. TEST_F(ServerTest, GetWithRange2) {
  4420. auto res = cli_.Get("/with-range", {
  4421. make_range_header({{1, -1}}),
  4422. {"Accept-Encoding", ""},
  4423. });
  4424. ASSERT_TRUE(res);
  4425. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4426. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4427. EXPECT_EQ(true, res->has_header("Content-Range"));
  4428. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4429. EXPECT_EQ(std::string("bcdefg"), res->body);
  4430. }
  4431. TEST_F(ServerTest, GetWithRange3) {
  4432. auto res = cli_.Get("/with-range", {
  4433. make_range_header({{0, 0}}),
  4434. {"Accept-Encoding", ""},
  4435. });
  4436. ASSERT_TRUE(res);
  4437. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4438. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4439. EXPECT_EQ(true, res->has_header("Content-Range"));
  4440. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4441. EXPECT_EQ(std::string("a"), res->body);
  4442. }
  4443. TEST_F(ServerTest, GetWithRange4) {
  4444. auto res = cli_.Get("/with-range", {
  4445. make_range_header({{-1, 2}}),
  4446. {"Accept-Encoding", ""},
  4447. });
  4448. ASSERT_TRUE(res);
  4449. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4450. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4451. EXPECT_EQ(true, res->has_header("Content-Range"));
  4452. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4453. EXPECT_EQ(std::string("fg"), res->body);
  4454. }
  4455. TEST_F(ServerTest, GetWithRange5) {
  4456. auto res = cli_.Get("/with-range", {
  4457. make_range_header({{0, 5}}),
  4458. {"Accept-Encoding", ""},
  4459. });
  4460. ASSERT_TRUE(res);
  4461. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4462. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4463. EXPECT_EQ(true, res->has_header("Content-Range"));
  4464. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4465. EXPECT_EQ(std::string("abcdef"), res->body);
  4466. }
  4467. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4468. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4469. ASSERT_TRUE(res);
  4470. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4471. }
  4472. TEST_F(ServerTest, GetWithRangeMultipart) {
  4473. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4474. ASSERT_TRUE(res);
  4475. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4476. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4477. EXPECT_EQ(false, res->has_header("Content-Range"));
  4478. EXPECT_EQ(267U, res->body.size());
  4479. }
  4480. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4481. auto res =
  4482. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4483. ASSERT_TRUE(res);
  4484. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4485. }
  4486. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4487. auto res = cli_.Get("/with-range-customized-response",
  4488. {{make_range_header({{1, 2}})}});
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4491. EXPECT_EQ(true, res->has_header("Content-Length"));
  4492. EXPECT_EQ(false, res->has_header("Content-Range"));
  4493. EXPECT_EQ(JSON_DATA, res->body);
  4494. }
  4495. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4496. auto res = cli_.Get("/with-range-customized-response",
  4497. {{make_range_header({{1, 2}, {4, 5}})}});
  4498. ASSERT_TRUE(res);
  4499. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4500. EXPECT_EQ(true, res->has_header("Content-Length"));
  4501. EXPECT_EQ(false, res->has_header("Content-Range"));
  4502. EXPECT_EQ(JSON_DATA, res->body);
  4503. }
  4504. TEST_F(ServerTest, Issue1772) {
  4505. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4508. }
  4509. TEST_F(ServerTest, Issue609) {
  4510. auto res = cli_.Delete("/issue609");
  4511. ASSERT_TRUE(res);
  4512. EXPECT_EQ(StatusCode::OK_200, res->status);
  4513. EXPECT_EQ(std::string("ok"), res->body);
  4514. }
  4515. TEST_F(ServerTest, GetStreamedChunked) {
  4516. auto res = cli_.Get("/streamed-chunked");
  4517. ASSERT_TRUE(res);
  4518. EXPECT_EQ(StatusCode::OK_200, res->status);
  4519. EXPECT_EQ(std::string("123456789"), res->body);
  4520. }
  4521. TEST_F(ServerTest, GetStreamedChunked2) {
  4522. auto res = cli_.Get("/streamed-chunked2");
  4523. ASSERT_TRUE(res);
  4524. EXPECT_EQ(StatusCode::OK_200, res->status);
  4525. EXPECT_EQ(std::string("123456789"), res->body);
  4526. }
  4527. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4528. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ(std::string("123456789"), res->body);
  4532. EXPECT_TRUE(res->has_header("Trailer"));
  4533. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4534. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4535. // Trailers are now stored separately from headers (security fix)
  4536. EXPECT_EQ(2U, res->trailers.size());
  4537. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4538. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4539. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4540. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4541. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4542. // Verify trailers are NOT in headers (security verification)
  4543. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4544. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4545. }
  4546. TEST_F(ServerTest, LargeChunkedPost) {
  4547. Request req;
  4548. req.method = "POST";
  4549. req.path = "/large-chunked";
  4550. std::string host_and_port;
  4551. host_and_port += HOST;
  4552. host_and_port += ":";
  4553. host_and_port += std::to_string(PORT);
  4554. req.headers.emplace("Host", host_and_port.c_str());
  4555. req.headers.emplace("Accept", "*/*");
  4556. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4557. req.headers.emplace("Content-Type", "text/plain");
  4558. req.headers.emplace("Content-Length", "0");
  4559. req.headers.emplace("Transfer-Encoding", "chunked");
  4560. std::string long_string(30 * 1024u, 'a');
  4561. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4562. // Attempt to make a large enough post to exceed OS buffers, to test that
  4563. // the server handles short reads if the full chunk data isn't available.
  4564. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4565. auto res = std::make_shared<Response>();
  4566. auto error = Error::Success;
  4567. auto ret = cli_.send(req, *res, error);
  4568. ASSERT_TRUE(ret);
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. }
  4571. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4572. auto res = cli_.Get("/remote_addr");
  4573. ASSERT_TRUE(res);
  4574. EXPECT_EQ(StatusCode::OK_200, res->status);
  4575. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4576. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4577. }
  4578. TEST_F(ServerTest, GetMethodLocalAddr) {
  4579. auto res = cli_.Get("/local_addr");
  4580. ASSERT_TRUE(res);
  4581. EXPECT_EQ(StatusCode::OK_200, res->status);
  4582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4583. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4584. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4585. }
  4586. TEST_F(ServerTest, HTTPResponseSplitting) {
  4587. auto res = cli_.Get("/http_response_splitting");
  4588. ASSERT_TRUE(res);
  4589. EXPECT_EQ(StatusCode::OK_200, res->status);
  4590. }
  4591. TEST_F(ServerTest, SlowRequest) {
  4592. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4593. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4594. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4595. }
  4596. #if 0
  4597. TEST_F(ServerTest, SlowPost) {
  4598. char buffer[64 * 1024];
  4599. memset(buffer, 0x42, sizeof(buffer));
  4600. auto res = cli_.Post(
  4601. "/slowpost", 64 * 1024 * 1024,
  4602. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4603. auto ret = sink.write(buffer, sizeof(buffer));
  4604. EXPECT_TRUE(ret);
  4605. return true;
  4606. },
  4607. "text/plain");
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. }
  4611. TEST_F(ServerTest, SlowPostFail) {
  4612. char buffer[64 * 1024];
  4613. memset(buffer, 0x42, sizeof(buffer));
  4614. cli_.set_write_timeout(std::chrono::seconds(0));
  4615. auto res = cli_.Post(
  4616. "/slowpost", 64 * 1024 * 1024,
  4617. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4618. sink.write(buffer, sizeof(buffer));
  4619. return true;
  4620. },
  4621. "text/plain");
  4622. ASSERT_TRUE(!res);
  4623. EXPECT_EQ(Error::Write, res.error());
  4624. }
  4625. #endif
  4626. TEST_F(ServerTest, Put) {
  4627. auto res = cli_.Put("/put", "PUT", "text/plain");
  4628. ASSERT_TRUE(res);
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. EXPECT_EQ("PUT", res->body);
  4631. }
  4632. TEST_F(ServerTest, PutWithContentProvider) {
  4633. auto res = cli_.Put(
  4634. "/put", 3,
  4635. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4636. sink.os << "PUT";
  4637. return true;
  4638. },
  4639. "text/plain");
  4640. ASSERT_TRUE(res);
  4641. EXPECT_EQ(StatusCode::OK_200, res->status);
  4642. EXPECT_EQ("PUT", res->body);
  4643. }
  4644. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4645. auto res = cli_.Post(
  4646. "/post", 42,
  4647. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4648. return false;
  4649. },
  4650. "text/plain");
  4651. ASSERT_TRUE(!res);
  4652. EXPECT_EQ(Error::Canceled, res.error());
  4653. }
  4654. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4655. auto res = cli_.Put(
  4656. "/put",
  4657. [](size_t /*offset*/, DataSink &sink) {
  4658. sink.os << "PUT";
  4659. sink.done();
  4660. return true;
  4661. },
  4662. "text/plain");
  4663. ASSERT_TRUE(res);
  4664. EXPECT_EQ(StatusCode::OK_200, res->status);
  4665. EXPECT_EQ("PUT", res->body);
  4666. }
  4667. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4668. auto res = cli_.Post(
  4669. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4670. "text/plain");
  4671. ASSERT_TRUE(!res);
  4672. EXPECT_EQ(Error::Canceled, res.error());
  4673. }
  4674. TEST_F(ServerTest, PostLoopBack) {
  4675. std::string body;
  4676. auto res = cli_.Post(
  4677. "/post-loopback", 9,
  4678. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4679. EXPECT_EQ(9u, length);
  4680. sink.write("123", 3);
  4681. sink.write("456", 3);
  4682. sink.write("789", 3);
  4683. return true;
  4684. },
  4685. "text/plain",
  4686. [&body](const char *data, size_t data_length) {
  4687. body.append(data, data_length);
  4688. return true;
  4689. });
  4690. ASSERT_TRUE(res);
  4691. EXPECT_EQ(StatusCode::OK_200, res->status);
  4692. EXPECT_EQ("123456789", body);
  4693. }
  4694. TEST_F(ServerTest, PutLoopBack) {
  4695. std::string body;
  4696. auto res = cli_.Put(
  4697. "/put-loopback", 9,
  4698. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4699. EXPECT_EQ(9u, length);
  4700. sink.write("123", 3);
  4701. sink.write("456", 3);
  4702. sink.write("789", 3);
  4703. return true;
  4704. },
  4705. "text/plain",
  4706. [&body](const char *data, size_t data_length) {
  4707. body.append(data, data_length);
  4708. return true;
  4709. });
  4710. ASSERT_TRUE(res);
  4711. EXPECT_EQ(StatusCode::OK_200, res->status);
  4712. EXPECT_EQ("123456789", body);
  4713. }
  4714. TEST_F(ServerTest, PatchLoopBack) {
  4715. std::string body;
  4716. auto res = cli_.Patch(
  4717. "/patch-loopback", 9,
  4718. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4719. EXPECT_EQ(9u, length);
  4720. sink.write("123", 3);
  4721. sink.write("456", 3);
  4722. sink.write("789", 3);
  4723. return true;
  4724. },
  4725. "text/plain",
  4726. [&body](const char *data, size_t data_length) {
  4727. body.append(data, data_length);
  4728. return true;
  4729. });
  4730. ASSERT_TRUE(res);
  4731. EXPECT_EQ(StatusCode::OK_200, res->status);
  4732. EXPECT_EQ("123456789", body);
  4733. }
  4734. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4735. std::string body;
  4736. auto res = cli_.Post(
  4737. "/post-loopback",
  4738. [](size_t /*offset*/, DataSink &sink) {
  4739. sink.write("123", 3);
  4740. sink.write("456", 3);
  4741. sink.write("789", 3);
  4742. sink.done();
  4743. return true;
  4744. },
  4745. "text/plain",
  4746. [&body](const char *data, size_t data_length) {
  4747. body.append(data, data_length);
  4748. return true;
  4749. });
  4750. ASSERT_TRUE(res);
  4751. EXPECT_EQ(StatusCode::OK_200, res->status);
  4752. EXPECT_EQ("123456789", body);
  4753. }
  4754. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4755. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4756. cli_.set_compress(true);
  4757. auto res = cli_.Put(
  4758. "/put", 3,
  4759. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4760. sink.os << "PUT";
  4761. return true;
  4762. },
  4763. "text/plain");
  4764. ASSERT_TRUE(res);
  4765. EXPECT_EQ(StatusCode::OK_200, res->status);
  4766. EXPECT_EQ("PUT", res->body);
  4767. }
  4768. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4769. cli_.set_compress(true);
  4770. auto res = cli_.Post(
  4771. "/post", 42,
  4772. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4773. return false;
  4774. },
  4775. "text/plain");
  4776. ASSERT_TRUE(!res);
  4777. EXPECT_EQ(Error::Canceled, res.error());
  4778. }
  4779. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4780. cli_.set_compress(true);
  4781. auto res = cli_.Put(
  4782. "/put",
  4783. [](size_t /*offset*/, DataSink &sink) {
  4784. sink.os << "PUT";
  4785. sink.done();
  4786. return true;
  4787. },
  4788. "text/plain");
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ("PUT", res->body);
  4792. }
  4793. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4794. cli_.set_compress(true);
  4795. auto res = cli_.Post(
  4796. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4797. "text/plain");
  4798. ASSERT_TRUE(!res);
  4799. EXPECT_EQ(Error::Canceled, res.error());
  4800. }
  4801. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4802. cli_.set_compress(true);
  4803. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4804. ASSERT_TRUE(res);
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. EXPECT_EQ(LARGE_DATA, res->body);
  4807. }
  4808. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4809. #ifdef CPPHTTPLIB_SSL_ENABLED
  4810. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4811. Client cli(s.c_str());
  4812. cli.enable_server_certificate_verification(false);
  4813. #else
  4814. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4815. Client cli(s.c_str());
  4816. #endif
  4817. cli.set_compress(true);
  4818. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4819. ASSERT_TRUE(res);
  4820. EXPECT_EQ(StatusCode::OK_200, res->status);
  4821. EXPECT_EQ(LARGE_DATA, res->body);
  4822. // The compressed size should be less than a 10th of the original. May vary
  4823. // depending on the zlib library.
  4824. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4825. static_cast<uint64_t>(10 * 1024 * 1024));
  4826. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4827. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4828. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4829. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4830. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4831. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4832. #endif
  4833. }
  4834. TEST_F(ServerTest, PutContentWithDeflate) {
  4835. cli_.set_compress(false);
  4836. Headers headers;
  4837. headers.emplace("Content-Encoding", "deflate");
  4838. // PUT in deflate format:
  4839. auto res = cli_.Put("/put", headers,
  4840. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4841. ASSERT_TRUE(res);
  4842. EXPECT_EQ(StatusCode::OK_200, res->status);
  4843. EXPECT_EQ("PUT", res->body);
  4844. }
  4845. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4846. Headers headers;
  4847. headers.emplace("Accept-Encoding", "gzip, deflate");
  4848. auto res = cli_.Get("/streamed-chunked", headers);
  4849. ASSERT_TRUE(res);
  4850. EXPECT_EQ(StatusCode::OK_200, res->status);
  4851. EXPECT_EQ(std::string("123456789"), res->body);
  4852. }
  4853. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4854. Headers headers;
  4855. headers.emplace("Accept-Encoding", "gzip, deflate");
  4856. auto res = cli_.Get("/streamed-chunked2", headers);
  4857. ASSERT_TRUE(res);
  4858. EXPECT_EQ(StatusCode::OK_200, res->status);
  4859. EXPECT_EQ(std::string("123456789"), res->body);
  4860. }
  4861. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4862. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4863. ASSERT_TRUE(res);
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. }
  4866. TEST(GzipDecompressor, ChunkedDecompression) {
  4867. std::string data;
  4868. for (size_t i = 0; i < 32 * 1024; ++i) {
  4869. data.push_back(static_cast<char>('a' + i % 26));
  4870. }
  4871. std::string compressed_data;
  4872. {
  4873. httplib::detail::gzip_compressor compressor;
  4874. bool result = compressor.compress(
  4875. data.data(), data.size(),
  4876. /*last=*/true,
  4877. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4878. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4879. compressed_data_size);
  4880. return true;
  4881. });
  4882. ASSERT_TRUE(result);
  4883. }
  4884. std::string decompressed_data;
  4885. {
  4886. httplib::detail::gzip_decompressor decompressor;
  4887. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4888. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4889. size_t chunk_size = 130;
  4890. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4891. chunk_begin += chunk_size) {
  4892. size_t current_chunk_size =
  4893. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4894. bool result = decompressor.decompress(
  4895. compressed_data.data() + chunk_begin, current_chunk_size,
  4896. [&](const char *decompressed_data_chunk,
  4897. size_t decompressed_data_chunk_size) {
  4898. decompressed_data.insert(decompressed_data.size(),
  4899. decompressed_data_chunk,
  4900. decompressed_data_chunk_size);
  4901. return true;
  4902. });
  4903. ASSERT_TRUE(result);
  4904. }
  4905. }
  4906. ASSERT_EQ(data, decompressed_data);
  4907. }
  4908. TEST(GzipDecompressor, DeflateDecompression) {
  4909. std::string original_text = "Raw deflate without gzip";
  4910. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4911. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4912. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4913. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4914. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4915. std::string decompressed_data;
  4916. {
  4917. httplib::detail::gzip_decompressor decompressor;
  4918. bool result = decompressor.decompress(
  4919. compressed_data.data(), compressed_data.size(),
  4920. [&](const char *decompressed_data_chunk,
  4921. size_t decompressed_data_chunk_size) {
  4922. decompressed_data.insert(decompressed_data.size(),
  4923. decompressed_data_chunk,
  4924. decompressed_data_chunk_size);
  4925. return true;
  4926. });
  4927. ASSERT_TRUE(result);
  4928. }
  4929. ASSERT_EQ(original_text, decompressed_data);
  4930. }
  4931. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4932. std::string original_text = "Raw deflate without gzip";
  4933. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4934. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4935. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4936. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4937. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4938. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4939. std::string decompressed_data;
  4940. {
  4941. httplib::detail::gzip_decompressor decompressor;
  4942. bool result = decompressor.decompress(
  4943. compressed_data.data(), compressed_data.size(),
  4944. [&](const char *decompressed_data_chunk,
  4945. size_t decompressed_data_chunk_size) {
  4946. decompressed_data.insert(decompressed_data.size(),
  4947. decompressed_data_chunk,
  4948. decompressed_data_chunk_size);
  4949. return true;
  4950. });
  4951. ASSERT_TRUE(result);
  4952. }
  4953. ASSERT_EQ(original_text, decompressed_data);
  4954. }
  4955. #endif
  4956. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4957. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4958. Headers headers;
  4959. headers.emplace("Accept-Encoding", "br");
  4960. auto res = cli_.Get("/streamed-chunked", headers);
  4961. ASSERT_TRUE(res);
  4962. EXPECT_EQ(StatusCode::OK_200, res->status);
  4963. EXPECT_EQ(std::string("123456789"), res->body);
  4964. }
  4965. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4966. Headers headers;
  4967. headers.emplace("Accept-Encoding", "br");
  4968. auto res = cli_.Get("/streamed-chunked2", headers);
  4969. ASSERT_TRUE(res);
  4970. EXPECT_EQ(StatusCode::OK_200, res->status);
  4971. EXPECT_EQ(std::string("123456789"), res->body);
  4972. }
  4973. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4974. cli_.set_compress(true);
  4975. auto res = cli_.Put(
  4976. "/put", 3,
  4977. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4978. sink.os << "PUT";
  4979. return true;
  4980. },
  4981. "text/plain");
  4982. ASSERT_TRUE(res);
  4983. EXPECT_EQ(StatusCode::OK_200, res->status);
  4984. EXPECT_EQ("PUT", res->body);
  4985. }
  4986. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4987. cli_.set_compress(true);
  4988. auto res = cli_.Put(
  4989. "/put",
  4990. [](size_t /*offset*/, DataSink &sink) {
  4991. sink.os << "PUT";
  4992. sink.done();
  4993. return true;
  4994. },
  4995. "text/plain");
  4996. ASSERT_TRUE(res);
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("PUT", res->body);
  4999. }
  5000. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5001. cli_.set_compress(true);
  5002. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5003. ASSERT_TRUE(res);
  5004. EXPECT_EQ(StatusCode::OK_200, res->status);
  5005. EXPECT_EQ(LARGE_DATA, res->body);
  5006. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5007. }
  5008. #endif
  5009. TEST_F(ServerTest, Patch) {
  5010. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5011. ASSERT_TRUE(res);
  5012. EXPECT_EQ(StatusCode::OK_200, res->status);
  5013. EXPECT_EQ("PATCH", res->body);
  5014. }
  5015. TEST_F(ServerTest, Delete) {
  5016. auto res = cli_.Delete("/delete");
  5017. ASSERT_TRUE(res);
  5018. EXPECT_EQ(StatusCode::OK_200, res->status);
  5019. EXPECT_EQ("DELETE", res->body);
  5020. }
  5021. TEST_F(ServerTest, DeleteContentReceiver) {
  5022. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(StatusCode::OK_200, res->status);
  5025. EXPECT_EQ("content", res->body);
  5026. }
  5027. TEST_F(ServerTest, Options) {
  5028. auto res = cli_.Options("*");
  5029. ASSERT_TRUE(res);
  5030. EXPECT_EQ(StatusCode::OK_200, res->status);
  5031. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5032. EXPECT_TRUE(res->body.empty());
  5033. }
  5034. TEST_F(ServerTest, URL) {
  5035. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5036. ASSERT_TRUE(res);
  5037. EXPECT_EQ(StatusCode::OK_200, res->status);
  5038. }
  5039. TEST_F(ServerTest, ArrayParam) {
  5040. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5041. ASSERT_TRUE(res);
  5042. EXPECT_EQ(StatusCode::OK_200, res->status);
  5043. }
  5044. TEST_F(ServerTest, NoMultipleHeaders) {
  5045. Headers headers = {{"Content-Length", "5"}};
  5046. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5047. "text/plain");
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. }
  5051. TEST_F(ServerTest, PostContentReceiver) {
  5052. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5053. ASSERT_TRUE(res);
  5054. ASSERT_EQ(StatusCode::OK_200, res->status);
  5055. ASSERT_EQ("content", res->body);
  5056. }
  5057. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5058. UploadFormDataItems items = {
  5059. {"text1", "text default", "", ""},
  5060. {"text2", "aωb", "", ""},
  5061. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5062. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5063. {"file3", "", "", "application/octet-stream"},
  5064. };
  5065. auto res = cli_.Post("/content_receiver", items);
  5066. ASSERT_TRUE(res);
  5067. EXPECT_EQ(StatusCode::OK_200, res->status);
  5068. }
  5069. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5070. UploadFormDataItems items = {
  5071. {"text1", "text default", "", ""},
  5072. {"text2", "aωb", "", ""},
  5073. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5074. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5075. {"file3", "", "", "application/octet-stream"},
  5076. };
  5077. auto boundary = std::string("+++++");
  5078. std::string body;
  5079. for (const auto &item : items) {
  5080. body += "--" + boundary + "\r\n";
  5081. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5082. if (!item.filename.empty()) {
  5083. body += "; filename=\"" + item.filename + "\"";
  5084. }
  5085. body += "\r\n";
  5086. if (!item.content_type.empty()) {
  5087. body += "Content-Type: " + item.content_type + "\r\n";
  5088. }
  5089. body += "\r\n";
  5090. body += item.content + "\r\n";
  5091. }
  5092. body += "--" + boundary + "--\r\n";
  5093. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5094. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5095. ASSERT_TRUE(res);
  5096. EXPECT_EQ(StatusCode::OK_200, res->status);
  5097. }
  5098. TEST_F(ServerTest, PostContentReceiverGzip) {
  5099. cli_.set_compress(true);
  5100. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5101. ASSERT_TRUE(res);
  5102. ASSERT_EQ(StatusCode::OK_200, res->status);
  5103. ASSERT_EQ("content", res->body);
  5104. }
  5105. TEST_F(ServerTest, PutContentReceiver) {
  5106. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5107. ASSERT_TRUE(res);
  5108. ASSERT_EQ(StatusCode::OK_200, res->status);
  5109. ASSERT_EQ("content", res->body);
  5110. }
  5111. TEST_F(ServerTest, PatchContentReceiver) {
  5112. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5113. ASSERT_TRUE(res);
  5114. ASSERT_EQ(StatusCode::OK_200, res->status);
  5115. ASSERT_EQ("content", res->body);
  5116. }
  5117. template <typename ClientType>
  5118. void TestWithHeadersAndContentReceiver(
  5119. ClientType &cli,
  5120. std::function<Result(ClientType &, const std::string &, const Headers &,
  5121. const std::string &, const std::string &,
  5122. ContentReceiver, DownloadProgress)>
  5123. request_func) {
  5124. Headers headers;
  5125. headers.emplace("X-Custom-Header", "test-value");
  5126. std::string received_body;
  5127. auto res = request_func(
  5128. cli, "/content_receiver", headers, "content", "application/json",
  5129. [&](const char *data, size_t data_length) {
  5130. received_body.append(data, data_length);
  5131. return true;
  5132. },
  5133. nullptr);
  5134. ASSERT_TRUE(res);
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. EXPECT_EQ("content", received_body);
  5137. }
  5138. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5139. #ifdef CPPHTTPLIB_SSL_ENABLED
  5140. using ClientT = SSLClient;
  5141. #else
  5142. using ClientT = Client;
  5143. #endif
  5144. TestWithHeadersAndContentReceiver<ClientT>(
  5145. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5146. const std::string &body, const std::string &content_type,
  5147. ContentReceiver receiver, DownloadProgress progress) {
  5148. return cli.Post(path, headers, body, content_type, receiver, progress);
  5149. });
  5150. }
  5151. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5152. #ifdef CPPHTTPLIB_SSL_ENABLED
  5153. using ClientT = SSLClient;
  5154. #else
  5155. using ClientT = Client;
  5156. #endif
  5157. TestWithHeadersAndContentReceiver<ClientT>(
  5158. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5159. const std::string &body, const std::string &content_type,
  5160. ContentReceiver receiver, DownloadProgress progress) {
  5161. return cli.Put(path, headers, body, content_type, receiver, progress);
  5162. });
  5163. }
  5164. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5165. #ifdef CPPHTTPLIB_SSL_ENABLED
  5166. using ClientT = SSLClient;
  5167. #else
  5168. using ClientT = Client;
  5169. #endif
  5170. TestWithHeadersAndContentReceiver<ClientT>(
  5171. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5172. const std::string &body, const std::string &content_type,
  5173. ContentReceiver receiver, DownloadProgress progress) {
  5174. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5175. });
  5176. }
  5177. template <typename ClientType>
  5178. void TestWithHeadersAndContentReceiverWithProgress(
  5179. ClientType &cli,
  5180. std::function<Result(ClientType &, const std::string &, const Headers &,
  5181. const std::string &, const std::string &,
  5182. ContentReceiver, DownloadProgress)>
  5183. request_func) {
  5184. Headers headers;
  5185. headers.emplace("X-Test-Header", "progress-test");
  5186. std::string received_body;
  5187. auto progress_called = false;
  5188. auto res = request_func(
  5189. cli, "/content_receiver", headers, "content", "text/plain",
  5190. [&](const char *data, size_t data_length) {
  5191. received_body.append(data, data_length);
  5192. return true;
  5193. },
  5194. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5195. progress_called = true;
  5196. return true;
  5197. });
  5198. ASSERT_TRUE(res);
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. EXPECT_EQ("content", received_body);
  5201. EXPECT_TRUE(progress_called);
  5202. }
  5203. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5204. #ifdef CPPHTTPLIB_SSL_ENABLED
  5205. using ClientT = SSLClient;
  5206. #else
  5207. using ClientT = Client;
  5208. #endif
  5209. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5210. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5211. const std::string &body, const std::string &content_type,
  5212. ContentReceiver receiver, DownloadProgress progress) {
  5213. return cli.Post(path, headers, body, content_type, receiver, progress);
  5214. });
  5215. }
  5216. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5217. #ifdef CPPHTTPLIB_SSL_ENABLED
  5218. using ClientT = SSLClient;
  5219. #else
  5220. using ClientT = Client;
  5221. #endif
  5222. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5223. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5224. const std::string &body, const std::string &content_type,
  5225. ContentReceiver receiver, DownloadProgress progress) {
  5226. return cli.Put(path, headers, body, content_type, receiver, progress);
  5227. });
  5228. }
  5229. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5230. #ifdef CPPHTTPLIB_SSL_ENABLED
  5231. using ClientT = SSLClient;
  5232. #else
  5233. using ClientT = Client;
  5234. #endif
  5235. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5236. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5237. const std::string &body, const std::string &content_type,
  5238. ContentReceiver receiver, DownloadProgress progress) {
  5239. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5240. });
  5241. }
  5242. template <typename ClientType>
  5243. void TestWithHeadersAndContentReceiverError(
  5244. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5245. const Headers &, const std::string &,
  5246. const std::string &, ContentReceiver)>
  5247. request_func) {
  5248. Headers headers;
  5249. headers.emplace("X-Error-Test", "true");
  5250. std::string received_body;
  5251. auto receiver_failed = false;
  5252. auto res =
  5253. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5254. [&](const char *data, size_t data_length) {
  5255. received_body.append(data, data_length);
  5256. receiver_failed = true;
  5257. return false;
  5258. });
  5259. ASSERT_FALSE(res);
  5260. EXPECT_TRUE(receiver_failed);
  5261. }
  5262. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5263. #ifdef CPPHTTPLIB_SSL_ENABLED
  5264. using ClientT = SSLClient;
  5265. #else
  5266. using ClientT = Client;
  5267. #endif
  5268. TestWithHeadersAndContentReceiverError<ClientT>(
  5269. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5270. const std::string &body, const std::string &content_type,
  5271. ContentReceiver receiver) {
  5272. return cli.Post(path, headers, body, content_type, receiver);
  5273. });
  5274. }
  5275. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5276. #ifdef CPPHTTPLIB_SSL_ENABLED
  5277. using ClientT = SSLClient;
  5278. #else
  5279. using ClientT = Client;
  5280. #endif
  5281. TestWithHeadersAndContentReceiverError<ClientT>(
  5282. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5283. const std::string &body, const std::string &content_type,
  5284. ContentReceiver receiver) {
  5285. return cli.Put(path, headers, body, content_type, receiver);
  5286. });
  5287. }
  5288. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5289. #ifdef CPPHTTPLIB_SSL_ENABLED
  5290. using ClientT = SSLClient;
  5291. #else
  5292. using ClientT = Client;
  5293. #endif
  5294. TestWithHeadersAndContentReceiverError<ClientT>(
  5295. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5296. const std::string &body, const std::string &content_type,
  5297. ContentReceiver receiver) {
  5298. return cli.Patch(path, headers, body, content_type, receiver);
  5299. });
  5300. }
  5301. TEST_F(ServerTest, PostQueryStringAndBody) {
  5302. auto res =
  5303. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5304. ASSERT_TRUE(res);
  5305. ASSERT_EQ(StatusCode::OK_200, res->status);
  5306. }
  5307. TEST_F(ServerTest, HTTP2Magic) {
  5308. Request req;
  5309. req.method = "PRI";
  5310. req.path = "*";
  5311. req.body = "SM";
  5312. auto res = std::make_shared<Response>();
  5313. auto error = Error::Success;
  5314. auto ret = cli_.send(req, *res, error);
  5315. ASSERT_TRUE(ret);
  5316. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5317. }
  5318. TEST_F(ServerTest, KeepAlive) {
  5319. auto res = cli_.Get("/hi");
  5320. ASSERT_TRUE(res);
  5321. EXPECT_EQ(StatusCode::OK_200, res->status);
  5322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5323. EXPECT_EQ("Hello World!", res->body);
  5324. res = cli_.Get("/hi");
  5325. ASSERT_TRUE(res);
  5326. EXPECT_EQ(StatusCode::OK_200, res->status);
  5327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5328. EXPECT_EQ("Hello World!", res->body);
  5329. res = cli_.Get("/hi");
  5330. ASSERT_TRUE(res);
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. EXPECT_EQ("Hello World!", res->body);
  5334. res = cli_.Get("/not-exist");
  5335. ASSERT_TRUE(res);
  5336. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5337. res = cli_.Post("/empty", "", "text/plain");
  5338. ASSERT_TRUE(res);
  5339. EXPECT_EQ(StatusCode::OK_200, res->status);
  5340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5341. EXPECT_EQ("empty", res->body);
  5342. EXPECT_EQ("close", res->get_header_value("Connection"));
  5343. res = cli_.Post(
  5344. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5345. "text/plain");
  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("empty", res->body);
  5350. cli_.set_keep_alive(false);
  5351. res = cli_.Get("/last-request");
  5352. ASSERT_TRUE(res);
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. EXPECT_EQ("close", res->get_header_value("Connection"));
  5355. }
  5356. TEST_F(ServerTest, TooManyRedirect) {
  5357. cli_.set_follow_location(true);
  5358. auto res = cli_.Get("/redirect/0");
  5359. ASSERT_TRUE(!res);
  5360. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5361. }
  5362. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5363. Request req;
  5364. req.method = "FOOBAR";
  5365. req.path = "/hi";
  5366. cli_.set_keep_alive(true);
  5367. auto res = cli_.send(req);
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5370. EXPECT_EQ("close", res->get_header_value("Connection"));
  5371. EXPECT_FALSE(cli_.is_socket_open());
  5372. }
  5373. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5374. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5375. TEST_F(ServerTest, Gzip) {
  5376. Headers headers;
  5377. headers.emplace("Accept-Encoding", "gzip, deflate");
  5378. auto res = cli_.Get("/compress", headers);
  5379. ASSERT_TRUE(res);
  5380. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5381. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5382. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5383. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5384. "7890123456789012345678901234567890",
  5385. res->body);
  5386. EXPECT_EQ(StatusCode::OK_200, res->status);
  5387. }
  5388. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5389. Headers headers;
  5390. headers.emplace("Accept-Encoding", "gzip, deflate");
  5391. auto res = cli_.Get("/compress-with-charset", headers);
  5392. ASSERT_TRUE(res);
  5393. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5394. EXPECT_EQ("application/json; charset=utf-8",
  5395. res->get_header_value("Content-Type"));
  5396. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5397. "7890123456789012345678901234567890",
  5398. res->body);
  5399. EXPECT_EQ(StatusCode::OK_200, res->status);
  5400. }
  5401. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5402. Headers headers;
  5403. headers.emplace("Accept-Encoding", "");
  5404. auto res = cli_.Get("/compress", headers);
  5405. ASSERT_TRUE(res);
  5406. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5408. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5410. "7890123456789012345678901234567890",
  5411. res->body);
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. }
  5414. TEST_F(ServerTest, GzipWithContentReceiver) {
  5415. Headers headers;
  5416. headers.emplace("Accept-Encoding", "gzip, deflate");
  5417. std::string body;
  5418. auto res = cli_.Get("/compress", headers,
  5419. [&](const char *data, uint64_t data_length) {
  5420. EXPECT_EQ(100U, data_length);
  5421. body.append(data, data_length);
  5422. return true;
  5423. });
  5424. ASSERT_TRUE(res);
  5425. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5426. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5427. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5428. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5429. "7890123456789012345678901234567890",
  5430. body);
  5431. EXPECT_EQ(StatusCode::OK_200, res->status);
  5432. }
  5433. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5434. Headers headers;
  5435. headers.emplace("Accept-Encoding", "gzip, deflate");
  5436. cli_.set_decompress(false);
  5437. auto res = cli_.Get("/compress", headers);
  5438. ASSERT_TRUE(res);
  5439. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5440. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5441. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5442. EXPECT_EQ(33U, res->body.size());
  5443. EXPECT_EQ(StatusCode::OK_200, res->status);
  5444. }
  5445. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5446. Headers headers;
  5447. headers.emplace("Accept-Encoding", "");
  5448. std::string body;
  5449. auto res = cli_.Get("/compress", headers,
  5450. [&](const char *data, uint64_t data_length) {
  5451. EXPECT_EQ(100U, data_length);
  5452. body.append(data, data_length);
  5453. return true;
  5454. });
  5455. ASSERT_TRUE(res);
  5456. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5457. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5458. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5459. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5460. "7890123456789012345678901234567890",
  5461. body);
  5462. EXPECT_EQ(StatusCode::OK_200, res->status);
  5463. }
  5464. TEST_F(ServerTest, NoGzip) {
  5465. Headers headers;
  5466. headers.emplace("Accept-Encoding", "gzip, deflate");
  5467. auto res = cli_.Get("/nocompress", headers);
  5468. ASSERT_TRUE(res);
  5469. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5470. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5471. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5472. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5473. "7890123456789012345678901234567890",
  5474. res->body);
  5475. EXPECT_EQ(StatusCode::OK_200, res->status);
  5476. }
  5477. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5478. Headers headers;
  5479. headers.emplace("Accept-Encoding", "gzip, deflate");
  5480. std::string body;
  5481. auto res = cli_.Get("/nocompress", headers,
  5482. [&](const char *data, uint64_t data_length) {
  5483. EXPECT_EQ(100U, data_length);
  5484. body.append(data, data_length);
  5485. return true;
  5486. });
  5487. ASSERT_TRUE(res);
  5488. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5489. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5490. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5491. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5492. "7890123456789012345678901234567890",
  5493. body);
  5494. EXPECT_EQ(StatusCode::OK_200, res->status);
  5495. }
  5496. TEST_F(ServerTest, MultipartFormDataGzip) {
  5497. UploadFormDataItems items = {
  5498. {"key1", "test", "", ""},
  5499. {"key2", "--abcdefg123", "", ""},
  5500. };
  5501. cli_.set_compress(true);
  5502. auto res = cli_.Post("/compress-multipart", items);
  5503. ASSERT_TRUE(res);
  5504. EXPECT_EQ(StatusCode::OK_200, res->status);
  5505. }
  5506. #endif
  5507. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5508. TEST_F(ServerTest, Brotli) {
  5509. Headers headers;
  5510. headers.emplace("Accept-Encoding", "br");
  5511. auto res = cli_.Get("/compress", headers);
  5512. ASSERT_TRUE(res);
  5513. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5516. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5517. "7890123456789012345678901234567890",
  5518. res->body);
  5519. EXPECT_EQ(StatusCode::OK_200, res->status);
  5520. }
  5521. #endif
  5522. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5523. TEST_F(ServerTest, Zstd) {
  5524. Headers headers;
  5525. headers.emplace("Accept-Encoding", "zstd");
  5526. auto res = cli_.Get("/compress", headers);
  5527. ASSERT_TRUE(res);
  5528. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5529. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5530. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5531. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5532. "7890123456789012345678901234567890",
  5533. res->body);
  5534. EXPECT_EQ(StatusCode::OK_200, res->status);
  5535. }
  5536. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5537. Headers headers;
  5538. headers.emplace("Accept-Encoding", "");
  5539. auto res = cli_.Get("/compress", headers);
  5540. ASSERT_TRUE(res);
  5541. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5543. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5545. "7890123456789012345678901234567890",
  5546. res->body);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. }
  5549. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5550. Headers headers;
  5551. headers.emplace("Accept-Encoding", "zstd");
  5552. std::string body;
  5553. auto res = cli_.Get("/compress", headers,
  5554. [&](const char *data, uint64_t data_length) {
  5555. EXPECT_EQ(100U, data_length);
  5556. body.append(data, data_length);
  5557. return true;
  5558. });
  5559. ASSERT_TRUE(res);
  5560. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5561. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5562. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5563. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5564. "7890123456789012345678901234567890",
  5565. body);
  5566. EXPECT_EQ(StatusCode::OK_200, res->status);
  5567. }
  5568. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5569. Headers headers;
  5570. headers.emplace("Accept-Encoding", "zstd");
  5571. cli_.set_decompress(false);
  5572. auto res = cli_.Get("/compress", headers);
  5573. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5574. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5575. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5576. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5577. ASSERT_TRUE(res);
  5578. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5580. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5581. EXPECT_EQ(StatusCode::OK_200, res->status);
  5582. ASSERT_EQ(26U, res->body.size());
  5583. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5584. 0);
  5585. }
  5586. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5587. Headers headers;
  5588. headers.emplace("Accept-Encoding", "");
  5589. std::string body;
  5590. auto res = cli_.Get("/compress", headers,
  5591. [&](const char *data, uint64_t data_length) {
  5592. EXPECT_EQ(100U, data_length);
  5593. body.append(data, data_length);
  5594. return true;
  5595. });
  5596. ASSERT_TRUE(res);
  5597. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5598. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5599. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5600. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5601. "7890123456789012345678901234567890",
  5602. body);
  5603. EXPECT_EQ(StatusCode::OK_200, res->status);
  5604. }
  5605. TEST_F(ServerTest, NoZstd) {
  5606. Headers headers;
  5607. headers.emplace("Accept-Encoding", "zstd");
  5608. auto res = cli_.Get("/nocompress", headers);
  5609. ASSERT_TRUE(res);
  5610. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5611. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5612. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5613. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5614. "7890123456789012345678901234567890",
  5615. res->body);
  5616. EXPECT_EQ(StatusCode::OK_200, res->status);
  5617. }
  5618. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5619. Headers headers;
  5620. headers.emplace("Accept-Encoding", "zstd");
  5621. std::string body;
  5622. auto res = cli_.Get("/nocompress", headers,
  5623. [&](const char *data, uint64_t data_length) {
  5624. EXPECT_EQ(100U, data_length);
  5625. body.append(data, data_length);
  5626. return true;
  5627. });
  5628. ASSERT_TRUE(res);
  5629. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5630. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5631. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5632. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5633. "7890123456789012345678901234567890",
  5634. body);
  5635. EXPECT_EQ(StatusCode::OK_200, res->status);
  5636. }
  5637. // TODO: How to enable zstd ??
  5638. TEST_F(ServerTest, MultipartFormDataZstd) {
  5639. UploadFormDataItems items = {
  5640. {"key1", "test", "", ""},
  5641. {"key2", "--abcdefg123", "", ""},
  5642. };
  5643. Headers headers;
  5644. headers.emplace("Accept-Encoding", "zstd");
  5645. cli_.set_compress(true);
  5646. auto res = cli_.Post("/compress-multipart", headers, items);
  5647. ASSERT_TRUE(res);
  5648. EXPECT_EQ(StatusCode::OK_200, res->status);
  5649. }
  5650. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5651. Headers headers;
  5652. headers.emplace("Accept-Encoding", "zstd");
  5653. cli_.set_compress(true);
  5654. auto res = cli_.Put(
  5655. "/put", headers, 3,
  5656. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5657. sink.os << "PUT";
  5658. return true;
  5659. },
  5660. "text/plain");
  5661. ASSERT_TRUE(res);
  5662. EXPECT_EQ(StatusCode::OK_200, res->status);
  5663. EXPECT_EQ("PUT", res->body);
  5664. }
  5665. // Pre-compression logging tests
  5666. TEST_F(ServerTest, PreCompressionLogging) {
  5667. // Test data for compression (matches the actual /compress endpoint content)
  5668. const std::string test_content =
  5669. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5670. "3456789012345678901234567890";
  5671. // Variables to capture logging data
  5672. std::string pre_compression_body;
  5673. std::string pre_compression_content_type;
  5674. std::string pre_compression_content_encoding;
  5675. std::string post_compression_body;
  5676. std::string post_compression_content_type;
  5677. std::string post_compression_content_encoding;
  5678. // Set up pre-compression logger
  5679. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5680. const Response &res) {
  5681. pre_compression_body = res.body;
  5682. pre_compression_content_type = res.get_header_value("Content-Type");
  5683. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5684. });
  5685. // Set up post-compression logger
  5686. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5687. post_compression_body = res.body;
  5688. post_compression_content_type = res.get_header_value("Content-Type");
  5689. post_compression_content_encoding =
  5690. res.get_header_value("Content-Encoding");
  5691. });
  5692. // Test with gzip compression
  5693. Headers headers;
  5694. headers.emplace("Accept-Encoding", "gzip");
  5695. auto res = cli_.Get("/compress", headers);
  5696. // Verify response was compressed
  5697. ASSERT_TRUE(res);
  5698. EXPECT_EQ(StatusCode::OK_200, res->status);
  5699. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5700. // Verify pre-compression logger captured uncompressed content
  5701. EXPECT_EQ(test_content, pre_compression_body);
  5702. EXPECT_EQ("text/plain", pre_compression_content_type);
  5703. EXPECT_TRUE(pre_compression_content_encoding
  5704. .empty()); // No encoding header before compression
  5705. // Verify post-compression logger captured compressed content
  5706. EXPECT_NE(test_content,
  5707. post_compression_body); // Should be different after compression
  5708. EXPECT_EQ("text/plain", post_compression_content_type);
  5709. EXPECT_EQ("gzip", post_compression_content_encoding);
  5710. // Verify compressed content is smaller
  5711. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5712. }
  5713. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5714. const std::string test_content =
  5715. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5716. "3456789012345678901234567890";
  5717. std::string pre_compression_body;
  5718. std::string post_compression_body;
  5719. svr_.set_pre_compression_logger(
  5720. [&](const Request & /*req*/, const Response &res) {
  5721. pre_compression_body = res.body;
  5722. });
  5723. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5724. post_compression_body = res.body;
  5725. });
  5726. Headers headers;
  5727. headers.emplace("Accept-Encoding", "br");
  5728. auto res = cli_.Get("/compress", headers);
  5729. ASSERT_TRUE(res);
  5730. EXPECT_EQ(StatusCode::OK_200, res->status);
  5731. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5732. // Verify pre-compression content is uncompressed
  5733. EXPECT_EQ(test_content, pre_compression_body);
  5734. // Verify post-compression content is compressed
  5735. EXPECT_NE(test_content, post_compression_body);
  5736. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5737. }
  5738. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5739. const std::string test_content =
  5740. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5741. "3456789012345678901234567890";
  5742. std::string pre_compression_body;
  5743. std::string post_compression_body;
  5744. svr_.set_pre_compression_logger(
  5745. [&](const Request & /*req*/, const Response &res) {
  5746. pre_compression_body = res.body;
  5747. });
  5748. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5749. post_compression_body = res.body;
  5750. });
  5751. // Request without compression (use /nocompress endpoint)
  5752. Headers headers;
  5753. auto res = cli_.Get("/nocompress", headers);
  5754. ASSERT_TRUE(res);
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5757. // Pre-compression logger should not be called when no compression is applied
  5758. EXPECT_TRUE(
  5759. pre_compression_body.empty()); // Pre-compression logger not called
  5760. EXPECT_EQ(
  5761. test_content,
  5762. post_compression_body); // Post-compression logger captures final content
  5763. }
  5764. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5765. const std::string test_content =
  5766. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5767. "3456789012345678901234567890";
  5768. std::string pre_compression_body;
  5769. bool pre_logger_called = false;
  5770. // Set only pre-compression logger
  5771. svr_.set_pre_compression_logger(
  5772. [&](const Request & /*req*/, const Response &res) {
  5773. pre_compression_body = res.body;
  5774. pre_logger_called = true;
  5775. });
  5776. Headers headers;
  5777. headers.emplace("Accept-Encoding", "gzip");
  5778. auto res = cli_.Get("/compress", headers);
  5779. ASSERT_TRUE(res);
  5780. EXPECT_EQ(StatusCode::OK_200, res->status);
  5781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5782. // Verify pre-compression logger was called
  5783. EXPECT_TRUE(pre_logger_called);
  5784. EXPECT_EQ(test_content, pre_compression_body);
  5785. }
  5786. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5787. {
  5788. // Test with Expect: 100-continue header - success case
  5789. // Server returns 100 Continue, client sends body, server returns 200 OK
  5790. Request req;
  5791. req.method = "POST";
  5792. req.path = "/post-large";
  5793. req.set_header("Expect", "100-continue");
  5794. req.body = LARGE_DATA;
  5795. Response res;
  5796. auto error = Error::Success;
  5797. cli_.set_keep_alive(true);
  5798. auto ret = cli_.send(req, res, error);
  5799. EXPECT_TRUE(ret);
  5800. EXPECT_EQ(StatusCode::OK_200, res.status);
  5801. EXPECT_EQ(LARGE_DATA, res.body);
  5802. }
  5803. {
  5804. // Test with Expect: 100-continue header - error case
  5805. // Client should not send the body when server returns an error
  5806. Request req;
  5807. req.method = "POST";
  5808. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5809. req.set_header("Expect", "100-continue");
  5810. req.body = LARGE_DATA;
  5811. Response res;
  5812. auto error = Error::Success;
  5813. auto start = std::chrono::high_resolution_clock::now();
  5814. cli_.set_keep_alive(true);
  5815. auto ret = cli_.send(req, res, error);
  5816. auto end = std::chrono::high_resolution_clock::now();
  5817. auto elapsed =
  5818. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5819. .count();
  5820. // With Expect: 100-continue, request completes successfully but with error
  5821. EXPECT_TRUE(ret);
  5822. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5823. EXPECT_EQ("close", res.get_header_value("Connection"));
  5824. EXPECT_FALSE(cli_.is_socket_open());
  5825. EXPECT_LE(elapsed, 200);
  5826. }
  5827. {
  5828. // Send an extra GET request to ensure error recovery without hanging
  5829. Request req;
  5830. req.method = "GET";
  5831. req.path = "/hi";
  5832. auto start = std::chrono::high_resolution_clock::now();
  5833. auto res = cli_.send(req);
  5834. auto end = std::chrono::high_resolution_clock::now();
  5835. auto elapsed =
  5836. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5837. .count();
  5838. ASSERT_TRUE(res);
  5839. EXPECT_EQ(StatusCode::OK_200, res->status);
  5840. EXPECT_EQ("Hello World!", res->body);
  5841. EXPECT_LE(elapsed, 500);
  5842. }
  5843. }
  5844. TEST(ZstdDecompressor, ChunkedDecompression) {
  5845. std::string data;
  5846. for (size_t i = 0; i < 32 * 1024; ++i) {
  5847. data.push_back(static_cast<char>('a' + i % 26));
  5848. }
  5849. std::string compressed_data;
  5850. {
  5851. httplib::detail::zstd_compressor compressor;
  5852. bool result = compressor.compress(
  5853. data.data(), data.size(),
  5854. /*last=*/true,
  5855. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5856. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5857. compressed_data_size);
  5858. return true;
  5859. });
  5860. ASSERT_TRUE(result);
  5861. }
  5862. std::string decompressed_data;
  5863. {
  5864. httplib::detail::zstd_decompressor decompressor;
  5865. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5866. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5867. size_t chunk_size = 130;
  5868. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5869. chunk_begin += chunk_size) {
  5870. size_t current_chunk_size =
  5871. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5872. bool result = decompressor.decompress(
  5873. compressed_data.data() + chunk_begin, current_chunk_size,
  5874. [&](const char *decompressed_data_chunk,
  5875. size_t decompressed_data_chunk_size) {
  5876. decompressed_data.insert(decompressed_data.size(),
  5877. decompressed_data_chunk,
  5878. decompressed_data_chunk_size);
  5879. return true;
  5880. });
  5881. ASSERT_TRUE(result);
  5882. }
  5883. }
  5884. ASSERT_EQ(data, decompressed_data);
  5885. }
  5886. TEST(ZstdDecompressor, Decompress) {
  5887. std::string original_text = "Compressed with ZSTD";
  5888. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5889. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5890. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5891. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5892. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5893. std::string decompressed_data;
  5894. {
  5895. httplib::detail::zstd_decompressor decompressor;
  5896. bool result = decompressor.decompress(
  5897. compressed_data.data(), compressed_data.size(),
  5898. [&](const char *decompressed_data_chunk,
  5899. size_t decompressed_data_chunk_size) {
  5900. decompressed_data.insert(decompressed_data.size(),
  5901. decompressed_data_chunk,
  5902. decompressed_data_chunk_size);
  5903. return true;
  5904. });
  5905. ASSERT_TRUE(result);
  5906. }
  5907. ASSERT_EQ(original_text, decompressed_data);
  5908. }
  5909. #endif
  5910. // Sends a raw request to a server listening at HOST:PORT.
  5911. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5912. std::string *resp = nullptr) {
  5913. auto error = Error::Success;
  5914. auto client_sock = detail::create_client_socket(
  5915. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5916. /*connection_timeout_sec=*/5, 0,
  5917. /*read_timeout_sec=*/5, 0,
  5918. /*write_timeout_sec=*/5, 0, std::string(), error);
  5919. if (client_sock == INVALID_SOCKET) { return false; }
  5920. auto ret = detail::process_client_socket(
  5921. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5922. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5923. if (req.size() !=
  5924. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5925. return false;
  5926. }
  5927. char buf[512];
  5928. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5929. while (line_reader.getline()) {
  5930. if (resp) { *resp += line_reader.ptr(); }
  5931. }
  5932. return true;
  5933. });
  5934. detail::close_socket(client_sock);
  5935. return ret;
  5936. }
  5937. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5938. Server svr;
  5939. std::string header_value;
  5940. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5941. header_value = req.get_header_value("foo");
  5942. res.set_content("ok", "text/plain");
  5943. });
  5944. thread t = thread([&] { svr.listen(HOST, PORT); });
  5945. auto se = detail::scope_exit([&] {
  5946. svr.stop();
  5947. t.join();
  5948. ASSERT_FALSE(svr.is_running());
  5949. });
  5950. svr.wait_until_ready();
  5951. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5952. // like characters are not treated the same - use vertical tab and escape.
  5953. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5954. "foo: \t \v bar \x1B\t \r\n"
  5955. "Connection: close\r\n"
  5956. "\r\n";
  5957. std::string res;
  5958. ASSERT_TRUE(send_request(5, req, &res));
  5959. EXPECT_EQ(header_value, "");
  5960. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5961. }
  5962. // Sends a raw request and verifies that there isn't a crash or exception.
  5963. static void test_raw_request(const std::string &req,
  5964. std::string *out = nullptr) {
  5965. Server svr;
  5966. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5967. res.set_content("ok", "text/plain");
  5968. });
  5969. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5970. res.set_content("ok", "text/plain");
  5971. });
  5972. svr.Get("/header_field_value_check",
  5973. [&](const Request & /*req*/, Response &res) {
  5974. res.set_content("ok", "text/plain");
  5975. });
  5976. // Server read timeout must be longer than the client read timeout for the
  5977. // bug to reproduce, probably to force the server to process a request
  5978. // without a trailing blank line.
  5979. const time_t client_read_timeout_sec = 1;
  5980. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5981. bool listen_thread_ok = false;
  5982. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5983. auto se = detail::scope_exit([&] {
  5984. svr.stop();
  5985. t.join();
  5986. ASSERT_FALSE(svr.is_running());
  5987. EXPECT_TRUE(listen_thread_ok);
  5988. });
  5989. svr.wait_until_ready();
  5990. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5991. }
  5992. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5993. // A certain header line causes an exception if the header property is parsed
  5994. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5995. test_raw_request(
  5996. "GET /hi HTTP/1.1\r\n"
  5997. " : "
  5998. " "
  5999. " ");
  6000. }
  6001. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6002. // A certain header line causes an exception if the header property *name* is
  6003. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6004. // greedy matcher and requires backtracking when there are a lot of ":"
  6005. // characters.
  6006. // This occurs with libc++ but not libstdc++.
  6007. test_raw_request(
  6008. "GET /hi HTTP/1.1\r\n"
  6009. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6010. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6011. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6012. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6013. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6014. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6015. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6016. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6017. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6018. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6019. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6020. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6021. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6022. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6023. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6024. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6025. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6026. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6027. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6028. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6029. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6030. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6031. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6032. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6033. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6034. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6035. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6036. "&&&%%%");
  6037. }
  6038. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6039. // Make sure this doesn't crash the server.
  6040. // In a previous version of the header line regex, the "\r" rendered the line
  6041. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6042. // a new position where the leading white space ended and the field value
  6043. // began.
  6044. // The crash occurs with libc++ but not libstdc++.
  6045. test_raw_request("GET /hi HTTP/1.1\r\n"
  6046. "a:" +
  6047. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6048. "\r\n"
  6049. "\r\n");
  6050. }
  6051. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6052. std::string out;
  6053. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6054. "Content-Type: text/plain\r\n"
  6055. "Transfer-Encoding: chunked\r\n"
  6056. "\r\n"
  6057. "nothex\r\n",
  6058. &out);
  6059. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6060. }
  6061. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6062. std::string out;
  6063. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6064. "Content-Type: text/plain\r\n"
  6065. "Transfer-Encoding: chunked\r\n"
  6066. "\r\n"
  6067. "3\r\n"
  6068. "xyz\r\n"
  6069. "NaN\r\n",
  6070. &out);
  6071. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6072. }
  6073. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6074. std::string out;
  6075. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6076. "Content-Type: text/plain\r\n"
  6077. "Transfer-Encoding: chunked\r\n"
  6078. "\r\n"
  6079. // Length is too large for 64 bits.
  6080. "1ffffffffffffffff\r\n"
  6081. "xyz\r\n",
  6082. &out);
  6083. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6084. }
  6085. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6086. test_raw_request("GET /hi HTTP/1.1\r\n"
  6087. "Content-Type: text/plain\r\n\r");
  6088. }
  6089. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6090. std::string out;
  6091. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6092. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6093. }
  6094. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6095. Server svr;
  6096. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6097. EXPECT_TRUE(!req.remote_addr.empty());
  6098. });
  6099. thread t = thread([&] { svr.listen(HOST, PORT); });
  6100. auto se = detail::scope_exit([&] {
  6101. svr.stop();
  6102. t.join();
  6103. ASSERT_FALSE(svr.is_running());
  6104. });
  6105. svr.wait_until_ready();
  6106. // Send an invalid request line to trigger Bad Request
  6107. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6108. std::string out;
  6109. ASSERT_TRUE(send_request(5, bad_req, &out));
  6110. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6111. }
  6112. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6113. std::string out;
  6114. std::string request(
  6115. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6116. test_raw_request(request, &out);
  6117. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6118. }
  6119. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6120. std::string out;
  6121. std::string request(
  6122. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6123. test_raw_request(request, &out);
  6124. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6125. }
  6126. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6127. std::string out;
  6128. std::string request(
  6129. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6130. test_raw_request(request, &out);
  6131. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6132. }
  6133. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6134. std::string out;
  6135. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6136. "Test: \r\n\r\n",
  6137. &out);
  6138. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6139. }
  6140. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6141. Server svr;
  6142. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6143. res.set_header("Cache-Control", "no-cache");
  6144. res.set_chunked_content_provider(
  6145. "text/event-stream", [](size_t offset, DataSink &sink) {
  6146. std::string s = "data:";
  6147. s += std::to_string(offset);
  6148. s += "\n\n";
  6149. auto ret = sink.write(s.data(), s.size());
  6150. EXPECT_TRUE(ret);
  6151. std::this_thread::sleep_for(std::chrono::seconds(1));
  6152. return true;
  6153. });
  6154. });
  6155. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6156. svr.wait_until_ready();
  6157. Client client(HOST, PORT);
  6158. const Headers headers = {{"Accept", "text/event-stream"}};
  6159. auto get_thread = std::thread([&client, &headers]() {
  6160. auto res = client.Get(
  6161. "/events", headers,
  6162. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6163. });
  6164. auto se = detail::scope_exit([&] {
  6165. svr.stop();
  6166. get_thread.join();
  6167. listen_thread.join();
  6168. ASSERT_FALSE(svr.is_running());
  6169. });
  6170. // Give GET time to get a few messages.
  6171. std::this_thread::sleep_for(std::chrono::seconds(2));
  6172. }
  6173. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6174. httplib::Server svr;
  6175. svr.Post("/hi",
  6176. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6177. res.status = StatusCode::OK_200;
  6178. });
  6179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6180. svr.wait_until_ready();
  6181. Client cli(HOST, PORT);
  6182. auto res = cli.Post("/hi", "data", "text/plain");
  6183. ASSERT_TRUE(res);
  6184. EXPECT_EQ(StatusCode::OK_200, res->status);
  6185. svr.stop();
  6186. thread.join();
  6187. ASSERT_FALSE(svr.is_running());
  6188. res = cli.Post("/hi", "data", "text/plain");
  6189. ASSERT_FALSE(res);
  6190. }
  6191. TEST(ServerStopTest, ListenFailure) {
  6192. Server svr;
  6193. auto t = thread([&]() {
  6194. auto ret = svr.listen("????", PORT);
  6195. EXPECT_FALSE(ret);
  6196. });
  6197. svr.wait_until_ready();
  6198. svr.stop();
  6199. t.join();
  6200. }
  6201. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6202. TEST(ServerStopTest, Decommision) {
  6203. Server svr;
  6204. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6205. for (int i = 0; i < 4; i++) {
  6206. auto is_even = !(i % 2);
  6207. std::thread t{[&] {
  6208. try {
  6209. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6210. if (is_even) {
  6211. throw std::runtime_error("Some thing that happens to go wrong.");
  6212. }
  6213. svr.listen(HOST, PORT);
  6214. } catch (...) { svr.decommission(); }
  6215. }};
  6216. svr.wait_until_ready();
  6217. // Server is up
  6218. {
  6219. Client cli(HOST, PORT);
  6220. auto res = cli.Get("/hi");
  6221. if (is_even) {
  6222. EXPECT_FALSE(res);
  6223. } else {
  6224. EXPECT_TRUE(res);
  6225. EXPECT_EQ("hi...", res->body);
  6226. }
  6227. }
  6228. svr.stop();
  6229. t.join();
  6230. // Server is down...
  6231. {
  6232. Client cli(HOST, PORT);
  6233. auto res = cli.Get("/hi");
  6234. EXPECT_FALSE(res);
  6235. }
  6236. }
  6237. }
  6238. #endif
  6239. // Helper function for string body upload progress tests
  6240. template <typename SetupHandler, typename ClientCall>
  6241. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6242. ClientCall &&client_call,
  6243. const string &body) {
  6244. Server svr;
  6245. setup_handler(svr);
  6246. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6247. auto se = detail::scope_exit([&] {
  6248. svr.stop();
  6249. t.join();
  6250. });
  6251. svr.wait_until_ready();
  6252. Client cli(HOST, PORT);
  6253. vector<uint64_t> progress_values;
  6254. bool progress_called = false;
  6255. auto res =
  6256. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6257. progress_values.push_back(current);
  6258. progress_called = true;
  6259. return true;
  6260. });
  6261. ASSERT_TRUE(res);
  6262. EXPECT_EQ(200, res->status);
  6263. EXPECT_TRUE(progress_called);
  6264. }
  6265. TEST(UploadProgressTest, PostStringBodyBasic) {
  6266. TestStringBodyUploadProgress(
  6267. [](Server &svr) {
  6268. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6269. res.set_content("received", "text/plain");
  6270. });
  6271. },
  6272. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6273. return cli.Post("/test", body, "text/plain", progress_callback);
  6274. },
  6275. "test data for upload progress");
  6276. }
  6277. TEST(UploadProgressTest, PutStringBodyBasic) {
  6278. TestStringBodyUploadProgress(
  6279. [](Server &svr) {
  6280. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6281. res.set_content("put received", "text/plain");
  6282. });
  6283. },
  6284. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6285. return cli.Put("/test", body, "text/plain", progress_callback);
  6286. },
  6287. "put test data for upload progress");
  6288. }
  6289. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6290. TestStringBodyUploadProgress(
  6291. [](Server &svr) {
  6292. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6293. res.set_content("patch received", "text/plain");
  6294. });
  6295. },
  6296. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6297. return cli.Patch("/test", body, "text/plain", progress_callback);
  6298. },
  6299. "patch test data for upload progress");
  6300. }
  6301. // Helper function for content provider upload progress tests
  6302. template <typename SetupHandler, typename ClientCall>
  6303. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6304. ClientCall &&client_call) {
  6305. Server svr;
  6306. setup_handler(svr);
  6307. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6308. auto se = detail::scope_exit([&] {
  6309. svr.stop();
  6310. t.join();
  6311. });
  6312. svr.wait_until_ready();
  6313. Client cli(HOST, PORT);
  6314. vector<uint64_t> progress_values;
  6315. auto res =
  6316. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6317. progress_values.push_back(current);
  6318. return true;
  6319. });
  6320. ASSERT_TRUE(res);
  6321. EXPECT_EQ(200, res->status);
  6322. EXPECT_FALSE(progress_values.empty());
  6323. }
  6324. TEST(UploadProgressTest, PostContentProviderProgress) {
  6325. TestContentProviderUploadProgress(
  6326. [](Server &svr) {
  6327. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6328. res.set_content("provider received", "text/plain");
  6329. });
  6330. },
  6331. [](Client &cli, UploadProgress progress_callback) {
  6332. return cli.Post(
  6333. "/test", 10,
  6334. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6335. sink.os << "test data";
  6336. return true;
  6337. },
  6338. "text/plain", progress_callback);
  6339. });
  6340. }
  6341. // Helper function for multipart upload progress tests
  6342. template <typename SetupHandler, typename ClientCall>
  6343. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6344. ClientCall &&client_call,
  6345. const string &endpoint) {
  6346. Server svr;
  6347. setup_handler(svr);
  6348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6349. auto se = detail::scope_exit([&] {
  6350. svr.stop();
  6351. t.join();
  6352. });
  6353. svr.wait_until_ready();
  6354. Client cli(HOST, PORT);
  6355. vector<uint64_t> progress_values;
  6356. UploadFormDataItems items = {
  6357. {"field1", "value1", "", ""},
  6358. {"field2", "longer value for progress tracking test", "", ""},
  6359. {"file1", "file content data for upload progress", "test.txt",
  6360. "text/plain"}};
  6361. auto res = client_call(cli, endpoint, items,
  6362. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6363. progress_values.push_back(current);
  6364. return true;
  6365. });
  6366. ASSERT_TRUE(res);
  6367. EXPECT_EQ(200, res->status);
  6368. EXPECT_FALSE(progress_values.empty());
  6369. }
  6370. TEST(UploadProgressTest, PostMultipartProgress) {
  6371. TestMultipartUploadProgress(
  6372. [](Server &svr) {
  6373. svr.Post("/multipart", [](const Request &req, Response &res) {
  6374. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6375. res.set_content("multipart received", "text/plain");
  6376. });
  6377. },
  6378. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6379. UploadProgress progress_callback) {
  6380. return cli.Post(endpoint, items, progress_callback);
  6381. },
  6382. "/multipart");
  6383. }
  6384. // Helper function for basic download progress tests
  6385. template <typename SetupHandler, typename ClientCall>
  6386. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6387. ClientCall &&client_call, const string &endpoint,
  6388. size_t expected_content_size) {
  6389. Server svr;
  6390. setup_handler(svr);
  6391. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6392. auto se = detail::scope_exit([&] {
  6393. svr.stop();
  6394. t.join();
  6395. });
  6396. svr.wait_until_ready();
  6397. Client cli(HOST, PORT);
  6398. vector<uint64_t> progress_values;
  6399. auto res = client_call(cli, endpoint,
  6400. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6401. progress_values.push_back(current);
  6402. return true;
  6403. });
  6404. ASSERT_TRUE(res);
  6405. EXPECT_EQ(200, res->status);
  6406. EXPECT_FALSE(progress_values.empty());
  6407. EXPECT_EQ(expected_content_size, res->body.size());
  6408. }
  6409. TEST(DownloadProgressTest, GetBasic) {
  6410. TestBasicDownloadProgress(
  6411. [](Server &svr) {
  6412. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6413. string content(1000, 'D');
  6414. res.set_content(content, "text/plain");
  6415. });
  6416. },
  6417. [](Client &cli, const string &endpoint,
  6418. DownloadProgress progress_callback) {
  6419. return cli.Get(endpoint, progress_callback);
  6420. },
  6421. "/download", 1000u);
  6422. }
  6423. // Helper function for content receiver download progress tests
  6424. template <typename SetupHandler, typename ClientCall>
  6425. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6426. ClientCall &&client_call,
  6427. const string &endpoint,
  6428. size_t expected_content_size) {
  6429. Server svr;
  6430. setup_handler(svr);
  6431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6432. auto se = detail::scope_exit([&] {
  6433. svr.stop();
  6434. t.join();
  6435. });
  6436. svr.wait_until_ready();
  6437. Client cli(HOST, PORT);
  6438. vector<uint64_t> progress_values;
  6439. string received_body;
  6440. auto res = client_call(
  6441. cli, endpoint,
  6442. [&](const char *data, size_t data_length) -> bool {
  6443. received_body.append(data, data_length);
  6444. return true;
  6445. },
  6446. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6447. progress_values.push_back(current);
  6448. return true;
  6449. });
  6450. ASSERT_TRUE(res);
  6451. EXPECT_EQ(200, res->status);
  6452. EXPECT_FALSE(progress_values.empty());
  6453. EXPECT_EQ(expected_content_size, received_body.size());
  6454. EXPECT_TRUE(res->body.empty());
  6455. }
  6456. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6457. TestContentReceiverDownloadProgress(
  6458. [](Server &svr) {
  6459. svr.Get("/download-receiver",
  6460. [](const Request & /*req*/, Response &res) {
  6461. string content(2000, 'R');
  6462. res.set_content(content, "text/plain");
  6463. });
  6464. },
  6465. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6466. DownloadProgress progress_callback) {
  6467. return cli.Get(endpoint, content_receiver, progress_callback);
  6468. },
  6469. "/download-receiver", 2000u);
  6470. }
  6471. TEST(StreamingTest, NoContentLengthStreaming) {
  6472. Server svr;
  6473. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6474. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6475. if (offset < 6) {
  6476. sink.os << (offset < 3 ? "a" : "b");
  6477. } else {
  6478. sink.done();
  6479. }
  6480. return true;
  6481. });
  6482. });
  6483. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6484. auto listen_se = detail::scope_exit([&] {
  6485. svr.stop();
  6486. listen_thread.join();
  6487. ASSERT_FALSE(svr.is_running());
  6488. });
  6489. svr.wait_until_ready();
  6490. Client client(HOST, PORT);
  6491. auto get_thread = std::thread([&client]() {
  6492. std::string s;
  6493. auto res =
  6494. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6495. s += std::string(data, len);
  6496. return true;
  6497. });
  6498. ASSERT_TRUE(res);
  6499. EXPECT_EQ(StatusCode::OK_200, res->status);
  6500. EXPECT_EQ("aaabbb", s);
  6501. });
  6502. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6503. // Give GET time to get a few messages.
  6504. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6505. }
  6506. TEST(MountTest, Unmount) {
  6507. Server svr;
  6508. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6509. auto se = detail::scope_exit([&] {
  6510. svr.stop();
  6511. listen_thread.join();
  6512. ASSERT_FALSE(svr.is_running());
  6513. });
  6514. svr.wait_until_ready();
  6515. Client cli("localhost", PORT);
  6516. svr.set_mount_point("/mount2", "./www2");
  6517. auto res = cli.Get("/");
  6518. ASSERT_TRUE(res);
  6519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6520. res = cli.Get("/mount2/dir/test.html");
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::OK_200, res->status);
  6523. svr.set_mount_point("/", "./www");
  6524. res = cli.Get("/dir/");
  6525. ASSERT_TRUE(res);
  6526. EXPECT_EQ(StatusCode::OK_200, res->status);
  6527. svr.remove_mount_point("/");
  6528. res = cli.Get("/dir/");
  6529. ASSERT_TRUE(res);
  6530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6531. svr.remove_mount_point("/mount2");
  6532. res = cli.Get("/mount2/dir/test.html");
  6533. ASSERT_TRUE(res);
  6534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6535. }
  6536. TEST(MountTest, Redicect) {
  6537. Server svr;
  6538. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6539. auto se = detail::scope_exit([&] {
  6540. svr.stop();
  6541. listen_thread.join();
  6542. ASSERT_FALSE(svr.is_running());
  6543. });
  6544. svr.set_mount_point("/", "./www");
  6545. svr.wait_until_ready();
  6546. Client cli("localhost", PORT);
  6547. auto res = cli.Get("/dir/");
  6548. ASSERT_TRUE(res);
  6549. EXPECT_EQ(StatusCode::OK_200, res->status);
  6550. res = cli.Get("/dir");
  6551. ASSERT_TRUE(res);
  6552. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6553. res = cli.Get("/file");
  6554. ASSERT_TRUE(res);
  6555. EXPECT_EQ(StatusCode::OK_200, res->status);
  6556. res = cli.Get("/file/");
  6557. ASSERT_TRUE(res);
  6558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6559. cli.set_follow_location(true);
  6560. res = cli.Get("/dir");
  6561. ASSERT_TRUE(res);
  6562. EXPECT_EQ(StatusCode::OK_200, res->status);
  6563. }
  6564. TEST(MountTest, MultibytesPathName) {
  6565. Server svr;
  6566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6567. auto se = detail::scope_exit([&] {
  6568. svr.stop();
  6569. listen_thread.join();
  6570. ASSERT_FALSE(svr.is_running());
  6571. });
  6572. svr.set_mount_point("/", "./www");
  6573. svr.wait_until_ready();
  6574. Client cli("localhost", PORT);
  6575. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6576. ASSERT_TRUE(res);
  6577. EXPECT_EQ(StatusCode::OK_200, res->status);
  6578. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6579. }
  6580. TEST(KeepAliveTest, ReadTimeout) {
  6581. Server svr;
  6582. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6583. std::this_thread::sleep_for(std::chrono::seconds(2));
  6584. res.set_content("a", "text/plain");
  6585. });
  6586. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6587. res.set_content("b", "text/plain");
  6588. });
  6589. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6590. auto se = detail::scope_exit([&] {
  6591. svr.stop();
  6592. listen_thread.join();
  6593. ASSERT_FALSE(svr.is_running());
  6594. });
  6595. svr.wait_until_ready();
  6596. Client cli("localhost", PORT);
  6597. cli.set_keep_alive(true);
  6598. cli.set_read_timeout(std::chrono::seconds(1));
  6599. auto resa = cli.Get("/a");
  6600. ASSERT_FALSE(resa);
  6601. EXPECT_EQ(Error::Read, resa.error());
  6602. auto resb = cli.Get("/b");
  6603. ASSERT_TRUE(resb);
  6604. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6605. EXPECT_EQ("b", resb->body);
  6606. }
  6607. TEST(KeepAliveTest, MaxCount) {
  6608. size_t keep_alive_max_count = 3;
  6609. Server svr;
  6610. svr.set_keep_alive_max_count(keep_alive_max_count);
  6611. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6612. res.set_content("Hello World!", "text/plain");
  6613. });
  6614. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6615. auto se = detail::scope_exit([&] {
  6616. svr.stop();
  6617. listen_thread.join();
  6618. ASSERT_FALSE(svr.is_running());
  6619. });
  6620. svr.wait_until_ready();
  6621. Client cli(HOST, PORT);
  6622. cli.set_keep_alive(true);
  6623. for (size_t i = 0; i < 5; i++) {
  6624. auto result = cli.Get("/hi");
  6625. ASSERT_TRUE(result);
  6626. EXPECT_EQ(StatusCode::OK_200, result->status);
  6627. if (i == keep_alive_max_count - 1) {
  6628. EXPECT_EQ("close", result->get_header_value("Connection"));
  6629. } else {
  6630. EXPECT_FALSE(result->has_header("Connection"));
  6631. }
  6632. }
  6633. }
  6634. TEST(KeepAliveTest, Issue1041) {
  6635. Server svr;
  6636. svr.set_keep_alive_timeout(3);
  6637. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6638. res.set_content("Hello World!", "text/plain");
  6639. });
  6640. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6641. auto se = detail::scope_exit([&] {
  6642. svr.stop();
  6643. listen_thread.join();
  6644. ASSERT_FALSE(svr.is_running());
  6645. });
  6646. svr.wait_until_ready();
  6647. Client cli(HOST, PORT);
  6648. cli.set_keep_alive(true);
  6649. auto result = cli.Get("/hi");
  6650. ASSERT_TRUE(result);
  6651. EXPECT_EQ(StatusCode::OK_200, result->status);
  6652. std::this_thread::sleep_for(std::chrono::seconds(5));
  6653. result = cli.Get("/hi");
  6654. ASSERT_TRUE(result);
  6655. EXPECT_EQ(StatusCode::OK_200, result->status);
  6656. }
  6657. TEST(KeepAliveTest, Issue1959) {
  6658. Server svr;
  6659. svr.set_keep_alive_timeout(5);
  6660. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6661. res.set_content("a", "text/plain");
  6662. });
  6663. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6664. auto se = detail::scope_exit([&] {
  6665. if (!svr.is_running()) return;
  6666. svr.stop();
  6667. listen_thread.join();
  6668. ASSERT_FALSE(svr.is_running());
  6669. });
  6670. svr.wait_until_ready();
  6671. Client cli("localhost", PORT);
  6672. cli.set_keep_alive(true);
  6673. using namespace std::chrono;
  6674. auto start = steady_clock::now();
  6675. cli.Get("/a");
  6676. svr.stop();
  6677. listen_thread.join();
  6678. auto end = steady_clock::now();
  6679. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6680. EXPECT_LT(elapsed, 5000);
  6681. }
  6682. #ifdef CPPHTTPLIB_SSL_ENABLED
  6683. TEST(KeepAliveTest, SSLClientReconnection) {
  6684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6685. ASSERT_TRUE(svr.is_valid());
  6686. svr.set_keep_alive_timeout(1);
  6687. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6688. res.set_content("Hello World!", "text/plain");
  6689. });
  6690. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6691. auto se = detail::scope_exit([&] {
  6692. svr.stop();
  6693. listen_thread.join();
  6694. ASSERT_FALSE(svr.is_running());
  6695. });
  6696. svr.wait_until_ready();
  6697. SSLClient cli(HOST, PORT);
  6698. cli.enable_server_certificate_verification(false);
  6699. cli.set_keep_alive(true);
  6700. auto result = cli.Get("/hi");
  6701. ASSERT_TRUE(result);
  6702. EXPECT_EQ(StatusCode::OK_200, result->status);
  6703. result = cli.Get("/hi");
  6704. ASSERT_TRUE(result);
  6705. EXPECT_EQ(StatusCode::OK_200, result->status);
  6706. std::this_thread::sleep_for(std::chrono::seconds(2));
  6707. // Recoonect
  6708. result = cli.Get("/hi");
  6709. ASSERT_TRUE(result);
  6710. EXPECT_EQ(StatusCode::OK_200, result->status);
  6711. result = cli.Get("/hi");
  6712. ASSERT_TRUE(result);
  6713. EXPECT_EQ(StatusCode::OK_200, result->status);
  6714. }
  6715. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6717. ASSERT_TRUE(svr.is_valid());
  6718. svr.set_keep_alive_timeout(1);
  6719. std::string content = "reconnect";
  6720. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6721. res.set_content("Hello World!", "text/plain");
  6722. });
  6723. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6724. auto se = detail::scope_exit([&] {
  6725. svr.stop();
  6726. listen_thread.join();
  6727. ASSERT_FALSE(svr.is_running());
  6728. });
  6729. svr.wait_until_ready();
  6730. SSLClient cli(HOST, PORT);
  6731. cli.enable_server_certificate_verification(false);
  6732. cli.set_keep_alive(true);
  6733. auto result = cli.Post(
  6734. "/hi", content.size(),
  6735. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6736. sink.write(content.c_str(), content.size());
  6737. return true;
  6738. },
  6739. "text/plain");
  6740. ASSERT_TRUE(result);
  6741. EXPECT_EQ(200, result->status);
  6742. std::this_thread::sleep_for(std::chrono::seconds(2));
  6743. // Recoonect
  6744. result = cli.Post(
  6745. "/hi", content.size(),
  6746. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6747. sink.write(content.c_str(), content.size());
  6748. return true;
  6749. },
  6750. "text/plain");
  6751. ASSERT_TRUE(result);
  6752. EXPECT_EQ(200, result->status);
  6753. result = cli.Post(
  6754. "/hi", content.size(),
  6755. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6756. sink.write(content.c_str(), content.size());
  6757. return true;
  6758. },
  6759. "text/plain");
  6760. ASSERT_TRUE(result);
  6761. EXPECT_EQ(200, result->status);
  6762. }
  6763. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6764. using namespace httplib::tls;
  6765. {
  6766. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6767. ASSERT_TRUE(svr.is_valid());
  6768. svr.Get("/sni", [&](const Request &req, Response &res) {
  6769. std::string expected = req.sni();
  6770. EXPECT_EQ(expected, req.get_param_value("expected"));
  6771. res.set_content("ok", "text/plain");
  6772. });
  6773. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6774. auto se = detail::scope_exit([&] {
  6775. svr.stop();
  6776. listen_thread.join();
  6777. ASSERT_FALSE(svr.is_running());
  6778. });
  6779. svr.wait_until_ready();
  6780. {
  6781. SSLClient cli("localhost", PORT);
  6782. cli.enable_server_certificate_verification(false);
  6783. auto res = cli.Get("/sni?expected=localhost");
  6784. ASSERT_TRUE(res);
  6785. }
  6786. {
  6787. SSLClient cli("::1", PORT);
  6788. cli.enable_server_certificate_verification(false);
  6789. auto res = cli.Get("/sni?expected=");
  6790. // NOTE: This may fail if the server is listening on IPv4 only
  6791. // (e.g., when localhost resolves to 127.0.0.1 only)
  6792. if (res) {
  6793. EXPECT_EQ(StatusCode::OK_200, res->status);
  6794. } else {
  6795. EXPECT_EQ(Error::Connection, res.error());
  6796. }
  6797. }
  6798. }
  6799. }
  6800. #endif
  6801. TEST(ClientProblemDetectionTest, ContentProvider) {
  6802. Server svr;
  6803. size_t content_length = 1024 * 1024;
  6804. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6805. res.set_content_provider(
  6806. content_length, "text/plain",
  6807. [&](size_t offset, size_t length, DataSink &sink) {
  6808. auto out_len = std::min(length, static_cast<size_t>(1024));
  6809. std::string out(out_len, '@');
  6810. sink.write(out.data(), out_len);
  6811. return offset < 4096;
  6812. },
  6813. [](bool success) { ASSERT_FALSE(success); });
  6814. });
  6815. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6816. res.set_content_provider(
  6817. 0, "text/plain",
  6818. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6819. EXPECT_TRUE(false);
  6820. return true;
  6821. },
  6822. [](bool success) { ASSERT_FALSE(success); });
  6823. });
  6824. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6825. auto se = detail::scope_exit([&] {
  6826. svr.stop();
  6827. listen_thread.join();
  6828. ASSERT_FALSE(svr.is_running());
  6829. });
  6830. svr.wait_until_ready();
  6831. Client cli("localhost", PORT);
  6832. {
  6833. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6834. size_t /*data_length*/) { return false; });
  6835. ASSERT_FALSE(res);
  6836. }
  6837. {
  6838. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6839. size_t /*data_length*/) { return false; });
  6840. ASSERT_TRUE(res);
  6841. }
  6842. }
  6843. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6844. Server svr;
  6845. svr.set_error_handler([](Request const &, Response &res) -> void {
  6846. res.set_chunked_content_provider(
  6847. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6848. sink.os << "hello";
  6849. sink.os << "world";
  6850. sink.done();
  6851. return true;
  6852. });
  6853. });
  6854. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6855. auto se = detail::scope_exit([&] {
  6856. svr.stop();
  6857. listen_thread.join();
  6858. ASSERT_FALSE(svr.is_running());
  6859. });
  6860. svr.wait_until_ready();
  6861. Client cli("localhost", PORT);
  6862. auto res = cli.Get("/");
  6863. ASSERT_TRUE(res);
  6864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6865. EXPECT_EQ("helloworld", res->body);
  6866. }
  6867. TEST(LongPollingTest, ClientCloseDetection) {
  6868. Server svr;
  6869. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6870. res.set_chunked_content_provider(
  6871. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6872. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6873. sink.os << "hello";
  6874. auto count = 10;
  6875. while (count > 0 && sink.is_writable()) {
  6876. this_thread::sleep_for(chrono::milliseconds(10));
  6877. count--;
  6878. }
  6879. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6880. return true;
  6881. });
  6882. });
  6883. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6884. auto se = detail::scope_exit([&] {
  6885. svr.stop();
  6886. listen_thread.join();
  6887. ASSERT_FALSE(svr.is_running());
  6888. });
  6889. svr.wait_until_ready();
  6890. Client cli("localhost", PORT);
  6891. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6892. EXPECT_EQ("hello", string(data, data_length));
  6893. return false; // close the socket immediately.
  6894. });
  6895. ASSERT_FALSE(res);
  6896. }
  6897. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6898. Server svr;
  6899. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6900. res.set_chunked_content_provider(
  6901. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6902. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6903. sink.os << "hello";
  6904. EXPECT_TRUE(sink.os.good());
  6905. // Wait for the client to close the connection
  6906. auto count = 10;
  6907. while (count > 0 && sink.is_writable()) {
  6908. this_thread::sleep_for(chrono::milliseconds(10));
  6909. count--;
  6910. }
  6911. // After client disconnect, write repeatedly until the socket
  6912. // write actually fails (small writes may be absorbed by the
  6913. // kernel buffer)
  6914. std::string chunk(1024, 'x');
  6915. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6916. sink.os << chunk;
  6917. }
  6918. EXPECT_TRUE(sink.os.fail());
  6919. return true;
  6920. });
  6921. });
  6922. auto port = svr.bind_to_any_port("localhost");
  6923. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6924. auto se = detail::scope_exit([&] {
  6925. svr.stop();
  6926. listen_thread.join();
  6927. ASSERT_FALSE(svr.is_running());
  6928. });
  6929. svr.wait_until_ready();
  6930. Client cli("localhost", port);
  6931. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6932. EXPECT_EQ("hello", string(data, data_length));
  6933. return false; // close the socket immediately.
  6934. });
  6935. ASSERT_FALSE(res);
  6936. }
  6937. TEST(GetWithParametersTest, GetWithParameters) {
  6938. Server svr;
  6939. svr.Get("/", [&](const Request &req, Response &) {
  6940. EXPECT_EQ("world", req.get_param_value("hello"));
  6941. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6942. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6943. });
  6944. svr.Get("/params", [&](const Request &req, Response &) {
  6945. EXPECT_EQ("world", req.get_param_value("hello"));
  6946. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6947. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6948. });
  6949. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6950. EXPECT_EQ("resource-id", req.matches[1]);
  6951. EXPECT_EQ("foo", req.get_param_value("param1"));
  6952. EXPECT_EQ("bar", req.get_param_value("param2"));
  6953. });
  6954. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6955. EXPECT_EQ("user-id", req.path_params.at("id"));
  6956. EXPECT_EQ("foo", req.get_param_value("param1"));
  6957. EXPECT_EQ("bar", req.get_param_value("param2"));
  6958. });
  6959. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6960. auto se = detail::scope_exit([&] {
  6961. svr.stop();
  6962. listen_thread.join();
  6963. ASSERT_FALSE(svr.is_running());
  6964. });
  6965. svr.wait_until_ready();
  6966. {
  6967. Client cli(HOST, PORT);
  6968. Params params;
  6969. params.emplace("hello", "world");
  6970. params.emplace("hello2", "world2");
  6971. params.emplace("hello3", "world3");
  6972. auto res = cli.Get("/", params, Headers{});
  6973. ASSERT_TRUE(res);
  6974. EXPECT_EQ(StatusCode::OK_200, res->status);
  6975. }
  6976. {
  6977. Client cli(HOST, PORT);
  6978. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6979. ASSERT_TRUE(res);
  6980. EXPECT_EQ(StatusCode::OK_200, res->status);
  6981. }
  6982. {
  6983. Client cli(HOST, PORT);
  6984. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6985. ASSERT_TRUE(res);
  6986. EXPECT_EQ(StatusCode::OK_200, res->status);
  6987. }
  6988. {
  6989. Client cli(HOST, PORT);
  6990. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6991. ASSERT_TRUE(res);
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. }
  6994. }
  6995. TEST(GetWithParametersTest, GetWithParameters2) {
  6996. Server svr;
  6997. svr.Get("/", [&](const Request &req, Response &res) {
  6998. auto text = req.get_param_value("hello");
  6999. res.set_content(text, "text/plain");
  7000. });
  7001. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7002. auto se = detail::scope_exit([&] {
  7003. svr.stop();
  7004. listen_thread.join();
  7005. ASSERT_FALSE(svr.is_running());
  7006. });
  7007. svr.wait_until_ready();
  7008. Client cli("localhost", PORT);
  7009. Params params;
  7010. params.emplace("hello", "world");
  7011. std::string body;
  7012. auto res = cli.Get("/", params, Headers{},
  7013. [&](const char *data, size_t data_length) {
  7014. body.append(data, data_length);
  7015. return true;
  7016. });
  7017. ASSERT_TRUE(res);
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. EXPECT_EQ("world", body);
  7020. }
  7021. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7022. auto host = "httpbingo.org";
  7023. auto path = std::string{"/range/32"};
  7024. #ifdef CPPHTTPLIB_SSL_ENABLED
  7025. SSLClient cli(host);
  7026. #else
  7027. Client cli(host);
  7028. #endif
  7029. cli.set_default_headers({make_range_header({{1, 10}})});
  7030. cli.set_connection_timeout(5);
  7031. {
  7032. auto res = cli.Get(path);
  7033. ASSERT_TRUE(res);
  7034. EXPECT_EQ("bcdefghijk", res->body);
  7035. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7036. }
  7037. {
  7038. auto res = cli.Get(path);
  7039. ASSERT_TRUE(res);
  7040. EXPECT_EQ("bcdefghijk", res->body);
  7041. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7042. }
  7043. }
  7044. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7045. Server svr;
  7046. svr.set_default_headers({{"Hello", "World"}});
  7047. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7048. res.set_content("ok", "text/plain");
  7049. });
  7050. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7051. auto se = detail::scope_exit([&] {
  7052. svr.stop();
  7053. listen_thread.join();
  7054. ASSERT_FALSE(svr.is_running());
  7055. });
  7056. svr.wait_until_ready();
  7057. Client cli("localhost", PORT);
  7058. auto res = cli.Get("/");
  7059. ASSERT_TRUE(res);
  7060. EXPECT_EQ(StatusCode::OK_200, res->status);
  7061. EXPECT_EQ("ok", res->body);
  7062. EXPECT_EQ("World", res->get_header_value("Hello"));
  7063. }
  7064. #ifdef CPPHTTPLIB_SSL_ENABLED
  7065. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7066. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7067. ASSERT_TRUE(svr.is_valid());
  7068. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7069. std::this_thread::sleep_for(std::chrono::seconds(2));
  7070. res.set_content("a", "text/plain");
  7071. });
  7072. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7073. res.set_content("b", "text/plain");
  7074. });
  7075. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7076. auto se = detail::scope_exit([&] {
  7077. svr.stop();
  7078. listen_thread.join();
  7079. ASSERT_FALSE(svr.is_running());
  7080. });
  7081. svr.wait_until_ready();
  7082. SSLClient cli("localhost", PORT);
  7083. cli.enable_server_certificate_verification(false);
  7084. cli.set_keep_alive(true);
  7085. cli.set_read_timeout(std::chrono::seconds(1));
  7086. auto resa = cli.Get("/a");
  7087. ASSERT_TRUE(!resa);
  7088. EXPECT_EQ(Error::Read, resa.error());
  7089. auto resb = cli.Get("/b");
  7090. ASSERT_TRUE(resb);
  7091. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7092. EXPECT_EQ("b", resb->body);
  7093. }
  7094. #endif
  7095. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7096. protected:
  7097. ServerTestWithAI_PASSIVE()
  7098. : cli_(HOST, PORT)
  7099. #ifdef CPPHTTPLIB_SSL_ENABLED
  7100. ,
  7101. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7102. #endif
  7103. {
  7104. #ifdef CPPHTTPLIB_SSL_ENABLED
  7105. cli_.enable_server_certificate_verification(false);
  7106. #endif
  7107. }
  7108. virtual void SetUp() {
  7109. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7110. res.set_content("Hello World!", "text/plain");
  7111. });
  7112. t_ = thread(
  7113. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7114. svr_.wait_until_ready();
  7115. }
  7116. virtual void TearDown() {
  7117. svr_.stop();
  7118. t_.join();
  7119. }
  7120. #ifdef CPPHTTPLIB_SSL_ENABLED
  7121. SSLClient cli_;
  7122. SSLServer svr_;
  7123. #else
  7124. Client cli_;
  7125. Server svr_;
  7126. #endif
  7127. thread t_;
  7128. };
  7129. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7130. auto res = cli_.Get("/hi");
  7131. ASSERT_TRUE(res);
  7132. EXPECT_EQ(StatusCode::OK_200, res->status);
  7133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7134. EXPECT_EQ("Hello World!", res->body);
  7135. }
  7136. class ServerUpDownTest : public ::testing::Test {
  7137. protected:
  7138. ServerUpDownTest() : cli_(HOST, PORT) {}
  7139. virtual void SetUp() {
  7140. t_ = thread([&]() {
  7141. svr_.bind_to_any_port(HOST);
  7142. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7143. ASSERT_TRUE(svr_.listen_after_bind());
  7144. });
  7145. svr_.wait_until_ready();
  7146. }
  7147. virtual void TearDown() {
  7148. svr_.stop();
  7149. t_.join();
  7150. }
  7151. Client cli_;
  7152. Server svr_;
  7153. thread t_;
  7154. };
  7155. TEST_F(ServerUpDownTest, QuickStartStop) {
  7156. // Should not crash, especially when run with
  7157. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7158. }
  7159. class PayloadMaxLengthTest : public ::testing::Test {
  7160. protected:
  7161. PayloadMaxLengthTest()
  7162. : cli_(HOST, PORT)
  7163. #ifdef CPPHTTPLIB_SSL_ENABLED
  7164. ,
  7165. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7166. #endif
  7167. {
  7168. #ifdef CPPHTTPLIB_SSL_ENABLED
  7169. cli_.enable_server_certificate_verification(false);
  7170. #endif
  7171. }
  7172. virtual void SetUp() {
  7173. svr_.set_payload_max_length(8);
  7174. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7175. res.set_content("test", "text/plain");
  7176. });
  7177. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7178. svr_.wait_until_ready();
  7179. }
  7180. virtual void TearDown() {
  7181. svr_.stop();
  7182. t_.join();
  7183. }
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. SSLClient cli_;
  7186. SSLServer svr_;
  7187. #else
  7188. Client cli_;
  7189. Server svr_;
  7190. #endif
  7191. thread t_;
  7192. };
  7193. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7194. auto res = cli_.Post("/test", "123456789", "text/plain");
  7195. ASSERT_TRUE(res);
  7196. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7197. res = cli_.Post("/test", "12345678", "text/plain");
  7198. ASSERT_TRUE(res);
  7199. EXPECT_EQ(StatusCode::OK_200, res->status);
  7200. }
  7201. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7202. // Test chunked encoding with payload exceeding the 8-byte limit
  7203. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7204. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7205. ASSERT_TRUE(res);
  7206. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7207. }
  7208. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7209. // Test chunked encoding with payload within the 8-byte limit
  7210. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7211. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7212. ASSERT_TRUE(res);
  7213. EXPECT_EQ(StatusCode::OK_200, res->status);
  7214. }
  7215. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7216. // Test using send_request to send chunked data exceeding payload limit
  7217. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7218. "Host: " +
  7219. std::string(HOST) + ":" + std::to_string(PORT) +
  7220. "\r\n"
  7221. "Transfer-Encoding: chunked\r\n"
  7222. "Connection: close\r\n"
  7223. "\r\n"
  7224. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7225. "0123456789\r\n"
  7226. "0\r\n" // End chunk
  7227. "\r\n";
  7228. std::string response;
  7229. bool result = send_request(1, chunked_request, &response);
  7230. if (!result) {
  7231. // If send_request fails, it might be because the server closed the
  7232. // connection due to payload limit enforcement, which is acceptable
  7233. SUCCEED()
  7234. << "Server rejected oversized chunked request (connection closed)";
  7235. } else {
  7236. // If we got a response, check if it's an error response or connection was
  7237. // closed early Short response length indicates connection was closed due to
  7238. // payload limit
  7239. if (response.length() <= 10) {
  7240. SUCCEED() << "Server closed connection for oversized chunked request";
  7241. } else {
  7242. // Check for error status codes
  7243. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7244. response.find("Payload Too Large") != std::string::npos ||
  7245. response.find("400") != std::string::npos);
  7246. }
  7247. }
  7248. }
  7249. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7250. // Test request without Content-Length header exceeding payload limit
  7251. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7252. "Host: " +
  7253. std::string(HOST) + ":" +
  7254. std::to_string(PORT) +
  7255. "\r\n"
  7256. "Connection: close\r\n"
  7257. "\r\n";
  7258. // Add payload exceeding the 8-byte limit
  7259. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7260. request_without_content_length += large_payload;
  7261. std::string response;
  7262. bool result = send_request(1, request_without_content_length, &response);
  7263. if (!result) {
  7264. // If send_request fails, server likely closed connection due to payload
  7265. // limit
  7266. SUCCEED() << "Server rejected oversized request without Content-Length "
  7267. "(connection closed)";
  7268. } else {
  7269. // Check if server responded with error or closed connection early
  7270. if (response.length() <= 10) {
  7271. SUCCEED() << "Server closed connection for oversized request without "
  7272. "Content-Length";
  7273. } else {
  7274. // Check for error status codes
  7275. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7276. response.find("Payload Too Large") != std::string::npos ||
  7277. response.find("400") != std::string::npos);
  7278. }
  7279. }
  7280. }
  7281. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7282. // Test request without Content-Length header within payload limit
  7283. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7284. "Host: " +
  7285. std::string(HOST) + ":" +
  7286. std::to_string(PORT) +
  7287. "\r\n"
  7288. "Connection: close\r\n"
  7289. "\r\n";
  7290. // Add payload within the 8-byte limit
  7291. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7292. request_without_content_length += small_payload;
  7293. std::string response;
  7294. bool result = send_request(1, request_without_content_length, &response);
  7295. // For requests without Content-Length, the server may have different behavior
  7296. // The key is that it should not reject due to payload limit for small
  7297. // payloads
  7298. if (result) {
  7299. // Check for any HTTP response (success or error, but not connection closed)
  7300. if (response.length() > 10) {
  7301. SUCCEED()
  7302. << "Server processed request without Content-Length within limit";
  7303. } else {
  7304. // Short response might indicate connection closed, which is acceptable
  7305. SUCCEED() << "Server closed connection for request without "
  7306. "Content-Length (acceptable behavior)";
  7307. }
  7308. } else {
  7309. // Connection failure might be due to protocol requirements
  7310. SUCCEED() << "Connection issue with request without Content-Length "
  7311. "(environment-specific)";
  7312. }
  7313. }
  7314. class LargePayloadMaxLengthTest : public ::testing::Test {
  7315. protected:
  7316. LargePayloadMaxLengthTest()
  7317. : cli_(HOST, PORT)
  7318. #ifdef CPPHTTPLIB_SSL_ENABLED
  7319. ,
  7320. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7321. #endif
  7322. {
  7323. #ifdef CPPHTTPLIB_SSL_ENABLED
  7324. cli_.enable_server_certificate_verification(false);
  7325. #endif
  7326. }
  7327. virtual void SetUp() {
  7328. // Set 10MB payload limit
  7329. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7330. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7331. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7332. res.set_content("Large payload test", "text/plain");
  7333. });
  7334. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7335. svr_.wait_until_ready();
  7336. }
  7337. virtual void TearDown() {
  7338. svr_.stop();
  7339. t_.join();
  7340. }
  7341. #ifdef CPPHTTPLIB_SSL_ENABLED
  7342. SSLClient cli_;
  7343. SSLServer svr_;
  7344. #else
  7345. Client cli_;
  7346. Server svr_;
  7347. #endif
  7348. thread t_;
  7349. };
  7350. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7351. // Test chunked encoding with payload within 10MB limit
  7352. std::string medium_payload(5 * 1024 * 1024,
  7353. 'A'); // 5MB payload, within 10MB limit
  7354. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7355. ASSERT_TRUE(res);
  7356. EXPECT_EQ(StatusCode::OK_200, res->status);
  7357. }
  7358. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7359. // Test chunked encoding with payload exceeding 10MB limit
  7360. std::string large_payload(12 * 1024 * 1024,
  7361. 'B'); // 12MB payload, exceeds 10MB limit
  7362. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7363. // Server may either return 413 or close the connection
  7364. if (res) {
  7365. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7366. } else {
  7367. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7368. }
  7369. }
  7370. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7371. // Test request without Content-Length header within 10MB limit
  7372. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7373. "Host: " +
  7374. std::string(HOST) + ":" +
  7375. std::to_string(PORT) +
  7376. "\r\n"
  7377. "Connection: close\r\n"
  7378. "\r\n";
  7379. // Add 1MB payload (within 10MB limit)
  7380. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7381. request_without_content_length += medium_payload;
  7382. std::string response;
  7383. bool result = send_request(5, request_without_content_length, &response);
  7384. if (result) {
  7385. // Should get a proper HTTP response for payloads within limit
  7386. if (response.length() > 10) {
  7387. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7388. "10MB limit";
  7389. } else {
  7390. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7391. "Content-Length)";
  7392. }
  7393. } else {
  7394. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7395. }
  7396. }
  7397. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7398. // Test request without Content-Length header exceeding 10MB limit
  7399. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7400. "Host: " +
  7401. std::string(HOST) + ":" +
  7402. std::to_string(PORT) +
  7403. "\r\n"
  7404. "Connection: close\r\n"
  7405. "\r\n";
  7406. // Add 12MB payload (exceeds 10MB limit)
  7407. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7408. request_without_content_length += large_payload;
  7409. std::string response;
  7410. bool result = send_request(10, request_without_content_length, &response);
  7411. if (!result) {
  7412. // Server should close connection due to payload limit
  7413. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7414. "(connection closed)";
  7415. } else {
  7416. // Check for error response
  7417. if (response.length() <= 10) {
  7418. SUCCEED()
  7419. << "Server closed connection for 12MB request exceeding 10MB limit";
  7420. } else {
  7421. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7422. response.find("Payload Too Large") != std::string::npos ||
  7423. response.find("400") != std::string::npos);
  7424. }
  7425. }
  7426. }
  7427. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7428. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7429. // path.
  7430. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7431. Server svr;
  7432. const size_t LIMIT = 64 * 1024; // 64KB
  7433. svr.set_payload_max_length(LIMIT);
  7434. size_t total = 0;
  7435. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7436. const ContentReader &content_reader) {
  7437. content_reader([&](const char * /*data*/, size_t len) {
  7438. total += len;
  7439. return true;
  7440. });
  7441. res.status = 200;
  7442. res.set_content("stream_ok", "text/plain");
  7443. });
  7444. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7445. auto se = detail::scope_exit([&] {
  7446. svr.stop();
  7447. thread.join();
  7448. ASSERT_FALSE(svr.is_running());
  7449. });
  7450. svr.wait_until_ready();
  7451. // Prepare 256KB raw data and gzip-compress it
  7452. std::string raw(256 * 1024, 'A');
  7453. std::string gz;
  7454. {
  7455. z_stream zs{};
  7456. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7457. Z_DEFAULT_STRATEGY);
  7458. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7459. zs.avail_in = static_cast<uInt>(raw.size());
  7460. char outbuf[4096];
  7461. int ret;
  7462. do {
  7463. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7464. zs.avail_out = sizeof(outbuf);
  7465. ret = deflate(&zs, Z_FINISH);
  7466. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7467. } while (ret != Z_STREAM_END);
  7468. deflateEnd(&zs);
  7469. }
  7470. Client cli(HOST, PORT);
  7471. cli.set_connection_timeout(std::chrono::seconds(5));
  7472. Headers headers = {{"Content-Encoding", "gzip"}};
  7473. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7474. "application/octet-stream");
  7475. ASSERT_TRUE(res);
  7476. // Server must reject oversized decompressed payloads with 413.
  7477. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7478. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7479. EXPECT_LE(total, LIMIT);
  7480. }
  7481. #endif
  7482. // Regression test for DoS vulnerability: a malicious server sending a response
  7483. // without Content-Length header must not cause unbounded memory consumption on
  7484. // the client side. The client should stop reading after a reasonable limit,
  7485. // similar to the server-side set_payload_max_length protection.
  7486. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7487. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7488. #ifndef _WIN32
  7489. signal(SIGPIPE, SIG_IGN);
  7490. #endif
  7491. auto server_thread = std::thread([] {
  7492. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7493. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7494. default_socket_options(srv);
  7495. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7496. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7497. sockaddr_in addr{};
  7498. addr.sin_family = AF_INET;
  7499. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7500. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7501. int opt = 1;
  7502. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7503. #ifdef _WIN32
  7504. reinterpret_cast<const char *>(&opt),
  7505. #else
  7506. &opt,
  7507. #endif
  7508. sizeof(opt));
  7509. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7510. ::listen(srv, 1);
  7511. sockaddr_in cli_addr{};
  7512. socklen_t cli_len = sizeof(cli_addr);
  7513. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7514. if (cli != INVALID_SOCKET) {
  7515. char buf[4096];
  7516. ::recv(cli, buf, sizeof(buf), 0);
  7517. // Malicious response: no Content-Length, no chunked encoding
  7518. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7519. "Connection: close\r\n"
  7520. "\r\n";
  7521. ::send(cli,
  7522. #ifdef _WIN32
  7523. static_cast<const char *>(response_header.c_str()),
  7524. static_cast<int>(response_header.size()),
  7525. #else
  7526. response_header.c_str(), response_header.size(),
  7527. #endif
  7528. 0);
  7529. // Send 10MB of data
  7530. std::string chunk(64 * 1024, 'A');
  7531. size_t total_sent = 0;
  7532. while (total_sent < MALICIOUS_DATA_SIZE) {
  7533. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7534. auto sent = ::send(cli,
  7535. #ifdef _WIN32
  7536. static_cast<const char *>(chunk.c_str()),
  7537. static_cast<int>(to_send),
  7538. #else
  7539. chunk.c_str(), to_send,
  7540. #endif
  7541. 0);
  7542. if (sent <= 0) break;
  7543. total_sent += static_cast<size_t>(sent);
  7544. }
  7545. detail::close_socket(cli);
  7546. }
  7547. detail::close_socket(srv);
  7548. });
  7549. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7550. size_t total_read = 0;
  7551. {
  7552. Client cli("127.0.0.1", PORT + 2);
  7553. cli.set_read_timeout(5, 0);
  7554. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7555. auto stream = cli.open_stream("GET", "/malicious");
  7556. ASSERT_TRUE(stream.is_valid());
  7557. char buffer[64 * 1024];
  7558. ssize_t n;
  7559. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7560. total_read += static_cast<size_t>(n);
  7561. }
  7562. } // StreamHandle and Client destroyed here, closing the socket
  7563. server_thread.join();
  7564. // With set_payload_max_length, the client must stop reading before consuming
  7565. // all 10MB. The read loop should be cut off at or near the configured limit.
  7566. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7567. << "Client read " << total_read << " bytes, exceeding the configured "
  7568. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7569. }
  7570. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7571. // the entire response body without truncation.
  7572. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7573. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7574. #ifndef _WIN32
  7575. signal(SIGPIPE, SIG_IGN);
  7576. #endif
  7577. auto server_thread = std::thread([] {
  7578. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7579. default_socket_options(srv);
  7580. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7581. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7582. sockaddr_in addr{};
  7583. addr.sin_family = AF_INET;
  7584. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7585. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7586. int opt = 1;
  7587. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7588. #ifdef _WIN32
  7589. reinterpret_cast<const char *>(&opt),
  7590. #else
  7591. &opt,
  7592. #endif
  7593. sizeof(opt));
  7594. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7595. ::listen(srv, 1);
  7596. sockaddr_in cli_addr{};
  7597. socklen_t cli_len = sizeof(cli_addr);
  7598. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7599. if (cli != INVALID_SOCKET) {
  7600. char buf[4096];
  7601. ::recv(cli, buf, sizeof(buf), 0);
  7602. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7603. "Connection: close\r\n"
  7604. "\r\n";
  7605. ::send(cli,
  7606. #ifdef _WIN32
  7607. static_cast<const char *>(response_header.c_str()),
  7608. static_cast<int>(response_header.size()),
  7609. #else
  7610. response_header.c_str(), response_header.size(),
  7611. #endif
  7612. 0);
  7613. std::string chunk(64 * 1024, 'A');
  7614. size_t total_sent = 0;
  7615. while (total_sent < DATA_SIZE) {
  7616. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7617. auto sent = ::send(cli,
  7618. #ifdef _WIN32
  7619. static_cast<const char *>(chunk.c_str()),
  7620. static_cast<int>(to_send),
  7621. #else
  7622. chunk.c_str(), to_send,
  7623. #endif
  7624. 0);
  7625. if (sent <= 0) break;
  7626. total_sent += static_cast<size_t>(sent);
  7627. }
  7628. #ifdef _WIN32
  7629. ::shutdown(cli, SD_SEND);
  7630. #else
  7631. ::shutdown(cli, SHUT_WR);
  7632. #endif
  7633. // Drain until the client closes its end, ensuring all data is delivered
  7634. char drain[1024];
  7635. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7636. detail::close_socket(cli);
  7637. }
  7638. detail::close_socket(srv);
  7639. });
  7640. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7641. size_t total_read = 0;
  7642. {
  7643. Client cli("127.0.0.1", PORT + 2);
  7644. cli.set_read_timeout(5, 0);
  7645. cli.set_payload_max_length(0); // 0 means no limit
  7646. auto stream = cli.open_stream("GET", "/data");
  7647. ASSERT_TRUE(stream.is_valid());
  7648. char buffer[64 * 1024];
  7649. ssize_t n;
  7650. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7651. total_read += static_cast<size_t>(n);
  7652. }
  7653. }
  7654. server_thread.join();
  7655. EXPECT_EQ(total_read, DATA_SIZE)
  7656. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7657. << " bytes without truncation, but only read " << total_read << " bytes.";
  7658. }
  7659. // Verify that content_receiver bypasses the default payload_max_length,
  7660. // allowing streaming downloads larger than 100MB without requiring an explicit
  7661. // set_payload_max_length call.
  7662. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7663. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7664. #ifndef _WIN32
  7665. signal(SIGPIPE, SIG_IGN);
  7666. #endif
  7667. auto server_thread = std::thread([] {
  7668. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7669. default_socket_options(srv);
  7670. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7671. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7672. sockaddr_in addr{};
  7673. addr.sin_family = AF_INET;
  7674. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7675. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7676. int opt = 1;
  7677. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7678. #ifdef _WIN32
  7679. reinterpret_cast<const char *>(&opt),
  7680. #else
  7681. &opt,
  7682. #endif
  7683. sizeof(opt));
  7684. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7685. ::listen(srv, 1);
  7686. sockaddr_in cli_addr{};
  7687. socklen_t cli_len = sizeof(cli_addr);
  7688. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7689. if (cli != INVALID_SOCKET) {
  7690. char buf[4096];
  7691. ::recv(cli, buf, sizeof(buf), 0);
  7692. // Response with Content-Length larger than default 100MB limit
  7693. auto content_length = std::to_string(DATA_SIZE);
  7694. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7695. "Content-Length: " +
  7696. content_length +
  7697. "\r\n"
  7698. "Connection: close\r\n"
  7699. "\r\n";
  7700. ::send(cli,
  7701. #ifdef _WIN32
  7702. static_cast<const char *>(response_header.c_str()),
  7703. static_cast<int>(response_header.size()),
  7704. #else
  7705. response_header.c_str(), response_header.size(),
  7706. #endif
  7707. 0);
  7708. std::string chunk(64 * 1024, 'A');
  7709. size_t total_sent = 0;
  7710. while (total_sent < DATA_SIZE) {
  7711. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7712. auto sent = ::send(cli,
  7713. #ifdef _WIN32
  7714. static_cast<const char *>(chunk.c_str()),
  7715. static_cast<int>(to_send),
  7716. #else
  7717. chunk.c_str(), to_send,
  7718. #endif
  7719. 0);
  7720. if (sent <= 0) break;
  7721. total_sent += static_cast<size_t>(sent);
  7722. }
  7723. detail::close_socket(cli);
  7724. }
  7725. detail::close_socket(srv);
  7726. });
  7727. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7728. size_t total_received = 0;
  7729. {
  7730. Client cli("127.0.0.1", PORT + 2);
  7731. cli.set_read_timeout(10, 0);
  7732. // Do NOT call set_payload_max_length — use the default 100MB limit
  7733. auto res =
  7734. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7735. total_received += data_length;
  7736. return true;
  7737. });
  7738. ASSERT_TRUE(res);
  7739. EXPECT_EQ(StatusCode::OK_200, res->status);
  7740. }
  7741. server_thread.join();
  7742. EXPECT_EQ(total_received, DATA_SIZE)
  7743. << "With content_receiver, the client should read all " << DATA_SIZE
  7744. << " bytes despite the default 100MB payload_max_length, but only read "
  7745. << total_received << " bytes.";
  7746. }
  7747. // Verify that an explicit set_payload_max_length smaller than the response is
  7748. // enforced even when a content_receiver is used.
  7749. TEST(ClientVulnerabilityTest,
  7750. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7751. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7752. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7753. #ifndef _WIN32
  7754. signal(SIGPIPE, SIG_IGN);
  7755. #endif
  7756. auto server_thread = std::thread([] {
  7757. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7758. default_socket_options(srv);
  7759. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7760. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7761. sockaddr_in addr{};
  7762. addr.sin_family = AF_INET;
  7763. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7764. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7765. int opt = 1;
  7766. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7767. #ifdef _WIN32
  7768. reinterpret_cast<const char *>(&opt),
  7769. #else
  7770. &opt,
  7771. #endif
  7772. sizeof(opt));
  7773. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7774. ::listen(srv, 1);
  7775. sockaddr_in cli_addr{};
  7776. socklen_t cli_len = sizeof(cli_addr);
  7777. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7778. if (cli != INVALID_SOCKET) {
  7779. char buf[4096];
  7780. ::recv(cli, buf, sizeof(buf), 0);
  7781. auto content_length = std::to_string(DATA_SIZE);
  7782. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7783. "Content-Length: " +
  7784. content_length +
  7785. "\r\n"
  7786. "Connection: close\r\n"
  7787. "\r\n";
  7788. ::send(cli,
  7789. #ifdef _WIN32
  7790. static_cast<const char *>(response_header.c_str()),
  7791. static_cast<int>(response_header.size()),
  7792. #else
  7793. response_header.c_str(), response_header.size(),
  7794. #endif
  7795. 0);
  7796. std::string chunk(64 * 1024, 'A');
  7797. size_t total_sent = 0;
  7798. while (total_sent < DATA_SIZE) {
  7799. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7800. auto sent = ::send(cli,
  7801. #ifdef _WIN32
  7802. static_cast<const char *>(chunk.c_str()),
  7803. static_cast<int>(to_send),
  7804. #else
  7805. chunk.c_str(), to_send,
  7806. #endif
  7807. 0);
  7808. if (sent <= 0) break;
  7809. total_sent += static_cast<size_t>(sent);
  7810. }
  7811. detail::close_socket(cli);
  7812. }
  7813. detail::close_socket(srv);
  7814. });
  7815. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7816. size_t total_received = 0;
  7817. {
  7818. Client cli("127.0.0.1", PORT + 2);
  7819. cli.set_read_timeout(10, 0);
  7820. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7821. auto res =
  7822. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7823. total_received += data_length;
  7824. return true;
  7825. });
  7826. // Should fail because 200MB exceeds the explicit 150MB limit
  7827. EXPECT_FALSE(res);
  7828. }
  7829. server_thread.join();
  7830. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7831. << "Client with content_receiver should respect the explicit "
  7832. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7833. << total_received << " bytes.";
  7834. }
  7835. // Verify that an explicit set_payload_max_length larger than the response
  7836. // allows the content_receiver to read all data successfully.
  7837. TEST(ClientVulnerabilityTest,
  7838. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7839. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7840. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7841. #ifndef _WIN32
  7842. signal(SIGPIPE, SIG_IGN);
  7843. #endif
  7844. auto server_thread = std::thread([] {
  7845. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7846. default_socket_options(srv);
  7847. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7848. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7849. sockaddr_in addr{};
  7850. addr.sin_family = AF_INET;
  7851. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7852. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7853. int opt = 1;
  7854. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7855. #ifdef _WIN32
  7856. reinterpret_cast<const char *>(&opt),
  7857. #else
  7858. &opt,
  7859. #endif
  7860. sizeof(opt));
  7861. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7862. ::listen(srv, 1);
  7863. sockaddr_in cli_addr{};
  7864. socklen_t cli_len = sizeof(cli_addr);
  7865. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7866. if (cli != INVALID_SOCKET) {
  7867. char buf[4096];
  7868. ::recv(cli, buf, sizeof(buf), 0);
  7869. auto content_length = std::to_string(DATA_SIZE);
  7870. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7871. "Content-Length: " +
  7872. content_length +
  7873. "\r\n"
  7874. "Connection: close\r\n"
  7875. "\r\n";
  7876. ::send(cli,
  7877. #ifdef _WIN32
  7878. static_cast<const char *>(response_header.c_str()),
  7879. static_cast<int>(response_header.size()),
  7880. #else
  7881. response_header.c_str(), response_header.size(),
  7882. #endif
  7883. 0);
  7884. std::string chunk(64 * 1024, 'A');
  7885. size_t total_sent = 0;
  7886. while (total_sent < DATA_SIZE) {
  7887. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7888. auto sent = ::send(cli,
  7889. #ifdef _WIN32
  7890. static_cast<const char *>(chunk.c_str()),
  7891. static_cast<int>(to_send),
  7892. #else
  7893. chunk.c_str(), to_send,
  7894. #endif
  7895. 0);
  7896. if (sent <= 0) break;
  7897. total_sent += static_cast<size_t>(sent);
  7898. }
  7899. #ifdef _WIN32
  7900. ::shutdown(cli, SD_SEND);
  7901. #else
  7902. ::shutdown(cli, SHUT_WR);
  7903. #endif
  7904. char drain[1024];
  7905. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7906. detail::close_socket(cli);
  7907. }
  7908. detail::close_socket(srv);
  7909. });
  7910. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7911. size_t total_received = 0;
  7912. {
  7913. Client cli("127.0.0.1", PORT + 2);
  7914. cli.set_read_timeout(10, 0);
  7915. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7916. auto res =
  7917. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7918. total_received += data_length;
  7919. return true;
  7920. });
  7921. ASSERT_TRUE(res);
  7922. EXPECT_EQ(StatusCode::OK_200, res->status);
  7923. }
  7924. server_thread.join();
  7925. EXPECT_EQ(total_received, DATA_SIZE)
  7926. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7927. << " bytes (larger than " << DATA_SIZE
  7928. << " bytes response), content_receiver should read all data, but only "
  7929. "read "
  7930. << total_received << " bytes.";
  7931. }
  7932. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7933. // Regression test for "zip bomb" attack on the client side: a malicious server
  7934. // sends a small gzip-compressed response that decompresses to a huge payload.
  7935. // The client must enforce payload_max_length on the decompressed size.
  7936. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7937. constexpr size_t DECOMPRESSED_SIZE =
  7938. 10 * 1024 * 1024; // 10MB after decompression
  7939. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7940. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7941. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7942. std::string compressed;
  7943. {
  7944. httplib::detail::gzip_compressor compressor;
  7945. bool ok =
  7946. compressor.compress(uncompressed.data(), uncompressed.size(),
  7947. /*last=*/true, [&](const char *buf, size_t len) {
  7948. compressed.append(buf, len);
  7949. return true;
  7950. });
  7951. ASSERT_TRUE(ok);
  7952. }
  7953. // Sanity: compressed data should be much smaller than the decompressed size
  7954. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7955. #ifndef _WIN32
  7956. signal(SIGPIPE, SIG_IGN);
  7957. #endif
  7958. // Set up the listening socket in the main thread so the server is guaranteed
  7959. // to be ready before the client connects (eliminates race condition).
  7960. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7961. default_socket_options(srv);
  7962. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7963. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7964. sockaddr_in addr{};
  7965. addr.sin_family = AF_INET;
  7966. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  7967. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7968. int opt = 1;
  7969. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7970. #ifdef _WIN32
  7971. reinterpret_cast<const char *>(&opt),
  7972. #else
  7973. &opt,
  7974. #endif
  7975. sizeof(opt));
  7976. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7977. ASSERT_EQ(0, ::listen(srv, 1));
  7978. auto server_thread = std::thread([&compressed, srv] {
  7979. sockaddr_in cli_addr{};
  7980. socklen_t cli_len = sizeof(cli_addr);
  7981. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7982. if (cli != INVALID_SOCKET) {
  7983. // Read the full HTTP request (until \r\n\r\n)
  7984. char buf[4096];
  7985. size_t total = 0;
  7986. while (total < sizeof(buf)) {
  7987. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  7988. if (n <= 0) break;
  7989. total += static_cast<size_t>(n);
  7990. // Check for end of headers
  7991. if (total >= 4) {
  7992. std::string req(buf, total);
  7993. if (req.find("\r\n\r\n") != std::string::npos) break;
  7994. }
  7995. }
  7996. // Malicious response: gzip-compressed body, no Content-Length
  7997. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7998. "Content-Encoding: gzip\r\n"
  7999. "Connection: close\r\n"
  8000. "\r\n";
  8001. ::send(cli,
  8002. #ifdef _WIN32
  8003. static_cast<const char *>(response_header.c_str()),
  8004. static_cast<int>(response_header.size()),
  8005. #else
  8006. response_header.c_str(), response_header.size(),
  8007. #endif
  8008. 0);
  8009. // Send the compressed payload (small on the wire, huge when decompressed)
  8010. size_t total_sent = 0;
  8011. while (total_sent < compressed.size()) {
  8012. auto to_send = std::min(compressed.size() - total_sent,
  8013. static_cast<size_t>(64 * 1024));
  8014. auto sent =
  8015. ::send(cli,
  8016. #ifdef _WIN32
  8017. static_cast<const char *>(compressed.c_str() + total_sent),
  8018. static_cast<int>(to_send),
  8019. #else
  8020. compressed.c_str() + total_sent, to_send,
  8021. #endif
  8022. 0);
  8023. if (sent <= 0) break;
  8024. total_sent += static_cast<size_t>(sent);
  8025. }
  8026. detail::close_socket(cli);
  8027. }
  8028. });
  8029. auto se = detail::scope_exit([&] {
  8030. detail::close_socket(srv);
  8031. server_thread.join();
  8032. });
  8033. size_t total_decompressed = 0;
  8034. {
  8035. Client cli("127.0.0.1", PORT + 3);
  8036. cli.set_read_timeout(5, 0);
  8037. cli.set_decompress(true);
  8038. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8039. auto stream = cli.open_stream("GET", "/zipbomb");
  8040. ASSERT_TRUE(stream.is_valid());
  8041. char buffer[64 * 1024];
  8042. ssize_t n;
  8043. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8044. total_decompressed += static_cast<size_t>(n);
  8045. }
  8046. }
  8047. // The decompressed size must be capped by payload_max_length. Without
  8048. // protection, the client would decompress the full 10MB from a tiny
  8049. // compressed payload, enabling a zip bomb DoS attack.
  8050. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8051. << "Client decompressed " << total_decompressed
  8052. << " bytes from a gzip response. The decompressed size should be "
  8053. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8054. }
  8055. #endif
  8056. TEST(HostAndPortPropertiesTest, NoSSL) {
  8057. httplib::Client cli("www.google.com", 1234);
  8058. ASSERT_EQ("www.google.com", cli.host());
  8059. ASSERT_EQ(1234, cli.port());
  8060. }
  8061. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8062. httplib::Client cli("www.google.com:1234");
  8063. ASSERT_EQ("www.google.com", cli.host());
  8064. ASSERT_EQ(1234, cli.port());
  8065. }
  8066. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8067. // Port number that overflows int — should not crash, client becomes invalid
  8068. httplib::Client cli("http://www.google.com:99999999999999999999");
  8069. ASSERT_FALSE(cli.is_valid());
  8070. }
  8071. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8072. // Port 99999 exceeds valid range (1-65535) — should not crash
  8073. httplib::Client cli("http://www.google.com:99999");
  8074. ASSERT_FALSE(cli.is_valid());
  8075. }
  8076. #ifdef CPPHTTPLIB_SSL_ENABLED
  8077. TEST(HostAndPortPropertiesTest, SSL) {
  8078. httplib::SSLClient cli("www.google.com");
  8079. ASSERT_EQ("www.google.com", cli.host());
  8080. ASSERT_EQ(443, cli.port());
  8081. }
  8082. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8083. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8084. std::string cert;
  8085. read_file(CA_CERT_FILE, cert);
  8086. httplib::SSLClient httplib_client("www.google.com");
  8087. // Load CA store first time
  8088. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8089. // Load CA store second time (update)
  8090. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8091. // Verify client is still valid and can make connections
  8092. httplib_client.enable_server_certificate_verification(true);
  8093. auto res = httplib_client.Get("/");
  8094. ASSERT_TRUE(res);
  8095. // Google may return 200 or 301 depending on various factors
  8096. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8097. res->status == StatusCode::MovedPermanently_301);
  8098. }
  8099. TEST(SSLClientTest, ServerNameIndication_Online) {
  8100. auto host = "httpbingo.org";
  8101. auto path = std::string{"/get"};
  8102. SSLClient cli(host, 443);
  8103. auto res = cli.Get(path);
  8104. ASSERT_TRUE(res);
  8105. ASSERT_EQ(StatusCode::OK_200, res->status);
  8106. }
  8107. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8108. // Use a site that will cause SSL verification failure due to self-signed cert
  8109. SSLClient cli("self-signed.badssl.com", 443);
  8110. cli.enable_server_certificate_verification(true);
  8111. auto res = cli.Get("/");
  8112. ASSERT_TRUE(!res);
  8113. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8114. // Verify backend error is captured for SSLServerVerification
  8115. // This occurs when certificate verification fails
  8116. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8117. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8118. EXPECT_NE(0UL, res.ssl_backend_error());
  8119. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8120. // For OpenSSL, ssl_error is 0 for verification errors
  8121. EXPECT_EQ(0, res.ssl_error());
  8122. #if !defined(_WIN32) || \
  8123. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8124. // On non-Windows or when Windows Schannel is disabled, the error comes
  8125. // from OpenSSL's verification
  8126. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8127. res.ssl_backend_error());
  8128. #endif
  8129. #endif
  8130. }
  8131. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8132. // Use a site where hostname doesn't match the certificate
  8133. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8134. SSLClient cli("wrong.host.badssl.com", 443);
  8135. cli.enable_server_certificate_verification(true);
  8136. cli.enable_server_hostname_verification(true);
  8137. auto res = cli.Get("/");
  8138. ASSERT_TRUE(!res);
  8139. // The error type depends on when hostname verification occurs:
  8140. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8141. // - Mbed TLS: SSLServerVerification (during handshake)
  8142. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8143. res.error() == Error::SSLServerVerification);
  8144. // Verify backend error is captured for hostname verification failure
  8145. EXPECT_NE(0UL, res.ssl_backend_error());
  8146. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8147. // For OpenSSL, ssl_error is 0 for verification errors
  8148. EXPECT_EQ(0, res.ssl_error());
  8149. #if !defined(_WIN32) || \
  8150. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8151. // On non-Windows or when Windows Schannel is disabled, the error comes
  8152. // from OpenSSL's hostname verification
  8153. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8154. res.ssl_backend_error());
  8155. #endif
  8156. #endif
  8157. }
  8158. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8159. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8160. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8161. SSLClient cli("www.google.com", 443);
  8162. cli.enable_server_certificate_verification(true);
  8163. auto res = cli.Get("/");
  8164. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8165. }
  8166. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8167. SSLClient cli("www.google.com", 443);
  8168. cli.enable_server_certificate_verification(true);
  8169. cli.enable_windows_certificate_verification(false);
  8170. auto res = cli.Get("/");
  8171. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8172. }
  8173. #endif
  8174. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8175. Client cli("https://google.com");
  8176. auto res = cli.Get("/");
  8177. ASSERT_TRUE(res);
  8178. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8179. }
  8180. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8181. SSLClient cli("google.com");
  8182. cli.set_ca_cert_path(CA_CERT_FILE);
  8183. auto res = cli.Get("/");
  8184. ASSERT_TRUE(res);
  8185. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8186. }
  8187. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8188. SSLClient cli("google.com");
  8189. cli.enable_server_certificate_verification(true);
  8190. cli.set_ca_cert_path("hello");
  8191. auto res = cli.Get("/");
  8192. ASSERT_TRUE(!res);
  8193. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8194. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8195. // should be set
  8196. EXPECT_EQ(0, res.ssl_error());
  8197. // Verify backend error is captured for SSLLoadingCerts
  8198. // This error occurs when loading CA certificates fails
  8199. EXPECT_NE(0UL, res.ssl_backend_error());
  8200. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8201. // OpenSSL specific error codes:
  8202. // > openssl errstr 0x80000002
  8203. // error:80000002:system library::No such file or directory
  8204. // > openssl errstr 0xA000126
  8205. // error:0A000126:SSL routines::unexpected eof while reading
  8206. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8207. res.ssl_backend_error() == 0xA000126);
  8208. #endif
  8209. }
  8210. TEST(SSLClientTest, ServerCertificateVerification4) {
  8211. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8212. ASSERT_TRUE(svr.is_valid());
  8213. svr.Get("/test", [&](const Request &, Response &res) {
  8214. res.set_content("test", "text/plain");
  8215. svr.stop();
  8216. ASSERT_TRUE(true);
  8217. });
  8218. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8219. auto se = detail::scope_exit([&] {
  8220. t.join();
  8221. ASSERT_FALSE(svr.is_running());
  8222. });
  8223. svr.wait_until_ready();
  8224. SSLClient cli("127.0.0.1", PORT);
  8225. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8226. cli.enable_server_certificate_verification(true);
  8227. cli.set_connection_timeout(30);
  8228. auto res = cli.Get("/test");
  8229. ASSERT_TRUE(res);
  8230. ASSERT_EQ(StatusCode::OK_200, res->status);
  8231. }
  8232. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8233. std::string cert;
  8234. read_file(CA_CERT_FILE, cert);
  8235. SSLClient cli("google.com");
  8236. cli.load_ca_cert_store(cert.data(), cert.size());
  8237. const auto res = cli.Get("/");
  8238. ASSERT_TRUE(res);
  8239. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8240. }
  8241. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8242. // clang-format off
  8243. static constexpr char cert[] =
  8244. "GlobalSign Root CA\n"
  8245. "==================\n"
  8246. "-----BEGIN CERTIFICATE-----\n"
  8247. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8248. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8249. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8250. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8251. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8252. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8253. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8254. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8255. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8256. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8257. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8258. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8259. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8260. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8261. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8262. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8263. "-----END CERTIFICATE-----\n";
  8264. // clang-format on
  8265. SSLClient cli("google.com");
  8266. cli.load_ca_cert_store(cert, sizeof(cert));
  8267. const auto res = cli.Get("/");
  8268. ASSERT_TRUE(res);
  8269. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8270. }
  8271. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8272. SSLClient cli("www.youtube.com");
  8273. cli.set_ca_cert_path(CA_CERT_FILE);
  8274. cli.enable_server_certificate_verification(true);
  8275. cli.set_follow_location(true);
  8276. auto res = cli.Get("/");
  8277. ASSERT_TRUE(res);
  8278. ASSERT_EQ(StatusCode::OK_200, res->status);
  8279. }
  8280. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8281. SSLClient cli("wWw.YouTube.Com");
  8282. cli.set_ca_cert_path(CA_CERT_FILE);
  8283. cli.enable_server_certificate_verification(true);
  8284. cli.enable_server_hostname_verification(true);
  8285. cli.set_follow_location(true);
  8286. auto res = cli.Get("/");
  8287. ASSERT_TRUE(res);
  8288. ASSERT_EQ(StatusCode::OK_200, res->status);
  8289. }
  8290. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8291. SSLClient cli("gOoGlE.COm");
  8292. cli.enable_server_certificate_verification(true);
  8293. cli.enable_server_hostname_verification(true);
  8294. cli.set_follow_location(true);
  8295. auto res = cli.Get("/");
  8296. ASSERT_TRUE(res);
  8297. ASSERT_EQ(StatusCode::OK_200, res->status);
  8298. }
  8299. TEST(SSLClientTest, Issue2004_Online) {
  8300. Client client("https://google.com");
  8301. client.set_follow_location(true);
  8302. auto res = client.Get("/");
  8303. ASSERT_TRUE(res);
  8304. ASSERT_EQ(StatusCode::OK_200, res->status);
  8305. auto body = res->body;
  8306. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8307. }
  8308. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8309. // Create SSLClient with invalid cert/key to make is_valid() return false
  8310. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8311. "nonexistent_key.pem");
  8312. // is_valid() should be false due to cert loading failure
  8313. ASSERT_FALSE(cli.is_valid());
  8314. auto res = cli.Get("/");
  8315. ASSERT_FALSE(res);
  8316. EXPECT_EQ(Error::SSLConnection, res.error());
  8317. }
  8318. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8319. // Test for Issue #2251: SSL error not properly reported when client cert
  8320. // and key paths are swapped or mismatched
  8321. // This simulates the scenario where user accidentally swaps the cert and key
  8322. // files
  8323. // Using client cert file as private key and vice versa (completely wrong)
  8324. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8325. // Should fail validation due to cert/key mismatch
  8326. ASSERT_FALSE(cli.is_valid());
  8327. // Attempt to make a request should fail with proper error
  8328. auto res = cli.Get("/");
  8329. ASSERT_FALSE(res);
  8330. EXPECT_EQ(Error::SSLConnection, res.error());
  8331. // SSL error should be recorded in the Result object (this is the key fix for
  8332. // Issue #2251)
  8333. auto backend_error = res.ssl_backend_error();
  8334. EXPECT_NE(0u, backend_error);
  8335. }
  8336. // Tests cert/key mismatch detection at the TLS context level
  8337. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8338. // Test that using mismatched cert/key causes connection failure.
  8339. // We verify this at the SSLClient level rather than through internal
  8340. // TLS API functions.
  8341. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8342. cli.enable_server_certificate_verification(false);
  8343. cli.set_connection_timeout(2);
  8344. // The mismatch should cause a connection or handshake error
  8345. auto res = cli.Get("/test");
  8346. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8347. // Either way, the request should fail
  8348. EXPECT_FALSE(res);
  8349. }
  8350. #endif
  8351. #if 0
  8352. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8353. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8354. ASSERT_TRUE(cli != nullptr);
  8355. cli->set_address_family(AF_INET6);
  8356. cli->set_interface("en0");
  8357. auto res = cli->Get("/get");
  8358. ASSERT_TRUE(res);
  8359. ASSERT_EQ(StatusCode::OK_200, res->status);
  8360. }
  8361. #endif
  8362. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8363. #ifdef CPPHTTPLIB_SSL_ENABLED
  8364. void ClientCertPresent(
  8365. const std::string &client_cert_file,
  8366. const std::string &client_private_key_file,
  8367. const std::string &client_encrypted_private_key_pass = std::string()) {
  8368. using namespace httplib::tls;
  8369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8370. CLIENT_CA_CERT_DIR);
  8371. ASSERT_TRUE(svr.is_valid());
  8372. svr.Get("/test", [&](const Request &req, Response &res) {
  8373. res.set_content("test", "text/plain");
  8374. auto cert = req.peer_cert();
  8375. ASSERT_TRUE(static_cast<bool>(cert));
  8376. std::string common_name = cert.subject_cn();
  8377. EXPECT_EQ("Common Name", common_name);
  8378. });
  8379. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8380. auto se = detail::scope_exit([&] {
  8381. svr.stop();
  8382. t.join();
  8383. ASSERT_FALSE(svr.is_running());
  8384. });
  8385. svr.wait_until_ready();
  8386. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8387. client_encrypted_private_key_pass);
  8388. cli.enable_server_certificate_verification(false);
  8389. cli.set_connection_timeout(30);
  8390. auto res = cli.Get("/test");
  8391. ASSERT_TRUE(res);
  8392. ASSERT_EQ(StatusCode::OK_200, res->status);
  8393. }
  8394. TEST(SSLClientServerTest, ClientCertPresent) {
  8395. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8396. }
  8397. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8398. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8399. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8400. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8401. }
  8402. // PEM memory-based constructor tests (works with all TLS backends)
  8403. void PemMemoryClientCertPresent(
  8404. const std::string &client_cert_file,
  8405. const std::string &client_private_key_file,
  8406. const std::string &client_encrypted_private_key_pass = std::string()) {
  8407. // Read PEM files into memory
  8408. std::string server_cert_pem, server_key_pem;
  8409. std::string client_ca_pem;
  8410. std::string client_cert_pem, client_key_pem;
  8411. read_file(SERVER_CERT_FILE, server_cert_pem);
  8412. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8413. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8414. read_file(client_cert_file, client_cert_pem);
  8415. read_file(client_private_key_file, client_key_pem);
  8416. // Create server with PEM memory
  8417. SSLServer::PemMemory server_pem = {
  8418. server_cert_pem.c_str(),
  8419. server_cert_pem.size(),
  8420. server_key_pem.c_str(),
  8421. server_key_pem.size(),
  8422. client_ca_pem.c_str(),
  8423. client_ca_pem.size(),
  8424. nullptr // no password for server key
  8425. };
  8426. SSLServer svr(server_pem);
  8427. ASSERT_TRUE(svr.is_valid());
  8428. svr.Get("/test", [&](const Request &, Response &res) {
  8429. res.set_content("test", "text/plain");
  8430. });
  8431. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8432. auto se = detail::scope_exit([&] {
  8433. svr.stop();
  8434. t.join();
  8435. ASSERT_FALSE(svr.is_running());
  8436. });
  8437. svr.wait_until_ready();
  8438. // Create client with PEM memory
  8439. const char *password = client_encrypted_private_key_pass.empty()
  8440. ? nullptr
  8441. : client_encrypted_private_key_pass.c_str();
  8442. SSLClient::PemMemory client_pem = {
  8443. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8444. client_key_pem.size(), password};
  8445. SSLClient cli(HOST, PORT, client_pem);
  8446. cli.enable_server_certificate_verification(false);
  8447. cli.set_connection_timeout(30);
  8448. auto res = cli.Get("/test");
  8449. ASSERT_TRUE(res);
  8450. ASSERT_EQ(StatusCode::OK_200, res->status);
  8451. }
  8452. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8453. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8454. }
  8455. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8456. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8457. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8458. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8459. }
  8460. TEST(SSLClientServerTest, ClientCertMissing) {
  8461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8462. CLIENT_CA_CERT_DIR);
  8463. ASSERT_TRUE(svr.is_valid());
  8464. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8465. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8466. auto se = detail::scope_exit([&] {
  8467. svr.stop();
  8468. t.join();
  8469. ASSERT_FALSE(svr.is_running());
  8470. });
  8471. svr.wait_until_ready();
  8472. SSLClient cli(HOST, PORT);
  8473. cli.set_connection_timeout(30);
  8474. auto res = cli.Get("/test");
  8475. ASSERT_TRUE(!res);
  8476. // When client cert is missing and server requires it, connection fails
  8477. // Error type depends on backend implementation
  8478. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8479. res.error() == Error::SSLConnection);
  8480. // Verify backend error is captured
  8481. // Note: This test may have different error codes depending on the exact
  8482. // verification failure
  8483. EXPECT_NE(0UL, res.ssl_backend_error());
  8484. }
  8485. TEST(SSLClientServerTest, TrustDirOptional) {
  8486. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8487. ASSERT_TRUE(svr.is_valid());
  8488. svr.Get("/test", [&](const Request &, Response &res) {
  8489. res.set_content("test", "text/plain");
  8490. });
  8491. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8492. auto se = detail::scope_exit([&] {
  8493. svr.stop();
  8494. t.join();
  8495. ASSERT_FALSE(svr.is_running());
  8496. });
  8497. svr.wait_until_ready();
  8498. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8499. cli.enable_server_certificate_verification(false);
  8500. cli.set_connection_timeout(30);
  8501. auto res = cli.Get("/test");
  8502. ASSERT_TRUE(res);
  8503. ASSERT_EQ(StatusCode::OK_200, res->status);
  8504. }
  8505. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8506. class NoListenSSLServer : public SSLServer {
  8507. public:
  8508. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8509. const char *client_ca_cert_file_path,
  8510. const char *client_ca_cert_dir_path = nullptr)
  8511. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8512. client_ca_cert_dir_path),
  8513. stop_(false) {}
  8514. std::atomic_bool stop_;
  8515. private:
  8516. bool process_and_close_socket(socket_t /*sock*/) override {
  8517. // Don't create SSL context
  8518. while (!stop_.load()) {
  8519. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8520. }
  8521. return true;
  8522. }
  8523. };
  8524. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8525. CLIENT_CA_CERT_FILE);
  8526. ASSERT_TRUE(svr.is_valid());
  8527. svr.Get("/test", [&](const Request &, Response &res) {
  8528. res.set_content("test", "text/plain");
  8529. });
  8530. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8531. auto se = detail::scope_exit([&] {
  8532. svr.stop_ = true;
  8533. svr.stop();
  8534. t.join();
  8535. ASSERT_FALSE(svr.is_running());
  8536. });
  8537. svr.wait_until_ready();
  8538. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8539. cli.enable_server_certificate_verification(false);
  8540. cli.set_connection_timeout(1);
  8541. auto res = cli.Get("/test");
  8542. ASSERT_TRUE(!res);
  8543. EXPECT_EQ(Error::SSLConnection, res.error());
  8544. // Timeout results in WantRead error code (maps to backend-specific value)
  8545. EXPECT_NE(0, res.ssl_error());
  8546. }
  8547. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8548. // Test SSLServer with client certificate verification using the standard
  8549. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8551. CLIENT_CA_CERT_DIR);
  8552. ASSERT_TRUE(svr.is_valid());
  8553. svr.Get("/test", [&](const Request &req, Response &res) {
  8554. res.set_content("test", "text/plain");
  8555. auto cert = req.peer_cert();
  8556. ASSERT_TRUE(static_cast<bool>(cert));
  8557. auto common_name = cert.subject_cn();
  8558. EXPECT_EQ("Common Name", common_name);
  8559. });
  8560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8561. auto se = detail::scope_exit([&] {
  8562. svr.stop();
  8563. t.join();
  8564. ASSERT_FALSE(svr.is_running());
  8565. });
  8566. svr.wait_until_ready();
  8567. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8568. cli.enable_server_certificate_verification(false);
  8569. cli.set_connection_timeout(30);
  8570. auto res = cli.Get("/test");
  8571. ASSERT_TRUE(res);
  8572. ASSERT_EQ(StatusCode::OK_200, res->status);
  8573. }
  8574. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8575. // Verifies that wildcard matching and exact matching work consistently
  8576. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8577. using namespace httplib::tls;
  8578. // We need a running server to test against
  8579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8580. ASSERT_TRUE(svr.is_valid());
  8581. svr.Get("/test", [](const Request &, Response &res) {
  8582. res.set_content("ok", "text/plain");
  8583. });
  8584. thread t([&]() { svr.listen(HOST, PORT); });
  8585. auto se = detail::scope_exit([&] {
  8586. svr.stop();
  8587. t.join();
  8588. });
  8589. svr.wait_until_ready();
  8590. bool verify_callback_called = false;
  8591. bool verify_result_wrong = false;
  8592. SSLClient cli(HOST, PORT);
  8593. cli.enable_server_certificate_verification(true);
  8594. cli.set_ca_cert_path(CA_CERT_FILE);
  8595. cli.set_connection_timeout(5);
  8596. // Note: Test certificate has CN="Common Name", not "localhost"
  8597. bool verify_result_cn = false;
  8598. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8599. verify_callback_called = true;
  8600. if (!ctx.cert) return false;
  8601. // Test 1: "Common Name" should match (our test server cert CN)
  8602. verify_result_cn = ctx.check_hostname("Common Name");
  8603. // Test 2: wrong hostname should not match
  8604. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8605. return true; // Accept for the purpose of this test
  8606. });
  8607. auto res = cli.Get("/test");
  8608. // The request may succeed or fail depending on cert configuration
  8609. // but the callback should have been called
  8610. ASSERT_TRUE(verify_callback_called)
  8611. << "Verify callback should have been called";
  8612. // CN="Common Name" should match our test certificate
  8613. EXPECT_TRUE(verify_result_cn)
  8614. << "verify_hostname should match 'Common Name' (certificate CN)";
  8615. // Wrong hostname should not match
  8616. EXPECT_FALSE(verify_result_wrong)
  8617. << "verify_hostname should not match 'wronghost.example.com'";
  8618. }
  8619. #endif
  8620. // mbedTLS-specific callback constructor test
  8621. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8622. #ifdef CPPHTTPLIB_SSL_ENABLED
  8623. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8625. ASSERT_TRUE(svr.is_valid());
  8626. // Set up a handler to verify client certificate is present
  8627. bool client_cert_verified = false;
  8628. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8629. // Verify that client certificate was provided
  8630. client_cert_verified = true;
  8631. res.set_content("success", "text/plain");
  8632. });
  8633. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8634. auto se = detail::scope_exit([&] {
  8635. svr.stop();
  8636. t.join();
  8637. ASSERT_FALSE(svr.is_running());
  8638. });
  8639. svr.wait_until_ready();
  8640. // Client with certificate
  8641. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8642. cli.enable_server_certificate_verification(false);
  8643. cli.set_connection_timeout(30);
  8644. auto res = cli.Get("/test");
  8645. ASSERT_TRUE(res);
  8646. ASSERT_EQ(StatusCode::OK_200, res->status);
  8647. ASSERT_TRUE(client_cert_verified);
  8648. EXPECT_EQ("success", res->body);
  8649. }
  8650. #endif
  8651. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8652. // backends
  8653. #ifdef CPPHTTPLIB_SSL_ENABLED
  8654. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8655. using namespace httplib::tls;
  8656. // Test that when client CA cert file is provided,
  8657. // the server properly requests and validates client certificates
  8658. // Create a server with client authentication
  8659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8660. ASSERT_TRUE(svr.is_valid());
  8661. bool handler_called = false;
  8662. svr.Get("/test", [&](const Request &req, Response &res) {
  8663. handler_called = true;
  8664. // Verify that a client certificate was provided
  8665. auto cert = req.peer_cert();
  8666. ASSERT_TRUE(static_cast<bool>(cert));
  8667. // Get the issuer name
  8668. std::string issuer_str = cert.issuer_name();
  8669. ASSERT_FALSE(issuer_str.empty());
  8670. // The client certificate should be issued by our test CA
  8671. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8672. res.set_content("authenticated", "text/plain");
  8673. });
  8674. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8675. auto se = detail::scope_exit([&] {
  8676. svr.stop();
  8677. t.join();
  8678. ASSERT_FALSE(svr.is_running());
  8679. });
  8680. svr.wait_until_ready();
  8681. // Connect with a client certificate issued by the CA
  8682. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8683. cli.enable_server_certificate_verification(false);
  8684. cli.set_connection_timeout(30);
  8685. auto res = cli.Get("/test");
  8686. ASSERT_TRUE(res);
  8687. ASSERT_EQ(StatusCode::OK_200, res->status);
  8688. ASSERT_TRUE(handler_called);
  8689. EXPECT_EQ("authenticated", res->body);
  8690. }
  8691. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8692. using namespace httplib::tls;
  8693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8694. ASSERT_TRUE(svr.is_valid());
  8695. svr.Get("/test", [](const Request &, Response &res) {
  8696. res.set_content("ok", "text/plain");
  8697. });
  8698. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8699. auto se = detail::scope_exit([&] {
  8700. svr.stop();
  8701. t.join();
  8702. });
  8703. svr.wait_until_ready();
  8704. SSLClient cli(HOST, PORT);
  8705. cli.enable_server_certificate_verification(false);
  8706. cli.set_connection_timeout(30);
  8707. bool cert_checked = false;
  8708. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8709. if (ctx.cert) {
  8710. auto sans = ctx.sans();
  8711. // Test certificate may or may not have SANs - just verify the API
  8712. // works If SANs exist, verify the types are valid
  8713. for (const auto &san : sans) {
  8714. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8715. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8716. san.type == SanType::OTHER);
  8717. EXPECT_FALSE(san.value.empty());
  8718. }
  8719. cert_checked = true;
  8720. }
  8721. return true;
  8722. });
  8723. auto res = cli.Get("/test");
  8724. ASSERT_TRUE(res);
  8725. EXPECT_TRUE(cert_checked);
  8726. }
  8727. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8728. using namespace httplib::tls;
  8729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8730. ASSERT_TRUE(svr.is_valid());
  8731. svr.Get("/test", [](const Request &, Response &res) {
  8732. res.set_content("ok", "text/plain");
  8733. });
  8734. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8735. auto se = detail::scope_exit([&] {
  8736. svr.stop();
  8737. t.join();
  8738. });
  8739. svr.wait_until_ready();
  8740. SSLClient cli(HOST, PORT);
  8741. cli.enable_server_certificate_verification(false);
  8742. cli.set_connection_timeout(30);
  8743. bool validity_checked = false;
  8744. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8745. if (ctx.cert) {
  8746. time_t not_before = 0, not_after = 0;
  8747. bool result = ctx.validity(not_before, not_after);
  8748. EXPECT_TRUE(result);
  8749. // Verify that not_before < now < not_after for a valid cert
  8750. time_t now = time(nullptr);
  8751. EXPECT_LT(not_before, now);
  8752. EXPECT_GT(not_after, now);
  8753. validity_checked = true;
  8754. }
  8755. return true;
  8756. });
  8757. auto res = cli.Get("/test");
  8758. ASSERT_TRUE(res);
  8759. EXPECT_TRUE(validity_checked);
  8760. }
  8761. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8762. using namespace httplib::tls;
  8763. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8764. ASSERT_TRUE(svr.is_valid());
  8765. svr.Get("/test", [](const Request &, Response &res) {
  8766. res.set_content("ok", "text/plain");
  8767. });
  8768. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8769. auto se = detail::scope_exit([&] {
  8770. svr.stop();
  8771. t.join();
  8772. });
  8773. svr.wait_until_ready();
  8774. SSLClient cli(HOST, PORT);
  8775. cli.enable_server_certificate_verification(false);
  8776. cli.set_connection_timeout(30);
  8777. bool serial_checked = false;
  8778. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8779. if (ctx.cert) {
  8780. std::string serial = ctx.serial();
  8781. EXPECT_FALSE(serial.empty());
  8782. // Serial should be a hex string
  8783. for (char c : serial) {
  8784. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8785. (c >= 'a' && c <= 'f'));
  8786. }
  8787. serial_checked = true;
  8788. }
  8789. return true;
  8790. });
  8791. auto res = cli.Get("/test");
  8792. ASSERT_TRUE(res);
  8793. EXPECT_TRUE(serial_checked);
  8794. }
  8795. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8796. // Test 1: Valid CA file - no error should be recorded
  8797. {
  8798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8799. CLIENT_CA_CERT_FILE);
  8800. ASSERT_TRUE(svr.is_valid());
  8801. // With valid setup, last_ssl_error should be 0
  8802. EXPECT_EQ(0, svr.ssl_last_error());
  8803. }
  8804. // Test 2: Invalid CA file content
  8805. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8806. {
  8807. // Create a temporary file with completely invalid content
  8808. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8809. {
  8810. std::ofstream ofs(temp_invalid_ca);
  8811. ofs << "This is not a certificate file at all\n";
  8812. ofs << "Just plain text content\n";
  8813. }
  8814. // Create server with invalid CA file
  8815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8816. // Clean up temporary file
  8817. std::remove(temp_invalid_ca);
  8818. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8819. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8820. // Note: SSL_CTX_load_verify_locations typically fails first,
  8821. // but our error handling code path is still exercised
  8822. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8823. }
  8824. }
  8825. TEST(VerifyCallbackTest, VerifyContextFields) {
  8826. using namespace httplib::tls;
  8827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8828. ASSERT_TRUE(svr.is_valid());
  8829. svr.Get("/test", [](const Request &, Response &res) {
  8830. res.set_content("ok", "text/plain");
  8831. });
  8832. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8833. auto se = detail::scope_exit([&] {
  8834. svr.stop();
  8835. t.join();
  8836. });
  8837. svr.wait_until_ready();
  8838. SSLClient cli(HOST, PORT);
  8839. cli.enable_server_certificate_verification(false);
  8840. cli.set_connection_timeout(30);
  8841. int callback_count = 0;
  8842. bool saw_leaf_cert = false;
  8843. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8844. if (ctx.cert) {
  8845. callback_count++;
  8846. // We should see at least one certificate (the leaf)
  8847. std::string cn = ctx.subject_cn();
  8848. if (!cn.empty()) { saw_leaf_cert = true; }
  8849. // Verify context fields are populated
  8850. EXPECT_NE(ctx.session, nullptr);
  8851. EXPECT_GE(ctx.depth, 0);
  8852. }
  8853. return true;
  8854. });
  8855. auto res = cli.Get("/test");
  8856. ASSERT_TRUE(res);
  8857. EXPECT_GT(callback_count, 0);
  8858. EXPECT_TRUE(saw_leaf_cert);
  8859. }
  8860. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8861. using httplib::tls::TlsError;
  8862. // Test that verify_error_to_string returns empty for success
  8863. std::string success_str = TlsError::verify_error_to_string(0);
  8864. EXPECT_TRUE(success_str.empty());
  8865. // Test that verify_error_to_string returns non-empty for error codes
  8866. // Using a common error code (certificate expired)
  8867. std::string error_str =
  8868. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8869. EXPECT_FALSE(error_str.empty());
  8870. }
  8871. TEST(SessionVerifierTest, CertificateAccepted) {
  8872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8873. ASSERT_TRUE(svr.is_valid());
  8874. svr.Get("/test", [](const Request &, Response &res) {
  8875. res.set_content("ok", "text/plain");
  8876. });
  8877. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8878. auto se = detail::scope_exit([&] {
  8879. svr.stop();
  8880. t.join();
  8881. });
  8882. svr.wait_until_ready();
  8883. SSLClient cli(HOST, PORT);
  8884. cli.enable_server_certificate_verification(false);
  8885. cli.set_connection_timeout(30);
  8886. bool callback_called = false;
  8887. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8888. EXPECT_NE(session, nullptr);
  8889. callback_called = true;
  8890. return SSLVerifierResponse::CertificateAccepted;
  8891. });
  8892. auto res = cli.Get("/test");
  8893. ASSERT_TRUE(res);
  8894. EXPECT_EQ(200, res->status);
  8895. EXPECT_TRUE(callback_called);
  8896. }
  8897. TEST(SessionVerifierTest, CertificateRejected) {
  8898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8899. ASSERT_TRUE(svr.is_valid());
  8900. svr.Get("/test", [](const Request &, Response &res) {
  8901. res.set_content("ok", "text/plain");
  8902. });
  8903. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8904. auto se = detail::scope_exit([&] {
  8905. svr.stop();
  8906. t.join();
  8907. });
  8908. svr.wait_until_ready();
  8909. SSLClient cli(HOST, PORT);
  8910. cli.enable_server_certificate_verification(false);
  8911. cli.set_connection_timeout(30);
  8912. bool callback_called = false;
  8913. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8914. EXPECT_NE(session, nullptr);
  8915. callback_called = true;
  8916. return SSLVerifierResponse::CertificateRejected;
  8917. });
  8918. auto res = cli.Get("/test");
  8919. EXPECT_FALSE(res);
  8920. EXPECT_TRUE(callback_called);
  8921. }
  8922. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8923. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8924. ASSERT_TRUE(svr.is_valid());
  8925. svr.Get("/test", [](const Request &, Response &res) {
  8926. res.set_content("ok", "text/plain");
  8927. });
  8928. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8929. auto se = detail::scope_exit([&] {
  8930. svr.stop();
  8931. t.join();
  8932. });
  8933. svr.wait_until_ready();
  8934. // NoDecisionMade with verification disabled should succeed (no default check)
  8935. SSLClient cli(HOST, PORT);
  8936. cli.enable_server_certificate_verification(false);
  8937. cli.set_connection_timeout(30);
  8938. bool callback_called = false;
  8939. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8940. EXPECT_NE(session, nullptr);
  8941. callback_called = true;
  8942. return SSLVerifierResponse::NoDecisionMade;
  8943. });
  8944. auto res = cli.Get("/test");
  8945. ASSERT_TRUE(res);
  8946. EXPECT_EQ(200, res->status);
  8947. EXPECT_TRUE(callback_called);
  8948. }
  8949. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8950. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8951. ASSERT_TRUE(svr.is_valid());
  8952. svr.Get("/test", [](const Request &, Response &res) {
  8953. res.set_content("ok", "text/plain");
  8954. });
  8955. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8956. auto se = detail::scope_exit([&] {
  8957. svr.stop();
  8958. t.join();
  8959. });
  8960. svr.wait_until_ready();
  8961. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8962. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8963. // so we only check that the request fails, not whether the callback was
  8964. // called.
  8965. SSLClient cli(HOST, PORT);
  8966. cli.enable_server_certificate_verification(true);
  8967. cli.set_connection_timeout(30);
  8968. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8969. EXPECT_NE(session, nullptr);
  8970. return SSLVerifierResponse::NoDecisionMade;
  8971. });
  8972. auto res = cli.Get("/test");
  8973. EXPECT_FALSE(res);
  8974. }
  8975. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8976. // Test SSL server using PemMemory constructor with client CA certificates
  8977. // Read PEM files
  8978. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8979. read_file(SERVER_CERT_FILE, server_cert_pem);
  8980. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8981. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8982. // Create SSLServer with PemMemory constructor including client CA
  8983. SSLServer::PemMemory server_pem = {
  8984. server_cert_pem.c_str(),
  8985. server_cert_pem.size(),
  8986. server_key_pem.c_str(),
  8987. server_key_pem.size(),
  8988. client_ca_pem.c_str(),
  8989. client_ca_pem.size(),
  8990. nullptr // no password for server key
  8991. };
  8992. SSLServer svr(server_pem);
  8993. ASSERT_TRUE(svr.is_valid());
  8994. // No SSL error should be recorded for valid setup
  8995. EXPECT_EQ(0, svr.ssl_last_error());
  8996. // Set up server endpoints
  8997. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8998. res.set_content("ok", "text/plain");
  8999. });
  9000. // Start server in a thread
  9001. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9002. svr.wait_until_ready();
  9003. // Connect with client certificate (using constructor with paths)
  9004. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9005. cli.enable_server_certificate_verification(false);
  9006. auto res = cli.Get("/test-pem-ca");
  9007. ASSERT_TRUE(res);
  9008. EXPECT_EQ(200, res->status);
  9009. EXPECT_EQ("ok", res->body);
  9010. svr.stop();
  9011. server_thread.join();
  9012. }
  9013. #endif
  9014. #ifdef _WIN32
  9015. TEST(CleanupTest, WSACleanup) {
  9016. int ret = WSACleanup();
  9017. ASSERT_EQ(0, ret);
  9018. }
  9019. #endif
  9020. #ifndef CPPHTTPLIB_SSL_ENABLED
  9021. TEST(NoSSLSupport, SimpleInterface) {
  9022. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9023. }
  9024. #endif
  9025. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9026. TEST(InvalidScheme, SimpleInterface) {
  9027. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9028. }
  9029. #endif
  9030. TEST(NoScheme, SimpleInterface) {
  9031. Client cli("yahoo.com:80");
  9032. ASSERT_TRUE(cli.is_valid());
  9033. }
  9034. TEST(SendAPI, SimpleInterface_Online) {
  9035. Client cli("http://yahoo.com");
  9036. Request req;
  9037. req.method = "GET";
  9038. req.path = "/";
  9039. auto res = cli.send(req);
  9040. ASSERT_TRUE(res);
  9041. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9042. }
  9043. TEST(SendAPI, WithParamsInRequest) {
  9044. Server svr;
  9045. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9046. EXPECT_TRUE(req.has_param("test"));
  9047. EXPECT_EQ("test_value", req.get_param_value("test"));
  9048. });
  9049. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9050. auto se = detail::scope_exit([&] {
  9051. svr.stop();
  9052. t.join();
  9053. ASSERT_FALSE(svr.is_running());
  9054. });
  9055. svr.wait_until_ready();
  9056. Client cli(HOST, PORT);
  9057. {
  9058. Request req;
  9059. req.method = "GET";
  9060. req.path = "/";
  9061. req.params.emplace("test", "test_value");
  9062. auto res = cli.send(req);
  9063. ASSERT_TRUE(res);
  9064. }
  9065. {
  9066. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9067. ASSERT_TRUE(res);
  9068. }
  9069. }
  9070. TEST(ClientImplMethods, GetSocketTest) {
  9071. httplib::Server svr;
  9072. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9073. res.status = StatusCode::OK_200;
  9074. });
  9075. auto port = svr.bind_to_any_port("127.0.0.1");
  9076. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9077. auto se = detail::scope_exit([&] {
  9078. svr.stop();
  9079. thread.join();
  9080. ASSERT_FALSE(svr.is_running());
  9081. });
  9082. svr.wait_until_ready();
  9083. {
  9084. httplib::Client cli("127.0.0.1", port);
  9085. cli.set_keep_alive(true);
  9086. // Use the behavior of cpp-httplib of opening the connection
  9087. // only when the first request happens. If that changes,
  9088. // this test would be obsolete.
  9089. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9090. // This also implicitly tests the server. But other tests would fail much
  9091. // earlier than this one to be considered.
  9092. auto res = cli.Get("/");
  9093. ASSERT_TRUE(res);
  9094. EXPECT_EQ(StatusCode::OK_200, res->status);
  9095. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9096. }
  9097. }
  9098. #ifdef CPPHTTPLIB_SSL_ENABLED
  9099. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9100. Client cli("http://yahoo.com");
  9101. auto res = cli.Get("/");
  9102. ASSERT_TRUE(res);
  9103. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9104. cli.set_follow_location(true);
  9105. res = cli.Get("/");
  9106. ASSERT_TRUE(res);
  9107. EXPECT_EQ(StatusCode::OK_200, res->status);
  9108. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9109. }
  9110. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9111. Client cli("https://yahoo.com");
  9112. auto res = cli.Get("/");
  9113. ASSERT_TRUE(res);
  9114. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9115. cli.set_follow_location(true);
  9116. res = cli.Get("/");
  9117. ASSERT_TRUE(res);
  9118. EXPECT_EQ(StatusCode::OK_200, res->status);
  9119. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9120. }
  9121. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9122. Client cli("https://yahoo.com");
  9123. auto res = cli.Get("/");
  9124. ASSERT_TRUE(res);
  9125. ASSERT_FALSE(!res);
  9126. ASSERT_TRUE(res);
  9127. ASSERT_FALSE(res == nullptr);
  9128. ASSERT_TRUE(res != nullptr);
  9129. EXPECT_EQ(Error::Success, res.error());
  9130. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9131. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9132. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9133. cli.set_follow_location(true);
  9134. res = cli.Get("/");
  9135. ASSERT_TRUE(res);
  9136. EXPECT_EQ(Error::Success, res.error());
  9137. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9138. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9139. EXPECT_EQ(StatusCode::OK_200, res->status);
  9140. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9141. }
  9142. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9143. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9144. Client cli("https://cdnjs.cloudflare.com");
  9145. auto res =
  9146. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9147. ASSERT_TRUE(res);
  9148. EXPECT_EQ(StatusCode::OK_200, res->status);
  9149. EXPECT_EQ(287630U, res->body.size());
  9150. EXPECT_EQ("application/javascript; charset=utf-8",
  9151. res->get_header_value("Content-Type"));
  9152. }
  9153. #endif
  9154. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9155. #undef REDIR_HOST // Silence compiler warning
  9156. #define REDIR_HOST "https://httpbingo.org"
  9157. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9158. Client cli(REDIR_HOST);
  9159. cli.set_follow_location(true);
  9160. auto res =
  9161. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9162. ASSERT_TRUE(res);
  9163. EXPECT_EQ(StatusCode::OK_200, res->status);
  9164. }
  9165. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9166. Client cli(REDIR_HOST);
  9167. cli.set_follow_location(true);
  9168. Params params;
  9169. params.emplace("url", "http://example.com");
  9170. params.emplace("status_code", "302");
  9171. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9172. ASSERT_TRUE(res);
  9173. EXPECT_EQ(StatusCode::OK_200, res->status);
  9174. }
  9175. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9176. Client cli(REDIR_HOST);
  9177. cli.set_follow_location(true);
  9178. Params params;
  9179. params.emplace("url", "http://example.com");
  9180. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9181. ASSERT_TRUE(res);
  9182. EXPECT_EQ(StatusCode::OK_200, res->status);
  9183. }
  9184. TEST(HttpToHttpsRedirectTest, CertFile) {
  9185. auto ssl_port = PORT + 1;
  9186. Server svr;
  9187. ASSERT_TRUE(svr.is_valid());
  9188. svr.Get("/index", [&](const Request &, Response &res) {
  9189. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9190. "/index");
  9191. svr.stop();
  9192. });
  9193. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9194. ASSERT_TRUE(ssl_svr.is_valid());
  9195. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9196. res.set_content("test", "text/plain");
  9197. ssl_svr.stop();
  9198. });
  9199. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9200. thread t2 =
  9201. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9202. auto se = detail::scope_exit([&] {
  9203. t2.join();
  9204. t.join();
  9205. ASSERT_FALSE(svr.is_running());
  9206. });
  9207. svr.wait_until_ready();
  9208. ssl_svr.wait_until_ready();
  9209. Client cli("127.0.0.1", PORT);
  9210. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9211. cli.enable_server_certificate_verification(true);
  9212. cli.set_follow_location(true);
  9213. cli.set_connection_timeout(30);
  9214. auto res = cli.Get("/index");
  9215. ASSERT_TRUE(res);
  9216. ASSERT_EQ(StatusCode::OK_200, res->status);
  9217. }
  9218. TEST(SSLClientRedirectTest, CertFile) {
  9219. auto ssl_port = PORT + 1;
  9220. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9221. ASSERT_TRUE(ssl_svr1.is_valid());
  9222. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9223. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9224. "/index");
  9225. ssl_svr1.stop();
  9226. });
  9227. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9228. ASSERT_TRUE(ssl_svr2.is_valid());
  9229. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9230. res.set_content("test", "text/plain");
  9231. ssl_svr2.stop();
  9232. });
  9233. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9234. thread t2 =
  9235. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9236. auto se = detail::scope_exit([&] {
  9237. t2.join();
  9238. t.join();
  9239. ASSERT_FALSE(ssl_svr1.is_running());
  9240. });
  9241. ssl_svr1.wait_until_ready();
  9242. ssl_svr2.wait_until_ready();
  9243. SSLClient cli("127.0.0.1", PORT);
  9244. std::string cert;
  9245. read_file(SERVER_CERT2_FILE, cert);
  9246. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9247. cli.enable_server_certificate_verification(true);
  9248. cli.set_follow_location(true);
  9249. cli.set_connection_timeout(30);
  9250. auto res = cli.Get("/index");
  9251. ASSERT_TRUE(res);
  9252. ASSERT_EQ(StatusCode::OK_200, res->status);
  9253. }
  9254. #endif
  9255. #ifdef CPPHTTPLIB_SSL_ENABLED
  9256. // Test that set_ca_cert_store() skips system certs (consistent with
  9257. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9258. // should be trusted - system certs should NOT be loaded.
  9259. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9260. // Load a specific cert that is NOT a system CA cert
  9261. std::string cert;
  9262. read_file(SERVER_CERT2_FILE, cert);
  9263. SSLClient cli("google.com");
  9264. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9265. cli.enable_server_certificate_verification(true);
  9266. // This should FAIL because:
  9267. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9268. // 2. System certs should NOT be loaded when custom store is set
  9269. // If system certs WERE loaded, this would succeed
  9270. auto res = cli.Get("/");
  9271. ASSERT_FALSE(res);
  9272. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9273. }
  9274. TEST(MultipartFormDataTest, LargeData) {
  9275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9276. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9277. const ContentReader &content_reader) {
  9278. if (req.is_multipart_form_data()) {
  9279. std::vector<FormData> items;
  9280. content_reader(
  9281. [&](const FormData &file) {
  9282. items.push_back(file);
  9283. return true;
  9284. },
  9285. [&](const char *data, size_t data_length) {
  9286. items.back().content.append(data, data_length);
  9287. return true;
  9288. });
  9289. EXPECT_TRUE(std::string(items[0].name) == "document");
  9290. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9291. EXPECT_TRUE(items[0].filename == "2MB_data");
  9292. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9293. EXPECT_TRUE(items[1].name == "hello");
  9294. EXPECT_TRUE(items[1].content == "world");
  9295. EXPECT_TRUE(items[1].filename == "");
  9296. EXPECT_TRUE(items[1].content_type == "");
  9297. } else {
  9298. std::string body;
  9299. content_reader([&](const char *data, size_t data_length) {
  9300. body.append(data, data_length);
  9301. return true;
  9302. });
  9303. }
  9304. });
  9305. auto port = svr.bind_to_any_port(HOST);
  9306. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9307. auto se = detail::scope_exit([&] {
  9308. svr.stop();
  9309. t.join();
  9310. ASSERT_FALSE(svr.is_running());
  9311. });
  9312. svr.wait_until_ready();
  9313. {
  9314. std::string data(1024 * 1024 * 2, '.');
  9315. std::stringstream buffer;
  9316. buffer << data;
  9317. SSLClient cli(HOST, port);
  9318. cli.enable_server_certificate_verification(false);
  9319. UploadFormDataItems items{
  9320. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9321. {"hello", "world", "", ""},
  9322. };
  9323. auto res = cli.Post("/post", items);
  9324. ASSERT_TRUE(res);
  9325. ASSERT_EQ(StatusCode::OK_200, res->status);
  9326. }
  9327. }
  9328. TEST(MultipartFormDataTest, DataProviderItems) {
  9329. std::random_device seed_gen;
  9330. std::mt19937 random(seed_gen());
  9331. std::string rand1;
  9332. rand1.resize(1000);
  9333. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9334. std::string rand2;
  9335. rand2.resize(3000);
  9336. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9337. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9338. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9339. const ContentReader &content_reader) {
  9340. ASSERT_FALSE(req.is_multipart_form_data());
  9341. std::string body;
  9342. content_reader([&](const char *data, size_t data_length) {
  9343. body.append(data, data_length);
  9344. return true;
  9345. });
  9346. EXPECT_EQ(body, "");
  9347. });
  9348. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9349. const ContentReader &content_reader) {
  9350. ASSERT_TRUE(req.is_multipart_form_data());
  9351. std::vector<FormData> items;
  9352. content_reader(
  9353. [&](const FormData &file) {
  9354. items.push_back(file);
  9355. return true;
  9356. },
  9357. [&](const char *data, size_t data_length) {
  9358. items.back().content.append(data, data_length);
  9359. return true;
  9360. });
  9361. ASSERT_TRUE(items.size() == 2);
  9362. EXPECT_EQ(std::string(items[0].name), "name1");
  9363. EXPECT_EQ(items[0].content, "Testing123");
  9364. EXPECT_EQ(items[0].filename, "filename1");
  9365. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9366. EXPECT_EQ(items[1].name, "name2");
  9367. EXPECT_EQ(items[1].content, "Testing456");
  9368. EXPECT_EQ(items[1].filename, "");
  9369. EXPECT_EQ(items[1].content_type, "");
  9370. });
  9371. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9372. const ContentReader &content_reader) {
  9373. ASSERT_TRUE(req.is_multipart_form_data());
  9374. std::vector<FormData> items;
  9375. content_reader(
  9376. [&](const FormData &file) {
  9377. items.push_back(file);
  9378. return true;
  9379. },
  9380. [&](const char *data, size_t data_length) {
  9381. items.back().content.append(data, data_length);
  9382. return true;
  9383. });
  9384. ASSERT_TRUE(items.size() == 2);
  9385. EXPECT_EQ(items[0].name, "name3");
  9386. EXPECT_EQ(items[0].content, rand1);
  9387. EXPECT_EQ(items[0].filename, "filename3");
  9388. EXPECT_EQ(items[0].content_type, "");
  9389. EXPECT_EQ(items[1].name, "name4");
  9390. EXPECT_EQ(items[1].content, rand2);
  9391. EXPECT_EQ(items[1].filename, "filename4");
  9392. EXPECT_EQ(items[1].content_type, "");
  9393. });
  9394. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9395. const ContentReader &content_reader) {
  9396. ASSERT_TRUE(req.is_multipart_form_data());
  9397. std::vector<FormData> items;
  9398. content_reader(
  9399. [&](const FormData &file) {
  9400. items.push_back(file);
  9401. return true;
  9402. },
  9403. [&](const char *data, size_t data_length) {
  9404. items.back().content.append(data, data_length);
  9405. return true;
  9406. });
  9407. ASSERT_TRUE(items.size() == 4);
  9408. EXPECT_EQ(std::string(items[0].name), "name1");
  9409. EXPECT_EQ(items[0].content, "Testing123");
  9410. EXPECT_EQ(items[0].filename, "filename1");
  9411. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9412. EXPECT_EQ(items[1].name, "name2");
  9413. EXPECT_EQ(items[1].content, "Testing456");
  9414. EXPECT_EQ(items[1].filename, "");
  9415. EXPECT_EQ(items[1].content_type, "");
  9416. EXPECT_EQ(items[2].name, "name3");
  9417. EXPECT_EQ(items[2].content, rand1);
  9418. EXPECT_EQ(items[2].filename, "filename3");
  9419. EXPECT_EQ(items[2].content_type, "");
  9420. EXPECT_EQ(items[3].name, "name4");
  9421. EXPECT_EQ(items[3].content, rand2);
  9422. EXPECT_EQ(items[3].filename, "filename4");
  9423. EXPECT_EQ(items[3].content_type, "");
  9424. });
  9425. auto port = svr.bind_to_any_port("localhost");
  9426. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9427. auto se = detail::scope_exit([&] {
  9428. svr.stop();
  9429. t.join();
  9430. ASSERT_FALSE(svr.is_running());
  9431. });
  9432. svr.wait_until_ready();
  9433. {
  9434. SSLClient cli("localhost", port);
  9435. cli.enable_server_certificate_verification(false);
  9436. UploadFormDataItems items{
  9437. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9438. {"name2", "Testing456", "", ""}, // not a file
  9439. };
  9440. {
  9441. auto res = cli.Post("/post-none", {}, {}, {});
  9442. ASSERT_TRUE(res);
  9443. ASSERT_EQ(StatusCode::OK_200, res->status);
  9444. }
  9445. FormDataProviderItems providers;
  9446. {
  9447. auto res =
  9448. cli.Post("/post-items", {}, items, providers); // empty providers
  9449. ASSERT_TRUE(res);
  9450. ASSERT_EQ(StatusCode::OK_200, res->status);
  9451. }
  9452. providers.push_back({"name3",
  9453. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9454. // test the offset is given correctly at each step
  9455. if (!offset)
  9456. sink.os.write(rand1.data(), 30);
  9457. else if (offset == 30)
  9458. sink.os.write(rand1.data() + 30, 300);
  9459. else if (offset == 330)
  9460. sink.os.write(rand1.data() + 330, 670);
  9461. else if (offset == rand1.size())
  9462. sink.done();
  9463. return true;
  9464. },
  9465. "filename3",
  9466. {}});
  9467. providers.push_back({"name4",
  9468. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9469. // test the offset is given correctly at each step
  9470. if (!offset)
  9471. sink.os.write(rand2.data(), 2000);
  9472. else if (offset == 2000)
  9473. sink.os.write(rand2.data() + 2000, 1);
  9474. else if (offset == 2001)
  9475. sink.os.write(rand2.data() + 2001, 999);
  9476. else if (offset == rand2.size())
  9477. sink.done();
  9478. return true;
  9479. },
  9480. "filename4",
  9481. {}});
  9482. {
  9483. auto res = cli.Post("/post-providers", {}, {}, providers);
  9484. ASSERT_TRUE(res);
  9485. ASSERT_EQ(StatusCode::OK_200, res->status);
  9486. }
  9487. {
  9488. auto res = cli.Post("/post-both", {}, items, providers);
  9489. ASSERT_TRUE(res);
  9490. ASSERT_EQ(StatusCode::OK_200, res->status);
  9491. }
  9492. }
  9493. }
  9494. TEST(MultipartFormDataTest, BadHeader) {
  9495. Server svr;
  9496. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9497. res.set_content("ok", "text/plain");
  9498. });
  9499. thread t = thread([&] { svr.listen(HOST, PORT); });
  9500. auto se = detail::scope_exit([&] {
  9501. svr.stop();
  9502. t.join();
  9503. ASSERT_FALSE(svr.is_running());
  9504. });
  9505. svr.wait_until_ready();
  9506. const std::string body =
  9507. "This is the preamble. It is to be ignored, though it\r\n"
  9508. "is a handy place for composition agents to include an\r\n"
  9509. "explanatory note to non-MIME conformant readers.\r\n"
  9510. "\r\n"
  9511. "\r\n"
  9512. "--simple boundary\r\n"
  9513. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9514. ": BAD...\r\n"
  9515. "\r\n"
  9516. "value1\r\n"
  9517. "--simple boundary\r\n"
  9518. "Content-Disposition: form-data; name=\"field2\"; "
  9519. "filename=\"example.txt\"\r\n"
  9520. "\r\n"
  9521. "value2\r\n"
  9522. "--simple boundary--\r\n"
  9523. "This is the epilogue. It is also to be ignored.\r\n";
  9524. std::string content_type =
  9525. R"(multipart/form-data; boundary="simple boundary")";
  9526. Client cli(HOST, PORT);
  9527. auto res = cli.Post("/post", body, content_type.c_str());
  9528. ASSERT_TRUE(res);
  9529. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9530. }
  9531. TEST(MultipartFormDataTest, WithPreamble) {
  9532. Server svr;
  9533. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9534. res.set_content("ok", "text/plain");
  9535. });
  9536. thread t = thread([&] { svr.listen(HOST, PORT); });
  9537. auto se = detail::scope_exit([&] {
  9538. svr.stop();
  9539. t.join();
  9540. ASSERT_FALSE(svr.is_running());
  9541. });
  9542. svr.wait_until_ready();
  9543. const std::string body =
  9544. "This is the preamble. It is to be ignored, though it\r\n"
  9545. "is a handy place for composition agents to include an\r\n"
  9546. "explanatory note to non-MIME conformant readers.\r\n"
  9547. "\r\n"
  9548. "\r\n"
  9549. "--simple boundary\r\n"
  9550. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9551. "\r\n"
  9552. "value1\r\n"
  9553. "--simple boundary\r\n"
  9554. "Content-Disposition: form-data; name=\"field2\"; "
  9555. "filename=\"example.txt\"\r\n"
  9556. "\r\n"
  9557. "value2\r\n"
  9558. "--simple boundary--\r\n"
  9559. "This is the epilogue. It is also to be ignored.\r\n";
  9560. std::string content_type =
  9561. R"(multipart/form-data; boundary="simple boundary")";
  9562. Client cli(HOST, PORT);
  9563. auto res = cli.Post("/post", body, content_type.c_str());
  9564. ASSERT_TRUE(res);
  9565. EXPECT_EQ(StatusCode::OK_200, res->status);
  9566. }
  9567. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9569. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9570. const ContentReader &content_reader) {
  9571. if (req.is_multipart_form_data()) {
  9572. std::vector<FormData> items;
  9573. content_reader(
  9574. [&](const FormData &file) {
  9575. items.push_back(file);
  9576. return true;
  9577. },
  9578. [&](const char *data, size_t data_length) {
  9579. items.back().content.append(data, data_length);
  9580. return true;
  9581. });
  9582. EXPECT_TRUE(std::string(items[0].name) == "document");
  9583. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9584. EXPECT_TRUE(items[0].filename == "2MB_data");
  9585. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9586. EXPECT_TRUE(items[1].name == "hello");
  9587. EXPECT_TRUE(items[1].content == "world");
  9588. EXPECT_TRUE(items[1].filename == "");
  9589. EXPECT_TRUE(items[1].content_type == "");
  9590. } else {
  9591. std::string body;
  9592. content_reader([&](const char *data, size_t data_length) {
  9593. body.append(data, data_length);
  9594. return true;
  9595. });
  9596. }
  9597. });
  9598. auto port = svr.bind_to_any_port("localhost");
  9599. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9600. auto se = detail::scope_exit([&] {
  9601. svr.stop();
  9602. t.join();
  9603. ASSERT_FALSE(svr.is_running());
  9604. });
  9605. svr.wait_until_ready();
  9606. {
  9607. std::string data(1024 * 1024 * 2, '.');
  9608. std::stringstream buffer;
  9609. buffer << data;
  9610. SSLClient cli("localhost", port);
  9611. cli.enable_server_certificate_verification(false);
  9612. UploadFormDataItems items{
  9613. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9614. {"hello", "world", "", ""},
  9615. };
  9616. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9617. ASSERT_TRUE(res);
  9618. ASSERT_EQ(StatusCode::OK_200, res->status);
  9619. }
  9620. }
  9621. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9622. std::string data(1024 * 1024 * 2, '&');
  9623. std::stringstream buffer;
  9624. buffer << data;
  9625. Client cli("https://localhost:8080");
  9626. UploadFormDataItems items{
  9627. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9628. {"hello", "world", "", ""},
  9629. };
  9630. for (const char &c : " \t\r\n") {
  9631. auto res =
  9632. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9633. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9634. ASSERT_FALSE(res);
  9635. }
  9636. }
  9637. TEST(MultipartFormDataTest, PutFormData) {
  9638. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9639. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9640. const ContentReader &content_reader) {
  9641. if (req.is_multipart_form_data()) {
  9642. std::vector<FormData> items;
  9643. content_reader(
  9644. [&](const FormData &file) {
  9645. items.push_back(file);
  9646. return true;
  9647. },
  9648. [&](const char *data, size_t data_length) {
  9649. items.back().content.append(data, data_length);
  9650. return true;
  9651. });
  9652. EXPECT_TRUE(std::string(items[0].name) == "document");
  9653. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9654. EXPECT_TRUE(items[0].filename == "2MB_data");
  9655. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9656. EXPECT_TRUE(items[1].name == "hello");
  9657. EXPECT_TRUE(items[1].content == "world");
  9658. EXPECT_TRUE(items[1].filename == "");
  9659. EXPECT_TRUE(items[1].content_type == "");
  9660. } else {
  9661. std::string body;
  9662. content_reader([&](const char *data, size_t data_length) {
  9663. body.append(data, data_length);
  9664. return true;
  9665. });
  9666. }
  9667. });
  9668. auto port = svr.bind_to_any_port("localhost");
  9669. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9670. auto se = detail::scope_exit([&] {
  9671. svr.stop();
  9672. t.join();
  9673. ASSERT_FALSE(svr.is_running());
  9674. });
  9675. svr.wait_until_ready();
  9676. {
  9677. std::string data(1024 * 1024 * 2, '&');
  9678. std::stringstream buffer;
  9679. buffer << data;
  9680. SSLClient cli("localhost", port);
  9681. cli.enable_server_certificate_verification(false);
  9682. UploadFormDataItems items{
  9683. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9684. {"hello", "world", "", ""},
  9685. };
  9686. auto res = cli.Put("/put", items);
  9687. ASSERT_TRUE(res);
  9688. ASSERT_EQ(StatusCode::OK_200, res->status);
  9689. }
  9690. }
  9691. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9693. svr.Put("/put_customboundary",
  9694. [&](const Request &req, const Response & /*res*/,
  9695. const ContentReader &content_reader) {
  9696. if (req.is_multipart_form_data()) {
  9697. std::vector<FormData> items;
  9698. content_reader(
  9699. [&](const FormData &file) {
  9700. items.push_back(file);
  9701. return true;
  9702. },
  9703. [&](const char *data, size_t data_length) {
  9704. items.back().content.append(data, data_length);
  9705. return true;
  9706. });
  9707. EXPECT_TRUE(std::string(items[0].name) == "document");
  9708. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9709. EXPECT_TRUE(items[0].filename == "2MB_data");
  9710. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9711. EXPECT_TRUE(items[1].name == "hello");
  9712. EXPECT_TRUE(items[1].content == "world");
  9713. EXPECT_TRUE(items[1].filename == "");
  9714. EXPECT_TRUE(items[1].content_type == "");
  9715. } else {
  9716. std::string body;
  9717. content_reader([&](const char *data, size_t data_length) {
  9718. body.append(data, data_length);
  9719. return true;
  9720. });
  9721. }
  9722. });
  9723. auto port = svr.bind_to_any_port("localhost");
  9724. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9725. auto se = detail::scope_exit([&] {
  9726. svr.stop();
  9727. t.join();
  9728. ASSERT_FALSE(svr.is_running());
  9729. });
  9730. svr.wait_until_ready();
  9731. {
  9732. std::string data(1024 * 1024 * 2, '&');
  9733. std::stringstream buffer;
  9734. buffer << data;
  9735. SSLClient cli("localhost", port);
  9736. cli.enable_server_certificate_verification(false);
  9737. UploadFormDataItems items{
  9738. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9739. {"hello", "world", "", ""},
  9740. };
  9741. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9742. ASSERT_TRUE(res);
  9743. ASSERT_EQ(StatusCode::OK_200, res->status);
  9744. }
  9745. }
  9746. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9747. std::string data(1024 * 1024 * 2, '&');
  9748. std::stringstream buffer;
  9749. buffer << data;
  9750. Client cli("https://localhost:8080");
  9751. cli.enable_server_certificate_verification(false);
  9752. UploadFormDataItems items{
  9753. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9754. {"hello", "world", "", ""},
  9755. };
  9756. for (const char &c : " \t\r\n") {
  9757. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9758. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9759. ASSERT_FALSE(res);
  9760. }
  9761. }
  9762. TEST(MultipartFormDataTest, AlternateFilename) {
  9763. auto handled = false;
  9764. Server svr;
  9765. svr.Post("/test", [&](const Request &req, Response &res) {
  9766. ASSERT_EQ(2u, req.form.files.size());
  9767. ASSERT_EQ(1u, req.form.fields.size());
  9768. // Test files
  9769. const auto &file1 = req.form.get_file("file1");
  9770. ASSERT_EQ("file1", file1.name);
  9771. ASSERT_EQ("A.txt", file1.filename);
  9772. ASSERT_EQ("text/plain", file1.content_type);
  9773. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9774. const auto &file2 = req.form.get_file("file2");
  9775. ASSERT_EQ("file2", file2.name);
  9776. ASSERT_EQ("a.html", file2.filename);
  9777. ASSERT_EQ("text/html", file2.content_type);
  9778. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9779. file2.content);
  9780. // Test text field
  9781. const auto &text = req.form.get_field("text");
  9782. ASSERT_EQ("text default", text);
  9783. res.set_content("ok", "text/plain");
  9784. handled = true;
  9785. });
  9786. thread t = thread([&] { svr.listen(HOST, PORT); });
  9787. auto se = detail::scope_exit([&] {
  9788. svr.stop();
  9789. t.join();
  9790. ASSERT_FALSE(svr.is_running());
  9791. ASSERT_TRUE(handled);
  9792. });
  9793. svr.wait_until_ready();
  9794. auto req = "POST /test HTTP/1.1\r\n"
  9795. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9796. "Content-Length: 399\r\n"
  9797. "\r\n"
  9798. "----------\r\n"
  9799. "Content-Disposition: form-data; name=\"text\"\r\n"
  9800. "\r\n"
  9801. "text default\r\n"
  9802. "----------\r\n"
  9803. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9804. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9805. "Content-Type: text/plain\r\n"
  9806. "\r\n"
  9807. "Content of a.txt.\r\n"
  9808. "\r\n"
  9809. "----------\r\n"
  9810. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9811. "\"a.html\"\r\n"
  9812. "Content-Type: text/html\r\n"
  9813. "\r\n"
  9814. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9815. "\r\n"
  9816. "------------\r\n";
  9817. ASSERT_TRUE(send_request(1, req));
  9818. }
  9819. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9820. auto handled = false;
  9821. Server svr;
  9822. svr.Post("/test", [&](const Request &req, Response &res) {
  9823. // Case-insensitive "utf-8''" prefix with a long value
  9824. const auto &file = req.form.get_file("file1");
  9825. ASSERT_EQ("file1", file.name);
  9826. // 8000 chars exercises both the Content-Disposition parser and the
  9827. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9828. // Prior to the fix, std::regex_match on this header would cause O(N)
  9829. // stack recursion in libstdc++, leading to SIGSEGV.
  9830. std::string expected_filename(8000, 'A');
  9831. ASSERT_EQ(expected_filename, file.filename);
  9832. res.set_content("ok", "text/plain");
  9833. handled = true;
  9834. });
  9835. thread t = thread([&] { svr.listen(HOST, PORT); });
  9836. auto se = detail::scope_exit([&] {
  9837. svr.stop();
  9838. t.join();
  9839. ASSERT_FALSE(svr.is_running());
  9840. ASSERT_TRUE(handled);
  9841. });
  9842. svr.wait_until_ready();
  9843. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9844. // Regression test for GHSA-qq6v-r583-3h69
  9845. std::string long_filename(8000, 'A');
  9846. std::string body = "----------\r\n"
  9847. "Content-Disposition: form-data; name=\"file1\"; "
  9848. "filename*=\"Utf-8''" +
  9849. long_filename +
  9850. "\"\r\n"
  9851. "\r\n"
  9852. "hello\r\n"
  9853. "------------\r\n";
  9854. auto req = "POST /test HTTP/1.1\r\n"
  9855. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9856. "Content-Length: " +
  9857. std::to_string(body.size()) + "\r\n\r\n" + body;
  9858. ASSERT_TRUE(send_request(1, req));
  9859. }
  9860. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9861. auto handled = false;
  9862. Server svr;
  9863. svr.Post("/test", [&](const Request &req, Response &) {
  9864. ASSERT_EQ(2u, req.form.fields.size());
  9865. const auto &text1 = req.form.get_field("text1");
  9866. ASSERT_EQ("text1", text1);
  9867. const auto &text2 = req.form.get_field("text2");
  9868. ASSERT_EQ("text2", text2);
  9869. handled = true;
  9870. });
  9871. thread t = thread([&] { svr.listen(HOST, PORT); });
  9872. auto se = detail::scope_exit([&] {
  9873. svr.stop();
  9874. t.join();
  9875. ASSERT_FALSE(svr.is_running());
  9876. ASSERT_TRUE(handled);
  9877. });
  9878. svr.wait_until_ready();
  9879. auto req = "POST /test HTTP/1.1\r\n"
  9880. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9881. "Content-Length: 146\r\n"
  9882. "\r\n----------\r\n"
  9883. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9884. "\r\n"
  9885. "text1"
  9886. "\r\n----------\r\n"
  9887. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9888. "\r\n"
  9889. "text2"
  9890. "\r\n------------";
  9891. std::string response;
  9892. ASSERT_TRUE(send_request(1, req, &response));
  9893. ASSERT_EQ("200", response.substr(9, 3));
  9894. }
  9895. TEST(MultipartFormDataTest, ContentLength) {
  9896. auto handled = false;
  9897. Server svr;
  9898. svr.Post("/test", [&](const Request &req, Response &) {
  9899. ASSERT_EQ(2u, req.form.fields.size());
  9900. const auto &text1 = req.form.get_field("text1");
  9901. ASSERT_EQ("text1", text1);
  9902. const auto &text2 = req.form.get_field("text2");
  9903. ASSERT_EQ("text2", text2);
  9904. handled = true;
  9905. });
  9906. thread t = thread([&] { svr.listen(HOST, PORT); });
  9907. auto se = detail::scope_exit([&] {
  9908. svr.stop();
  9909. t.join();
  9910. ASSERT_FALSE(svr.is_running());
  9911. ASSERT_TRUE(handled);
  9912. });
  9913. svr.wait_until_ready();
  9914. auto req = "POST /test HTTP/1.1\r\n"
  9915. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9916. "Content-Length: 167\r\n"
  9917. "\r\n----------\r\n"
  9918. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9919. "Content-Length: 5\r\n"
  9920. "\r\n"
  9921. "text1"
  9922. "\r\n----------\r\n"
  9923. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9924. "\r\n"
  9925. "text2"
  9926. "\r\n------------\r\n";
  9927. std::string response;
  9928. ASSERT_TRUE(send_request(1, req, &response));
  9929. ASSERT_EQ("200", response.substr(9, 3));
  9930. }
  9931. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9932. auto handled = false;
  9933. Server svr;
  9934. svr.Post("/test", [&](const Request &req, Response &) {
  9935. ASSERT_EQ(2u, req.form.fields.size());
  9936. const auto &text1 = req.form.get_field("text1");
  9937. ASSERT_EQ("text1", text1);
  9938. // TODO: Add header access for text fields if needed
  9939. const auto &text2 = req.form.get_field("text2");
  9940. ASSERT_EQ("text2", text2);
  9941. // TODO: Header access for text fields needs to be implemented
  9942. // auto &headers = it->second.headers;
  9943. // ASSERT_EQ(3U, headers.size());
  9944. // auto custom_header = headers.find("x-whatever");
  9945. // ASSERT_TRUE(custom_header != headers.end());
  9946. // ASSERT_NE("customvalue", custom_header->second);
  9947. // ASSERT_EQ("CustomValue", custom_header->second);
  9948. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9949. handled = true;
  9950. });
  9951. thread t = thread([&] { svr.listen(HOST, PORT); });
  9952. auto se = detail::scope_exit([&] {
  9953. svr.stop();
  9954. t.join();
  9955. ASSERT_FALSE(svr.is_running());
  9956. ASSERT_TRUE(handled);
  9957. });
  9958. svr.wait_until_ready();
  9959. auto req = "POST /test HTTP/1.1\r\n"
  9960. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9961. "Content-Length: 232\r\n"
  9962. "\r\n----------\r\n"
  9963. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9964. "Content-Length: 5\r\n"
  9965. "X-Test: 1\r\n"
  9966. "\r\n"
  9967. "text1"
  9968. "\r\n----------\r\n"
  9969. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9970. "Content-Type: text/plain\r\n"
  9971. "X-Whatever: CustomValue\r\n"
  9972. "\r\n"
  9973. "text2"
  9974. "\r\n------------\r\n"
  9975. "That should be disregarded. Not even read";
  9976. std::string response;
  9977. ASSERT_TRUE(send_request(1, req, &response));
  9978. ASSERT_EQ("200", response.substr(9, 3));
  9979. }
  9980. TEST(MultipartFormDataTest, LargeHeader) {
  9981. auto handled = false;
  9982. Server svr;
  9983. svr.Post("/test", [&](const Request &req, Response &) {
  9984. ASSERT_EQ(1u, req.form.fields.size());
  9985. const auto &text = req.form.get_field("name1");
  9986. ASSERT_EQ("text1", text);
  9987. handled = true;
  9988. });
  9989. thread t = thread([&] { svr.listen(HOST, PORT); });
  9990. auto se = detail::scope_exit([&] {
  9991. svr.stop();
  9992. t.join();
  9993. ASSERT_FALSE(svr.is_running());
  9994. ASSERT_TRUE(handled);
  9995. });
  9996. svr.wait_until_ready();
  9997. auto boundary = std::string("cpp-httplib-multipart-data");
  9998. std::string content = "--" + boundary +
  9999. "\r\n"
  10000. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10001. "\r\n"
  10002. "text1\r\n"
  10003. "--" +
  10004. boundary + "--\r\n";
  10005. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10006. "Content-Type: multipart/form-data;boundary=" +
  10007. boundary +
  10008. "\r\n"
  10009. "Content-Length: " +
  10010. std::to_string(content.size()) +
  10011. "\r\n"
  10012. "Dummy-Header: ";
  10013. std::string header_suffix = "\r\n"
  10014. "\r\n";
  10015. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10016. size_t header_dummy_size =
  10017. read_buff_size -
  10018. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10019. auto header_dummy = std::string(header_dummy_size, '@');
  10020. auto req = header_prefix + header_dummy + header_suffix + content;
  10021. std::string response;
  10022. ASSERT_TRUE(send_request(1, req, &response));
  10023. ASSERT_EQ("200", response.substr(9, 3));
  10024. }
  10025. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10026. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10027. // (not chunked Transfer-Encoding) after the streaming refactor.
  10028. auto handled = false;
  10029. Server svr;
  10030. svr.Post("/upload", [&](const Request &req, Response &res) {
  10031. auto cl_it = req.headers.find("Content-Length");
  10032. EXPECT_TRUE(cl_it != req.headers.end());
  10033. auto te_it = req.headers.find("Transfer-Encoding");
  10034. EXPECT_TRUE(te_it == req.headers.end());
  10035. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10036. res.set_content("ok", "text/plain");
  10037. handled = true;
  10038. });
  10039. auto port = svr.bind_to_any_port(HOST);
  10040. auto t = thread([&] { svr.listen_after_bind(); });
  10041. auto se = detail::scope_exit([&] {
  10042. svr.stop();
  10043. t.join();
  10044. ASSERT_FALSE(svr.is_running());
  10045. ASSERT_TRUE(handled);
  10046. });
  10047. svr.wait_until_ready();
  10048. UploadFormDataItems items = {
  10049. {"field1", "hello", "", "text/plain"},
  10050. {"file1", "world", "test.txt", "application/octet-stream"},
  10051. };
  10052. Client cli(HOST, port);
  10053. auto res = cli.Post("/upload", {}, items);
  10054. ASSERT_TRUE(res);
  10055. EXPECT_EQ(StatusCode::OK_200, res->status);
  10056. }
  10057. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10058. // Verify that make_multipart_content_provider coalesces many small segments
  10059. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10060. constexpr size_t kItemCount = 1000;
  10061. UploadFormDataItems items;
  10062. items.reserve(kItemCount);
  10063. for (size_t i = 0; i < kItemCount; i++) {
  10064. items.push_back(
  10065. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10066. }
  10067. const std::string boundary = "----test-boundary";
  10068. auto content_length = detail::get_multipart_content_length(items, boundary);
  10069. auto provider = detail::make_multipart_content_provider(items, boundary);
  10070. // Drive the provider the same way write_content_with_progress does
  10071. size_t write_count = 0;
  10072. size_t total_bytes = 0;
  10073. DataSink sink;
  10074. size_t offset = 0;
  10075. sink.write = [&](const char *d, size_t l) -> bool {
  10076. (void)d;
  10077. write_count++;
  10078. total_bytes += l;
  10079. offset += l;
  10080. return true;
  10081. };
  10082. sink.is_writable = []() -> bool { return true; };
  10083. while (offset < content_length) {
  10084. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10085. }
  10086. EXPECT_EQ(content_length, total_bytes);
  10087. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10088. // With buffering into 64KB blocks, write_count should be much smaller.
  10089. auto segment_count = 3 * kItemCount + 1;
  10090. EXPECT_LT(write_count, segment_count / 10);
  10091. }
  10092. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10093. // Integration test: send many UploadFormDataItems and verify the server
  10094. // receives all of them correctly (#2410).
  10095. constexpr size_t kItemCount = 500;
  10096. auto handled = false;
  10097. Server svr;
  10098. svr.Post("/upload", [&](const Request &req, Response &res) {
  10099. EXPECT_EQ(kItemCount, req.form.fields.size());
  10100. for (size_t i = 0; i < kItemCount; i++) {
  10101. auto key = "field" + std::to_string(i);
  10102. auto val = "value" + std::to_string(i);
  10103. auto it = req.form.fields.find(key);
  10104. if (it != req.form.fields.end()) {
  10105. EXPECT_EQ(val, it->second.content);
  10106. } else {
  10107. ADD_FAILURE() << "Missing field: " << key;
  10108. }
  10109. }
  10110. res.set_content("ok", "text/plain");
  10111. handled = true;
  10112. });
  10113. auto port = svr.bind_to_any_port(HOST);
  10114. auto t = thread([&] { svr.listen_after_bind(); });
  10115. auto se = detail::scope_exit([&] {
  10116. svr.stop();
  10117. t.join();
  10118. ASSERT_FALSE(svr.is_running());
  10119. ASSERT_TRUE(handled);
  10120. });
  10121. svr.wait_until_ready();
  10122. UploadFormDataItems items;
  10123. items.reserve(kItemCount);
  10124. for (size_t i = 0; i < kItemCount; i++) {
  10125. items.push_back(
  10126. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10127. }
  10128. Client cli(HOST, port);
  10129. auto res = cli.Post("/upload", items);
  10130. ASSERT_TRUE(res);
  10131. EXPECT_EQ(StatusCode::OK_200, res->status);
  10132. }
  10133. TEST(MultipartFormDataTest, MakeFileProvider) {
  10134. // Verify make_file_provider sends a file's contents correctly.
  10135. const std::string file_content(4096, 'Z');
  10136. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10137. {
  10138. std::ofstream ofs(tmp_path, std::ios::binary);
  10139. ofs.write(file_content.data(),
  10140. static_cast<std::streamsize>(file_content.size()));
  10141. }
  10142. auto handled = false;
  10143. Server svr;
  10144. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10145. const ContentReader &content_reader) {
  10146. ASSERT_TRUE(req.is_multipart_form_data());
  10147. std::vector<FormData> items;
  10148. content_reader(
  10149. [&](const FormData &file) {
  10150. items.push_back(file);
  10151. return true;
  10152. },
  10153. [&](const char *data, size_t data_length) {
  10154. items.back().content.append(data, data_length);
  10155. return true;
  10156. });
  10157. ASSERT_EQ(1u, items.size());
  10158. EXPECT_EQ("myfile", items[0].name);
  10159. EXPECT_EQ("data.bin", items[0].filename);
  10160. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10161. EXPECT_EQ(file_content, items[0].content);
  10162. handled = true;
  10163. });
  10164. auto port = svr.bind_to_any_port(HOST);
  10165. auto t = thread([&] { svr.listen_after_bind(); });
  10166. auto se = detail::scope_exit([&] {
  10167. svr.stop();
  10168. t.join();
  10169. ASSERT_FALSE(svr.is_running());
  10170. ASSERT_TRUE(handled);
  10171. std::remove(tmp_path.c_str());
  10172. });
  10173. svr.wait_until_ready();
  10174. FormDataProviderItems providers;
  10175. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10176. "application/octet-stream"));
  10177. Client cli(HOST, port);
  10178. auto res = cli.Post("/upload", {}, {}, providers);
  10179. ASSERT_TRUE(res);
  10180. EXPECT_EQ(StatusCode::OK_200, res->status);
  10181. }
  10182. TEST(MakeFileBodyTest, Basic) {
  10183. const std::string file_content(4096, 'Z');
  10184. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10185. {
  10186. std::ofstream ofs(tmp_path, std::ios::binary);
  10187. ofs.write(file_content.data(),
  10188. static_cast<std::streamsize>(file_content.size()));
  10189. }
  10190. auto handled = false;
  10191. Server svr;
  10192. svr.Post("/upload", [&](const Request &req, Response &res) {
  10193. EXPECT_EQ(file_content, req.body);
  10194. handled = true;
  10195. res.status = StatusCode::OK_200;
  10196. });
  10197. auto port = svr.bind_to_any_port(HOST);
  10198. auto t = thread([&] { svr.listen_after_bind(); });
  10199. auto se = detail::scope_exit([&] {
  10200. svr.stop();
  10201. t.join();
  10202. ASSERT_FALSE(svr.is_running());
  10203. ASSERT_TRUE(handled);
  10204. std::remove(tmp_path.c_str());
  10205. });
  10206. svr.wait_until_ready();
  10207. auto fb = make_file_body(tmp_path);
  10208. ASSERT_GT(fb.first, 0u);
  10209. Client cli(HOST, port);
  10210. auto res =
  10211. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10212. ASSERT_TRUE(res);
  10213. EXPECT_EQ(StatusCode::OK_200, res->status);
  10214. }
  10215. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10216. static constexpr unsigned int number_of_tasks{1000000};
  10217. std::atomic_uint count{0};
  10218. std::unique_ptr<TaskQueue> task_queue{
  10219. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10220. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10221. auto queued = task_queue->enqueue(
  10222. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10223. EXPECT_TRUE(queued);
  10224. }
  10225. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10226. task_queue->shutdown();
  10227. #else
  10228. EXPECT_NO_THROW(task_queue->shutdown());
  10229. #endif
  10230. EXPECT_EQ(number_of_tasks, count.load());
  10231. }
  10232. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10233. static constexpr unsigned int number_of_tasks{1000000};
  10234. static constexpr unsigned int qlimit{2};
  10235. unsigned int queued_count{0};
  10236. std::atomic_uint count{0};
  10237. std::unique_ptr<TaskQueue> task_queue{
  10238. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10239. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10240. if (task_queue->enqueue(
  10241. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10242. queued_count++;
  10243. }
  10244. }
  10245. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10246. task_queue->shutdown();
  10247. #else
  10248. EXPECT_NO_THROW(task_queue->shutdown());
  10249. #endif
  10250. EXPECT_EQ(queued_count, count.load());
  10251. EXPECT_TRUE(queued_count <= number_of_tasks);
  10252. EXPECT_TRUE(queued_count >= qlimit);
  10253. }
  10254. TEST(TaskQueueTest, MaxQueuedRequests) {
  10255. static constexpr unsigned int qlimit{3};
  10256. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10257. std::condition_variable sem_cv;
  10258. std::mutex sem_mtx;
  10259. int credits = 0;
  10260. bool queued;
  10261. /* Fill up the queue with tasks that will block until we give them credits to
  10262. * complete. */
  10263. for (unsigned int n = 0; n <= qlimit;) {
  10264. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10265. std::unique_lock<std::mutex> lock(sem_mtx);
  10266. while (credits <= 0) {
  10267. sem_cv.wait(lock);
  10268. }
  10269. /* Consume the credit and signal the test code if they are all gone. */
  10270. if (--credits == 0) { sem_cv.notify_one(); }
  10271. });
  10272. if (n < qlimit) {
  10273. /* The first qlimit enqueues must succeed. */
  10274. EXPECT_TRUE(queued);
  10275. } else {
  10276. /* The last one will succeed only when the worker thread
  10277. * starts and dequeues the first blocking task. Although
  10278. * not necessary for the correctness of this test, we sleep for
  10279. * a short while to avoid busy waiting. */
  10280. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10281. }
  10282. if (queued) { n++; }
  10283. }
  10284. /* Further enqueues must fail since the queue is full. */
  10285. for (auto i = 0; i < 4; i++) {
  10286. queued = task_queue->enqueue([] {});
  10287. EXPECT_FALSE(queued);
  10288. }
  10289. /* Give the credits to allow the previous tasks to complete. */
  10290. {
  10291. std::unique_lock<std::mutex> lock(sem_mtx);
  10292. credits += qlimit + 1;
  10293. }
  10294. sem_cv.notify_all();
  10295. /* Wait for all the credits to be consumed. */
  10296. {
  10297. std::unique_lock<std::mutex> lock(sem_mtx);
  10298. while (credits > 0) {
  10299. sem_cv.wait(lock);
  10300. }
  10301. }
  10302. /* Check that we are able again to enqueue at least qlimit tasks. */
  10303. for (unsigned int i = 0; i < qlimit; i++) {
  10304. queued = task_queue->enqueue([] {});
  10305. EXPECT_TRUE(queued);
  10306. }
  10307. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10308. task_queue->shutdown();
  10309. #else
  10310. EXPECT_NO_THROW(task_queue->shutdown());
  10311. #endif
  10312. }
  10313. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10314. Server svr;
  10315. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10316. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10317. });
  10318. svr.Get("/hello", [](const Request &req, Response &res) {
  10319. res.set_content(req.get_param_value("key"), "text/plain");
  10320. });
  10321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10322. auto se = detail::scope_exit([&] {
  10323. svr.stop();
  10324. thread.join();
  10325. ASSERT_FALSE(svr.is_running());
  10326. });
  10327. svr.wait_until_ready();
  10328. {
  10329. Client cli(HOST, PORT);
  10330. cli.set_follow_location(true);
  10331. auto res = cli.Get("/");
  10332. ASSERT_TRUE(res);
  10333. EXPECT_EQ(StatusCode::OK_200, res->status);
  10334. EXPECT_EQ("val&key2=val2", res->body);
  10335. }
  10336. }
  10337. #endif
  10338. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10339. Server svr;
  10340. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10341. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10342. });
  10343. svr.Get("/hello", [](const Request &req, Response &res) {
  10344. res.set_content(req.get_param_value("key"), "text/plain");
  10345. });
  10346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10347. auto se = detail::scope_exit([&] {
  10348. svr.stop();
  10349. thread.join();
  10350. ASSERT_FALSE(svr.is_running());
  10351. });
  10352. svr.wait_until_ready();
  10353. {
  10354. Client cli(HOST, PORT);
  10355. cli.set_follow_location(true);
  10356. auto res = cli.Get("/");
  10357. ASSERT_TRUE(res);
  10358. EXPECT_EQ(StatusCode::OK_200, res->status);
  10359. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10360. }
  10361. }
  10362. TEST(RedirectTest, RedirectWithPlusInPath) {
  10363. Server svr;
  10364. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10365. res.set_redirect("/a+b");
  10366. });
  10367. // Route pattern uses regex; escape + as \\+
  10368. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10369. res.set_content(req.path, "text/plain");
  10370. });
  10371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10372. auto se = detail::scope_exit([&] {
  10373. svr.stop();
  10374. thread.join();
  10375. ASSERT_FALSE(svr.is_running());
  10376. });
  10377. svr.wait_until_ready();
  10378. {
  10379. Client cli(HOST, PORT);
  10380. cli.set_follow_location(true);
  10381. auto res = cli.Get("/");
  10382. ASSERT_TRUE(res);
  10383. EXPECT_EQ(StatusCode::OK_200, res->status);
  10384. EXPECT_EQ("/a+b", res->body);
  10385. }
  10386. }
  10387. #ifdef CPPHTTPLIB_SSL_ENABLED
  10388. TEST(RedirectTest, Issue2185_Online) {
  10389. SSLClient client("github.com");
  10390. client.set_follow_location(true);
  10391. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10392. "Coollab-Windows.zip");
  10393. ASSERT_TRUE(res);
  10394. EXPECT_EQ(StatusCode::OK_200, res->status);
  10395. EXPECT_EQ(9920427U, res->body.size());
  10396. }
  10397. #endif
  10398. TEST(VulnerabilityTest, CRLFInjection) {
  10399. Server svr;
  10400. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10401. res.set_content("Hello 1", "text/plain");
  10402. });
  10403. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10404. res.set_content("Hello 2", "text/plain");
  10405. });
  10406. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10407. res.set_content("Hello 3", "text/plain");
  10408. });
  10409. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10410. res.set_content("Hello 4", "text/plain");
  10411. });
  10412. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10413. for (const auto &x : req.headers) {
  10414. auto key = x.first;
  10415. EXPECT_STRNE("evil", key.c_str());
  10416. }
  10417. });
  10418. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. thread.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. {
  10426. Client cli(HOST, PORT);
  10427. cli.Post("/test1", "A=B",
  10428. "application/x-www-form-urlencoded\r\nevil: hello1");
  10429. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10430. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10431. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10432. }
  10433. }
  10434. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10435. auto server_thread = std::thread([] {
  10436. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10437. default_socket_options(srv);
  10438. sockaddr_in addr{};
  10439. addr.sin_family = AF_INET;
  10440. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10441. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10442. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10443. ::listen(srv, 1);
  10444. sockaddr_in cli_addr{};
  10445. socklen_t cli_len = sizeof(cli_addr);
  10446. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10447. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10448. std::string buf_all;
  10449. char buf[2048];
  10450. ssize_t n;
  10451. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10452. buf_all.append(buf, static_cast<size_t>(n));
  10453. size_t pos;
  10454. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10455. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10456. auto e = request_block.find("\r\n");
  10457. if (e != std::string::npos) {
  10458. auto request_line = request_block.substr(0, e);
  10459. std::string msg =
  10460. "CRLF injection detected in request line: '" + request_line + "'";
  10461. EXPECT_FALSE(true) << msg;
  10462. }
  10463. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10464. ::send(cli,
  10465. #ifdef _WIN32
  10466. static_cast<const char *>(resp.c_str()),
  10467. static_cast<int>(resp.size()),
  10468. #else
  10469. resp.c_str(), resp.size(),
  10470. #endif
  10471. 0);
  10472. buf_all.erase(0, pos + 4);
  10473. }
  10474. }
  10475. detail::close_socket(cli);
  10476. detail::close_socket(srv);
  10477. });
  10478. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10479. auto cli = Client("127.0.0.1", PORT + 1);
  10480. auto headers = Headers{
  10481. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10482. {"Connection", "keep-alive"}};
  10483. auto res = cli.Get("/hi", headers);
  10484. EXPECT_FALSE(res);
  10485. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10486. server_thread.join();
  10487. }
  10488. TEST(PathParamsTest, StaticMatch) {
  10489. const auto pattern = "/users/all";
  10490. detail::PathParamsMatcher matcher(pattern);
  10491. Request request;
  10492. request.path = "/users/all";
  10493. ASSERT_TRUE(matcher.match(request));
  10494. std::unordered_map<std::string, std::string> expected_params = {};
  10495. EXPECT_EQ(request.path_params, expected_params);
  10496. }
  10497. TEST(PathParamsTest, StaticMismatch) {
  10498. const auto pattern = "/users/all";
  10499. detail::PathParamsMatcher matcher(pattern);
  10500. Request request;
  10501. request.path = "/users/1";
  10502. ASSERT_FALSE(matcher.match(request));
  10503. }
  10504. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10505. const auto pattern = "/users/:id/subscriptions";
  10506. detail::PathParamsMatcher matcher(pattern);
  10507. Request request;
  10508. request.path = "/users/42/subscriptions";
  10509. ASSERT_TRUE(matcher.match(request));
  10510. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10511. EXPECT_EQ(request.path_params, expected_params);
  10512. }
  10513. TEST(PathParamsTest, SingleParamInTheEnd) {
  10514. const auto pattern = "/users/:id";
  10515. detail::PathParamsMatcher matcher(pattern);
  10516. Request request;
  10517. request.path = "/users/24";
  10518. ASSERT_TRUE(matcher.match(request));
  10519. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10520. EXPECT_EQ(request.path_params, expected_params);
  10521. }
  10522. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10523. const auto pattern = "/users/:id/";
  10524. detail::PathParamsMatcher matcher(pattern);
  10525. Request request;
  10526. request.path = "/users/42/";
  10527. ASSERT_TRUE(matcher.match(request));
  10528. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10529. EXPECT_EQ(request.path_params, expected_params);
  10530. }
  10531. TEST(PathParamsTest, EmptyParam) {
  10532. const auto pattern = "/users/:id/";
  10533. detail::PathParamsMatcher matcher(pattern);
  10534. Request request;
  10535. request.path = "/users//";
  10536. ASSERT_TRUE(matcher.match(request));
  10537. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10538. EXPECT_EQ(request.path_params, expected_params);
  10539. }
  10540. TEST(PathParamsTest, FragmentMismatch) {
  10541. const auto pattern = "/users/:id/";
  10542. detail::PathParamsMatcher matcher(pattern);
  10543. Request request;
  10544. request.path = "/admins/24/";
  10545. ASSERT_FALSE(matcher.match(request));
  10546. }
  10547. TEST(PathParamsTest, ExtraFragments) {
  10548. const auto pattern = "/users/:id";
  10549. detail::PathParamsMatcher matcher(pattern);
  10550. Request request;
  10551. request.path = "/users/42/subscriptions";
  10552. ASSERT_FALSE(matcher.match(request));
  10553. }
  10554. TEST(PathParamsTest, MissingTrailingParam) {
  10555. const auto pattern = "/users/:id";
  10556. detail::PathParamsMatcher matcher(pattern);
  10557. Request request;
  10558. request.path = "/users";
  10559. ASSERT_FALSE(matcher.match(request));
  10560. }
  10561. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10562. const auto pattern = "/users/:id/subscriptions";
  10563. detail::PathParamsMatcher matcher(pattern);
  10564. Request request;
  10565. request.path = "/users/subscriptions";
  10566. ASSERT_FALSE(matcher.match(request));
  10567. }
  10568. TEST(PathParamsTest, MultipleParams) {
  10569. const auto pattern = "/users/:userid/subscriptions/:subid";
  10570. detail::PathParamsMatcher matcher(pattern);
  10571. Request request;
  10572. request.path = "/users/42/subscriptions/2";
  10573. ASSERT_TRUE(matcher.match(request));
  10574. std::unordered_map<std::string, std::string> expected_params = {
  10575. {"userid", "42"}, {"subid", "2"}};
  10576. EXPECT_EQ(request.path_params, expected_params);
  10577. }
  10578. TEST(PathParamsTest, SequenceOfParams) {
  10579. const auto pattern = "/values/:x/:y/:z";
  10580. detail::PathParamsMatcher matcher(pattern);
  10581. Request request;
  10582. request.path = "/values/1/2/3";
  10583. ASSERT_TRUE(matcher.match(request));
  10584. std::unordered_map<std::string, std::string> expected_params = {
  10585. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10586. EXPECT_EQ(request.path_params, expected_params);
  10587. }
  10588. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10589. const auto pattern = "/prefix:suffix";
  10590. detail::PathParamsMatcher matcher(pattern);
  10591. Request request;
  10592. request.path = "/prefix:suffix";
  10593. ASSERT_TRUE(matcher.match(request));
  10594. const std::unordered_map<std::string, std::string> expected_params = {};
  10595. EXPECT_EQ(request.path_params, expected_params);
  10596. }
  10597. TEST(ParseUrlTest, VariousPatterns) {
  10598. {
  10599. detail::UrlComponents uc;
  10600. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10601. EXPECT_EQ("http", uc.scheme);
  10602. EXPECT_EQ("example.com", uc.host);
  10603. EXPECT_EQ("8080", uc.port);
  10604. EXPECT_EQ("/path", uc.path);
  10605. EXPECT_EQ("?q=1", uc.query);
  10606. }
  10607. {
  10608. detail::UrlComponents uc;
  10609. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10610. EXPECT_EQ("https", uc.scheme);
  10611. EXPECT_EQ("example.com", uc.host);
  10612. EXPECT_TRUE(uc.port.empty());
  10613. EXPECT_EQ("/path", uc.path);
  10614. }
  10615. {
  10616. detail::UrlComponents uc;
  10617. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10618. EXPECT_EQ("::1", uc.host);
  10619. EXPECT_EQ("8080", uc.port);
  10620. EXPECT_EQ("/path", uc.path);
  10621. }
  10622. {
  10623. detail::UrlComponents uc;
  10624. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10625. }
  10626. {
  10627. detail::UrlComponents uc;
  10628. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10629. EXPECT_TRUE(uc.scheme.empty());
  10630. EXPECT_EQ("example.com", uc.host);
  10631. EXPECT_EQ("/path", uc.path);
  10632. EXPECT_EQ("?q=1", uc.query);
  10633. }
  10634. {
  10635. detail::UrlComponents uc;
  10636. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10637. EXPECT_TRUE(uc.host.empty());
  10638. EXPECT_EQ("/path", uc.path);
  10639. EXPECT_EQ("?q=1", uc.query);
  10640. }
  10641. {
  10642. detail::UrlComponents uc;
  10643. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10644. EXPECT_EQ("example.com", uc.host);
  10645. EXPECT_EQ("8080", uc.port);
  10646. }
  10647. {
  10648. // Unix socket path — must not be parsed as host
  10649. detail::UrlComponents uc;
  10650. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  10651. EXPECT_TRUE(uc.host.empty());
  10652. }
  10653. {
  10654. detail::UrlComponents uc;
  10655. ASSERT_TRUE(detail::parse_url("", uc));
  10656. EXPECT_TRUE(uc.host.empty());
  10657. EXPECT_TRUE(uc.path.empty());
  10658. }
  10659. {
  10660. detail::UrlComponents uc;
  10661. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  10662. }
  10663. {
  10664. detail::UrlComponents uc;
  10665. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  10666. }
  10667. {
  10668. // Accepted by parse_url; callers restrict to http/https
  10669. detail::UrlComponents uc;
  10670. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  10671. EXPECT_EQ("ftp", uc.scheme);
  10672. }
  10673. {
  10674. detail::UrlComponents uc;
  10675. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  10676. }
  10677. {
  10678. detail::UrlComponents uc;
  10679. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  10680. }
  10681. }
  10682. TEST(ParseUrlTest, FragmentHandling) {
  10683. {
  10684. detail::UrlComponents uc;
  10685. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  10686. EXPECT_EQ("/path", uc.path);
  10687. EXPECT_TRUE(uc.query.empty());
  10688. }
  10689. {
  10690. detail::UrlComponents uc;
  10691. ASSERT_TRUE(detail::parse_url("#frag", uc));
  10692. EXPECT_TRUE(uc.path.empty());
  10693. EXPECT_TRUE(uc.query.empty());
  10694. }
  10695. }
  10696. TEST(ParseUrlTest, UserinfoHandling) {
  10697. // Userinfo with @ but no colon — host includes @
  10698. detail::UrlComponents uc;
  10699. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  10700. EXPECT_EQ("user@host.com", uc.host);
  10701. EXPECT_EQ("/path", uc.path);
  10702. }
  10703. TEST(ParseUrlTest, IPv6EdgeCases) {
  10704. {
  10705. detail::UrlComponents uc;
  10706. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  10707. EXPECT_TRUE(uc.scheme.empty());
  10708. EXPECT_EQ("::1", uc.host);
  10709. EXPECT_EQ("8080", uc.port);
  10710. }
  10711. {
  10712. // Zone ID '%25' is not in [a-fA-F0-9:]
  10713. detail::UrlComponents uc;
  10714. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  10715. }
  10716. }
  10717. TEST(ParseUrlTest, SchemeEdgeCases) {
  10718. {
  10719. detail::UrlComponents uc;
  10720. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  10721. }
  10722. {
  10723. detail::UrlComponents uc;
  10724. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  10725. }
  10726. {
  10727. detail::UrlComponents uc;
  10728. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  10729. }
  10730. }
  10731. TEST(ParseUrlTest, PortEdgeCases) {
  10732. {
  10733. detail::UrlComponents uc;
  10734. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  10735. EXPECT_TRUE(uc.port.empty());
  10736. EXPECT_EQ("/path", uc.path);
  10737. }
  10738. {
  10739. // parse_url accepts any port string; validation is done by parse_port
  10740. detail::UrlComponents uc;
  10741. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  10742. EXPECT_EQ("abc", uc.port);
  10743. }
  10744. }
  10745. TEST(ParseUrlTest, WebSocketPatterns) {
  10746. {
  10747. detail::UrlComponents uc;
  10748. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  10749. EXPECT_EQ("ws", uc.scheme);
  10750. EXPECT_EQ("echo.example.com", uc.host);
  10751. EXPECT_EQ("8080", uc.port);
  10752. EXPECT_EQ("/ws", uc.path);
  10753. }
  10754. {
  10755. detail::UrlComponents uc;
  10756. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  10757. EXPECT_EQ("wss", uc.scheme);
  10758. EXPECT_EQ("echo.example.com", uc.host);
  10759. EXPECT_TRUE(uc.port.empty());
  10760. EXPECT_EQ("/ws", uc.path);
  10761. }
  10762. }
  10763. TEST(ParseUrlTest, QueryOnly) {
  10764. detail::UrlComponents uc;
  10765. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  10766. EXPECT_TRUE(uc.host.empty());
  10767. EXPECT_TRUE(uc.path.empty());
  10768. EXPECT_EQ("?q=1&r=2", uc.query);
  10769. }
  10770. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  10771. detail::UrlComponents uc;
  10772. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  10773. EXPECT_TRUE(uc.scheme.empty());
  10774. EXPECT_EQ("example.com", uc.host);
  10775. EXPECT_EQ("443", uc.port);
  10776. EXPECT_EQ("/path", uc.path);
  10777. }
  10778. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10779. // If ipv6 regex working, regex match codepath is taken.
  10780. // else port will default to 80 in Client impl
  10781. int clientImplMagicPort = 80;
  10782. int port = 4321;
  10783. // above ports must be different to avoid false negative
  10784. EXPECT_NE(clientImplMagicPort, port);
  10785. std::string ipV6TestURL = "http://[ff06::c3]";
  10786. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10787. CLIENT_PRIVATE_KEY_FILE);
  10788. EXPECT_EQ(cli.port(), port);
  10789. }
  10790. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10791. auto file_path = "./www/dir/index.html";
  10792. auto dir_path = "./www/dir";
  10793. detail::FileStat stat_file(file_path);
  10794. EXPECT_TRUE(stat_file.is_file());
  10795. EXPECT_FALSE(stat_file.is_dir());
  10796. detail::FileStat stat_dir(dir_path);
  10797. EXPECT_FALSE(stat_dir.is_file());
  10798. EXPECT_TRUE(stat_dir.is_dir());
  10799. }
  10800. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10801. // IPv4 with default HTTP port (80)
  10802. EXPECT_EQ("example.com",
  10803. detail::make_host_and_port_string("example.com", 80, false));
  10804. // IPv4 with default HTTPS port (443)
  10805. EXPECT_EQ("example.com",
  10806. detail::make_host_and_port_string("example.com", 443, true));
  10807. // IPv4 with non-default HTTP port
  10808. EXPECT_EQ("example.com:8080",
  10809. detail::make_host_and_port_string("example.com", 8080, false));
  10810. // IPv4 with non-default HTTPS port
  10811. EXPECT_EQ("example.com:8443",
  10812. detail::make_host_and_port_string("example.com", 8443, true));
  10813. // IPv6 with default HTTP port (80)
  10814. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10815. // IPv6 with default HTTPS port (443)
  10816. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10817. // IPv6 with non-default HTTP port
  10818. EXPECT_EQ("[::1]:8080",
  10819. detail::make_host_and_port_string("::1", 8080, false));
  10820. // IPv6 with non-default HTTPS port
  10821. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10822. // IPv6 full address with default port
  10823. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10824. detail::make_host_and_port_string(
  10825. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10826. // IPv6 full address with non-default port
  10827. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10828. detail::make_host_and_port_string(
  10829. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10830. // IPv6 localhost with non-default port
  10831. EXPECT_EQ("[::1]:3000",
  10832. detail::make_host_and_port_string("::1", 3000, false));
  10833. // IPv6 with zone ID (link-local address) with default port
  10834. EXPECT_EQ("[fe80::1%eth0]",
  10835. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10836. // IPv6 with zone ID (link-local address) with non-default port
  10837. EXPECT_EQ("[fe80::1%eth0]:8080",
  10838. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10839. // Edge case: Port 443 with is_ssl=false (should add port)
  10840. EXPECT_EQ("example.com:443",
  10841. detail::make_host_and_port_string("example.com", 443, false));
  10842. // Edge case: Port 80 with is_ssl=true (should add port)
  10843. EXPECT_EQ("example.com:80",
  10844. detail::make_host_and_port_string("example.com", 80, true));
  10845. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10846. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10847. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10848. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10849. // Security fix: Already bracketed IPv6 should not get double brackets
  10850. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10851. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10852. EXPECT_EQ("[::1]:8080",
  10853. detail::make_host_and_port_string("[::1]", 8080, false));
  10854. EXPECT_EQ("[2001:db8::1]:8080",
  10855. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10856. EXPECT_EQ("[fe80::1%eth0]",
  10857. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10858. EXPECT_EQ("[fe80::1%eth0]:8080",
  10859. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10860. // Edge case: Empty host (should return as-is)
  10861. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10862. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10863. // This is a known limitation but shouldn't crash
  10864. EXPECT_EQ("[host:name]",
  10865. detail::make_host_and_port_string("host:name", 80, false));
  10866. // Port number edge cases (no validation, but should not crash)
  10867. EXPECT_EQ("example.com:0",
  10868. detail::make_host_and_port_string("example.com", 0, false));
  10869. EXPECT_EQ("example.com:-1",
  10870. detail::make_host_and_port_string("example.com", -1, false));
  10871. EXPECT_EQ("example.com:65535",
  10872. detail::make_host_and_port_string("example.com", 65535, false));
  10873. EXPECT_EQ("example.com:65536",
  10874. detail::make_host_and_port_string("example.com", 65536, false));
  10875. }
  10876. #ifdef CPPHTTPLIB_SSL_ENABLED
  10877. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10878. httplib::SSLClient cli("roblox.com", 443);
  10879. cli.set_follow_location(true);
  10880. auto res = cli.Get("/");
  10881. ASSERT_TRUE(res);
  10882. EXPECT_EQ(StatusCode::OK_200, res->status);
  10883. }
  10884. #endif
  10885. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10886. Server svr;
  10887. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10888. EXPECT_EQ(res.status, 400);
  10889. });
  10890. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10891. auto se = detail::scope_exit([&] {
  10892. svr.stop();
  10893. thread.join();
  10894. ASSERT_FALSE(svr.is_running());
  10895. });
  10896. svr.wait_until_ready();
  10897. Client cli(HOST, PORT);
  10898. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10899. }
  10900. TEST(InvalidHeaderCharsTest, is_field_name) {
  10901. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10902. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10903. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10904. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10905. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10906. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10907. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10908. EXPECT_FALSE(detail::fields::is_field_name(""));
  10909. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10910. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10911. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10912. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10913. }
  10914. TEST(InvalidHeaderCharsTest, is_field_value) {
  10915. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10916. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10917. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10918. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10919. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10920. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10921. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10922. EXPECT_TRUE(detail::fields::is_field_value(""));
  10923. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10924. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10925. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10926. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10927. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10928. }
  10929. TEST(InvalidHeaderCharsTest, OnServer) {
  10930. Server svr;
  10931. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10932. std::string header = "Not Set";
  10933. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10934. res.set_header(header, "value");
  10935. res.set_content("Page Content Page Content", "text/plain");
  10936. });
  10937. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10938. std::string header = "Not Set";
  10939. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10940. res.set_header("X-Test", header);
  10941. res.set_content("Page Content Page Content", "text/plain");
  10942. });
  10943. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10944. auto se = detail::scope_exit([&] {
  10945. svr.stop();
  10946. thread.join();
  10947. ASSERT_FALSE(svr.is_running());
  10948. });
  10949. svr.wait_until_ready();
  10950. Client cli(HOST, PORT);
  10951. {
  10952. auto res = cli.Get(
  10953. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10954. ASSERT_TRUE(res);
  10955. EXPECT_EQ("Page Content Page Content", res->body);
  10956. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10957. }
  10958. {
  10959. auto res = cli.Get(
  10960. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10961. ASSERT_TRUE(res);
  10962. EXPECT_EQ("Page Content Page Content", res->body);
  10963. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10964. }
  10965. }
  10966. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10967. auto handled = false;
  10968. Server svr;
  10969. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10970. thread t = thread([&] { svr.listen(HOST, PORT); });
  10971. auto se = detail::scope_exit([&] {
  10972. svr.stop();
  10973. t.join();
  10974. ASSERT_FALSE(svr.is_running());
  10975. ASSERT_FALSE(handled);
  10976. });
  10977. svr.wait_until_ready();
  10978. auto req = "POST /test HTTP/1.1\r\n"
  10979. "Content-Length: x\r\n"
  10980. "\r\n";
  10981. std::string response;
  10982. ASSERT_TRUE(send_request(1, req, &response));
  10983. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  10984. response.substr(0, response.find("\r\n")));
  10985. }
  10986. #ifndef _WIN32
  10987. TEST(Expect100ContinueTest, ServerClosesConnection) {
  10988. static constexpr char reject[] = "Unauthorized";
  10989. static constexpr char accept[] = "Upload accepted";
  10990. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  10991. Server svr;
  10992. svr.set_expect_100_continue_handler(
  10993. [](const Request & /*req*/, Response &res) {
  10994. res.status = StatusCode::Unauthorized_401;
  10995. res.set_content(reject, "text/plain");
  10996. return res.status;
  10997. });
  10998. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  10999. res.set_content(accept, "text/plain");
  11000. });
  11001. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11002. auto se = detail::scope_exit([&] {
  11003. svr.stop();
  11004. thread.join();
  11005. ASSERT_FALSE(svr.is_running());
  11006. });
  11007. svr.wait_until_ready();
  11008. {
  11009. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11010. curl_easy_init(), &curl_easy_cleanup};
  11011. ASSERT_NE(curl, nullptr);
  11012. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11013. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11014. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11015. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11016. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11017. &curl_slist_free_all};
  11018. ASSERT_NE(list, nullptr);
  11019. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11020. struct read_data {
  11021. size_t read_size;
  11022. size_t total_size;
  11023. } data = {0, total_size};
  11024. using read_callback_t =
  11025. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11026. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11027. void *userdata) -> size_t {
  11028. read_data *data = (read_data *)userdata;
  11029. if (!userdata || data->read_size >= data->total_size) { return 0; }
  11030. std::fill_n(ptr, size * nmemb, 'A');
  11031. data->read_size += size * nmemb;
  11032. return size * nmemb;
  11033. };
  11034. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11035. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11036. std::vector<char> buffer;
  11037. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11038. using write_callback_t =
  11039. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11040. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11041. void *userdata) -> size_t {
  11042. std::vector<char> *buffer = (std::vector<char> *)userdata;
  11043. buffer->reserve(buffer->size() + size * nmemb + 1);
  11044. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11045. return size * nmemb;
  11046. };
  11047. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11048. {
  11049. const auto res = curl_easy_perform(curl.get());
  11050. ASSERT_EQ(res, CURLE_OK);
  11051. }
  11052. {
  11053. auto response_code = long{};
  11054. const auto res =
  11055. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11056. ASSERT_EQ(res, CURLE_OK);
  11057. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11058. }
  11059. {
  11060. auto dl = curl_off_t{};
  11061. const auto res =
  11062. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11063. ASSERT_EQ(res, CURLE_OK);
  11064. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11065. }
  11066. {
  11067. buffer.push_back('\0');
  11068. ASSERT_STRCASEEQ(buffer.data(), reject);
  11069. }
  11070. }
  11071. }
  11072. #endif
  11073. template <typename S, typename C>
  11074. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11075. svr.Get("/stream", [&](const Request &, Response &res) {
  11076. auto data = new std::string("01234567890123456789");
  11077. res.set_content_provider(
  11078. data->size(), "text/plain",
  11079. [&, data](size_t offset, size_t length, DataSink &sink) {
  11080. const size_t DATA_CHUNK_SIZE = 4;
  11081. const auto &d = *data;
  11082. std::this_thread::sleep_for(std::chrono::seconds(1));
  11083. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11084. return true;
  11085. },
  11086. [data](bool success) {
  11087. EXPECT_FALSE(success);
  11088. delete data;
  11089. });
  11090. });
  11091. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11092. auto i = new size_t(0);
  11093. res.set_content_provider(
  11094. "text/plain",
  11095. [i](size_t, DataSink &sink) {
  11096. if (*i < 5) {
  11097. std::this_thread::sleep_for(std::chrono::seconds(1));
  11098. sink.write("abcd", 4);
  11099. (*i)++;
  11100. } else {
  11101. sink.done();
  11102. }
  11103. return true;
  11104. },
  11105. [i](bool success) {
  11106. EXPECT_FALSE(success);
  11107. delete i;
  11108. });
  11109. });
  11110. svr.Get("/chunked", [&](const Request &, Response &res) {
  11111. auto i = new size_t(0);
  11112. res.set_chunked_content_provider(
  11113. "text/plain",
  11114. [i](size_t, DataSink &sink) {
  11115. if (*i < 5) {
  11116. std::this_thread::sleep_for(std::chrono::seconds(1));
  11117. sink.os << "abcd";
  11118. (*i)++;
  11119. } else {
  11120. sink.done();
  11121. }
  11122. return true;
  11123. },
  11124. [i](bool success) {
  11125. EXPECT_FALSE(success);
  11126. delete i;
  11127. });
  11128. });
  11129. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11130. auto se = detail::scope_exit([&] {
  11131. svr.stop();
  11132. listen_thread.join();
  11133. ASSERT_FALSE(svr.is_running());
  11134. });
  11135. svr.wait_until_ready();
  11136. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11137. {
  11138. auto start = std::chrono::steady_clock::now();
  11139. auto res = cli.Get("/stream");
  11140. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11141. std::chrono::steady_clock::now() - start)
  11142. .count();
  11143. ASSERT_FALSE(res);
  11144. EXPECT_EQ(Error::Read, res.error());
  11145. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11146. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11147. }
  11148. {
  11149. auto start = std::chrono::steady_clock::now();
  11150. auto res = cli.Get("/stream_without_length");
  11151. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11152. std::chrono::steady_clock::now() - start)
  11153. .count();
  11154. ASSERT_FALSE(res);
  11155. EXPECT_EQ(Error::Read, res.error());
  11156. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11157. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11158. }
  11159. {
  11160. auto start = std::chrono::steady_clock::now();
  11161. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11162. EXPECT_EQ("abcd", string(data, data_length));
  11163. return true;
  11164. });
  11165. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11166. std::chrono::steady_clock::now() - start)
  11167. .count();
  11168. ASSERT_FALSE(res);
  11169. EXPECT_EQ(Error::Read, res.error());
  11170. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11171. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11172. }
  11173. }
  11174. TEST(MaxTimeoutTest, ContentStream) {
  11175. time_t timeout = 2000;
  11176. time_t threshold = 200;
  11177. Server svr;
  11178. Client cli("localhost", PORT);
  11179. max_timeout_test(svr, cli, timeout, threshold);
  11180. }
  11181. #ifdef CPPHTTPLIB_SSL_ENABLED
  11182. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11183. time_t timeout = 2000;
  11184. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11186. SSLClient cli("localhost", PORT);
  11187. cli.enable_server_certificate_verification(false);
  11188. max_timeout_test(svr, cli, timeout, threshold);
  11189. }
  11190. #endif
  11191. class EventDispatcher {
  11192. public:
  11193. EventDispatcher() {}
  11194. bool wait_event(DataSink *sink) {
  11195. unique_lock<mutex> lk(m_);
  11196. int id = id_;
  11197. // Wait with timeout to prevent hanging if client disconnects
  11198. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11199. [&] { return cid_ == id; })) {
  11200. return false; // Timeout occurred
  11201. }
  11202. sink->write(message_.data(), message_.size());
  11203. return true;
  11204. }
  11205. void send_event(const string &message) {
  11206. lock_guard<mutex> lk(m_);
  11207. cid_ = id_++;
  11208. message_ = message;
  11209. cv_.notify_all();
  11210. }
  11211. private:
  11212. mutex m_;
  11213. condition_variable cv_;
  11214. atomic_int id_{0};
  11215. atomic_int cid_{-1};
  11216. string message_;
  11217. };
  11218. TEST(ClientInThreadTest, Issue2068) {
  11219. EventDispatcher ed;
  11220. Server svr;
  11221. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11222. res.set_chunked_content_provider("text/event-stream",
  11223. [&](size_t /*offset*/, DataSink &sink) {
  11224. return ed.wait_event(&sink);
  11225. });
  11226. });
  11227. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11228. svr.wait_until_ready();
  11229. thread event_thread([&] {
  11230. int id = 0;
  11231. while (svr.is_running()) {
  11232. this_thread::sleep_for(chrono::milliseconds(500));
  11233. std::stringstream ss;
  11234. ss << "data: " << id << "\n\n";
  11235. ed.send_event(ss.str());
  11236. id++;
  11237. }
  11238. });
  11239. auto se = detail::scope_exit([&] {
  11240. svr.stop();
  11241. listen_thread.join();
  11242. event_thread.join();
  11243. ASSERT_FALSE(svr.is_running());
  11244. });
  11245. {
  11246. auto client = detail::make_unique<Client>(HOST, PORT);
  11247. client->set_read_timeout(std::chrono::minutes(10));
  11248. std::atomic<bool> stop{false};
  11249. std::thread t([&] {
  11250. client->Get("/event1",
  11251. [&](const char *, size_t) -> bool { return !stop; });
  11252. });
  11253. std::this_thread::sleep_for(std::chrono::seconds(2));
  11254. stop = true;
  11255. client->stop();
  11256. t.join();
  11257. // Reset client after thread has finished
  11258. client.reset();
  11259. }
  11260. }
  11261. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11262. auto handled = false;
  11263. Server svr;
  11264. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11265. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11266. auto se = detail::scope_exit([&] {
  11267. svr.stop();
  11268. t.join();
  11269. ASSERT_FALSE(svr.is_running());
  11270. ASSERT_FALSE(handled);
  11271. });
  11272. svr.wait_until_ready();
  11273. // Two Content-Length headers with different values — must be rejected
  11274. auto req = "POST /test HTTP/1.1\r\n"
  11275. "Content-Length: 5\r\n"
  11276. "Content-Length: 10\r\n"
  11277. "\r\n"
  11278. "hello";
  11279. std::string response;
  11280. ASSERT_TRUE(send_request(1, req, &response));
  11281. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11282. response.substr(0, response.find("\r\n")));
  11283. }
  11284. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11285. auto handled = false;
  11286. Server svr;
  11287. svr.Post("/test", [&](const Request &, Response &res) {
  11288. handled = true;
  11289. res.set_content("ok", "text/plain");
  11290. });
  11291. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11292. auto se = detail::scope_exit([&] {
  11293. svr.stop();
  11294. t.join();
  11295. ASSERT_FALSE(svr.is_running());
  11296. ASSERT_TRUE(handled);
  11297. });
  11298. svr.wait_until_ready();
  11299. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11300. auto req = "POST /test HTTP/1.1\r\n"
  11301. "Content-Length: 5\r\n"
  11302. "Content-Length: 5\r\n"
  11303. "\r\n"
  11304. "hello";
  11305. std::string response;
  11306. ASSERT_TRUE(send_request(1, req, &response));
  11307. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11308. }
  11309. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11310. Server svr;
  11311. svr.Get("/", [](const Request &req, Response &res) {
  11312. EXPECT_EQ(2U, req.trailers.size());
  11313. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11314. // Denied
  11315. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11316. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11317. // Accepted
  11318. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11319. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11320. EXPECT_TRUE(req.has_trailer("X-World"));
  11321. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11322. res.set_content("ok", "text/plain");
  11323. });
  11324. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11325. auto se = detail::scope_exit([&] {
  11326. svr.stop();
  11327. t.join();
  11328. ASSERT_FALSE(svr.is_running());
  11329. });
  11330. svr.wait_until_ready();
  11331. const std::string req = "GET / HTTP/1.1\r\n"
  11332. "Transfer-Encoding: chunked\r\n"
  11333. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11334. "\r\n"
  11335. "0\r\n"
  11336. "Content-Length: 10\r\n"
  11337. "Host: internal.local\r\n"
  11338. "Content-Type: malicious/content\r\n"
  11339. "Cookie: any\r\n"
  11340. "Set-Cookie: any\r\n"
  11341. "X-Forwarded-For: attacker.com\r\n"
  11342. "X-Real-Ip: 1.1.1.1\r\n"
  11343. "X-Hello: hello\r\n"
  11344. "X-World: world\r\n"
  11345. "\r\n";
  11346. std::string res;
  11347. ASSERT_TRUE(send_request(1, req, &res));
  11348. }
  11349. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11350. Server svr;
  11351. std::string observed_remote_addr;
  11352. std::string observed_xff;
  11353. svr.Get("/ip", [&](const Request &req, Response &res) {
  11354. observed_remote_addr = req.remote_addr;
  11355. observed_xff = req.get_header_value("X-Forwarded-For");
  11356. res.set_content("ok", "text/plain");
  11357. });
  11358. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11359. auto se = detail::scope_exit([&] {
  11360. svr.stop();
  11361. t.join();
  11362. ASSERT_FALSE(svr.is_running());
  11363. });
  11364. svr.wait_until_ready();
  11365. Client cli(HOST, PORT);
  11366. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11367. ASSERT_TRUE(res);
  11368. EXPECT_EQ(StatusCode::OK_200, res->status);
  11369. EXPECT_EQ(observed_xff, "203.0.113.66");
  11370. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11371. observed_remote_addr == "127.0.0.1");
  11372. }
  11373. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11374. Server svr;
  11375. svr.set_trusted_proxies({"203.0.113.66"});
  11376. std::string observed_remote_addr;
  11377. std::string observed_xff;
  11378. svr.Get("/ip", [&](const Request &req, Response &res) {
  11379. observed_remote_addr = req.remote_addr;
  11380. observed_xff = req.get_header_value("X-Forwarded-For");
  11381. res.set_content("ok", "text/plain");
  11382. });
  11383. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11384. auto se = detail::scope_exit([&] {
  11385. svr.stop();
  11386. t.join();
  11387. ASSERT_FALSE(svr.is_running());
  11388. });
  11389. svr.wait_until_ready();
  11390. Client cli(HOST, PORT);
  11391. auto res = cli.Get("/ip");
  11392. ASSERT_TRUE(res);
  11393. EXPECT_EQ(StatusCode::OK_200, res->status);
  11394. EXPECT_EQ(observed_xff, "");
  11395. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11396. observed_remote_addr == "127.0.0.1");
  11397. }
  11398. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11399. Server svr;
  11400. svr.set_trusted_proxies({"203.0.113.66"});
  11401. std::string observed_remote_addr;
  11402. std::string observed_xff;
  11403. svr.Get("/ip", [&](const Request &req, Response &res) {
  11404. observed_remote_addr = req.remote_addr;
  11405. observed_xff = req.get_header_value("X-Forwarded-For");
  11406. res.set_content("ok", "text/plain");
  11407. });
  11408. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11409. auto se = detail::scope_exit([&] {
  11410. svr.stop();
  11411. t.join();
  11412. ASSERT_FALSE(svr.is_running());
  11413. });
  11414. svr.wait_until_ready();
  11415. Client cli(HOST, PORT);
  11416. auto res =
  11417. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11418. ASSERT_TRUE(res);
  11419. EXPECT_EQ(StatusCode::OK_200, res->status);
  11420. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11421. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11422. }
  11423. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11424. Server svr;
  11425. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11426. std::string observed_remote_addr;
  11427. std::string observed_xff;
  11428. svr.Get("/ip", [&](const Request &req, Response &res) {
  11429. observed_remote_addr = req.remote_addr;
  11430. observed_xff = req.get_header_value("X-Forwarded-For");
  11431. res.set_content("ok", "text/plain");
  11432. });
  11433. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11434. auto se = detail::scope_exit([&] {
  11435. svr.stop();
  11436. t.join();
  11437. ASSERT_FALSE(svr.is_running());
  11438. });
  11439. svr.wait_until_ready();
  11440. Client cli(HOST, PORT);
  11441. auto res = cli.Get(
  11442. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11443. ASSERT_TRUE(res);
  11444. EXPECT_EQ(StatusCode::OK_200, res->status);
  11445. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11446. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11447. }
  11448. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11449. Server svr;
  11450. svr.set_trusted_proxies({"192.0.2.45"});
  11451. std::string observed_remote_addr;
  11452. std::string observed_xff;
  11453. svr.Get("/ip", [&](const Request &req, Response &res) {
  11454. observed_remote_addr = req.remote_addr;
  11455. observed_xff = req.get_header_value("X-Forwarded-For");
  11456. res.set_content("ok", "text/plain");
  11457. });
  11458. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11459. auto se = detail::scope_exit([&] {
  11460. svr.stop();
  11461. t.join();
  11462. ASSERT_FALSE(svr.is_running());
  11463. });
  11464. svr.wait_until_ready();
  11465. Client cli(HOST, PORT);
  11466. auto res =
  11467. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11468. ASSERT_TRUE(res);
  11469. EXPECT_EQ(StatusCode::OK_200, res->status);
  11470. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11471. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11472. }
  11473. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11474. Server svr;
  11475. svr.set_trusted_proxies({"192.0.2.45"});
  11476. std::string observed_remote_addr;
  11477. std::string observed_xff;
  11478. svr.Get("/ip", [&](const Request &req, Response &res) {
  11479. observed_remote_addr = req.remote_addr;
  11480. observed_xff = req.get_header_value("X-Forwarded-For");
  11481. res.set_content("ok", "text/plain");
  11482. });
  11483. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11484. auto se = detail::scope_exit([&] {
  11485. svr.stop();
  11486. t.join();
  11487. ASSERT_FALSE(svr.is_running());
  11488. });
  11489. svr.wait_until_ready();
  11490. Client cli(HOST, PORT);
  11491. auto res = cli.Get(
  11492. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11493. ASSERT_TRUE(res);
  11494. EXPECT_EQ(StatusCode::OK_200, res->status);
  11495. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11496. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11497. }
  11498. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11499. Server svr;
  11500. svr.set_trusted_proxies({"192.0.2.45"});
  11501. std::string observed_remote_addr;
  11502. std::string observed_xff;
  11503. svr.Get("/ip", [&](const Request &req, Response &res) {
  11504. observed_remote_addr = req.remote_addr;
  11505. observed_xff = req.get_header_value("X-Forwarded-For");
  11506. res.set_content("ok", "text/plain");
  11507. });
  11508. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11509. auto se = detail::scope_exit([&] {
  11510. svr.stop();
  11511. t.join();
  11512. ASSERT_FALSE(svr.is_running());
  11513. });
  11514. svr.wait_until_ready();
  11515. std::string raw_req =
  11516. "GET /ip HTTP/1.1\r\n"
  11517. "Host: localhost\r\n"
  11518. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11519. "Connection: close\r\n"
  11520. "\r\n";
  11521. std::string out;
  11522. ASSERT_TRUE(send_request(5, raw_req, &out));
  11523. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11524. // Header parser trims surrounding whitespace of the header value
  11525. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11526. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11527. }
  11528. #ifndef _WIN32
  11529. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11530. Server svr;
  11531. svr.Post("/post", [&](const Request &req, Response &res) {
  11532. res.set_content(req.body, "text/plain");
  11533. });
  11534. svr.Put("/put", [&](const Request &req, Response &res) {
  11535. res.set_content(req.body, "text/plain");
  11536. });
  11537. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11538. res.set_content(req.body, "text/plain");
  11539. });
  11540. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11541. res.set_content(req.body, "text/plain");
  11542. });
  11543. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. t.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. std::string resp;
  11551. // POST without Content-Length
  11552. ASSERT_TRUE(send_request(5,
  11553. "POST /post HTTP/1.1\r\n"
  11554. "Host: localhost\r\n"
  11555. "Connection: close\r\n"
  11556. "\r\n",
  11557. &resp));
  11558. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11559. // PUT without Content-Length
  11560. resp.clear();
  11561. ASSERT_TRUE(send_request(5,
  11562. "PUT /put HTTP/1.1\r\n"
  11563. "Host: localhost\r\n"
  11564. "Connection: close\r\n"
  11565. "\r\n",
  11566. &resp));
  11567. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11568. // PATCH without Content-Length
  11569. resp.clear();
  11570. ASSERT_TRUE(send_request(5,
  11571. "PATCH /patch HTTP/1.1\r\n"
  11572. "Host: localhost\r\n"
  11573. "Connection: close\r\n"
  11574. "\r\n",
  11575. &resp));
  11576. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11577. // DELETE without Content-Length
  11578. resp.clear();
  11579. ASSERT_TRUE(send_request(5,
  11580. "DELETE /delete HTTP/1.1\r\n"
  11581. "Host: localhost\r\n"
  11582. "Connection: close\r\n"
  11583. "\r\n",
  11584. &resp));
  11585. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11586. }
  11587. #endif
  11588. //==============================================================================
  11589. // open_stream() Tests
  11590. //==============================================================================
  11591. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11592. std::string result;
  11593. char buf[8192];
  11594. ssize_t n;
  11595. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11596. result.append(buf, static_cast<size_t>(n));
  11597. }
  11598. return result;
  11599. }
  11600. // Mock stream for unit tests
  11601. class MockStream : public Stream {
  11602. public:
  11603. std::string data;
  11604. size_t pos = 0;
  11605. ssize_t error_after = -1; // -1 = no error
  11606. explicit MockStream(const std::string &d, ssize_t err = -1)
  11607. : data(d), error_after(err) {}
  11608. bool is_readable() const override { return true; }
  11609. bool wait_readable() const override { return true; }
  11610. bool wait_writable() const override { return true; }
  11611. ssize_t read(char *ptr, size_t size) override {
  11612. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11613. if (pos >= data.size()) return 0;
  11614. size_t limit =
  11615. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11616. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11617. std::memcpy(ptr, data.data() + pos, to_read);
  11618. pos += to_read;
  11619. return static_cast<ssize_t>(to_read);
  11620. }
  11621. ssize_t write(const char *, size_t) override { return -1; }
  11622. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11623. ip = "127.0.0.1";
  11624. port = 0;
  11625. }
  11626. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11627. ip = "127.0.0.1";
  11628. port = 0;
  11629. }
  11630. socket_t socket() const override { return INVALID_SOCKET; }
  11631. time_t duration() const override { return 0; }
  11632. };
  11633. TEST(StreamHandleTest, Basic) {
  11634. ClientImpl::StreamHandle handle;
  11635. EXPECT_FALSE(handle.is_valid());
  11636. handle.response = detail::make_unique<Response>();
  11637. handle.error = Error::Connection;
  11638. EXPECT_FALSE(handle.is_valid());
  11639. handle.error = Error::Success;
  11640. EXPECT_TRUE(handle.is_valid());
  11641. }
  11642. TEST(BodyReaderTest, Basic) {
  11643. MockStream stream("Hello, World!");
  11644. detail::BodyReader reader;
  11645. reader.stream = &stream;
  11646. reader.content_length = 13;
  11647. char buf[32];
  11648. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11649. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11650. EXPECT_TRUE(reader.eof);
  11651. }
  11652. TEST(BodyReaderTest, NoStream) {
  11653. detail::BodyReader reader;
  11654. char buf[32];
  11655. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11656. EXPECT_EQ(Error::Connection, reader.last_error);
  11657. }
  11658. TEST(BodyReaderTest, Error) {
  11659. MockStream stream("Hello, World!", 5);
  11660. detail::BodyReader reader;
  11661. reader.stream = &stream;
  11662. reader.content_length = 13;
  11663. char buf[32];
  11664. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11665. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11666. EXPECT_EQ(Error::Read, reader.last_error);
  11667. }
  11668. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11669. // Mock-based StreamHandle tests relying on private internals are removed.
  11670. class OpenStreamTest : public ::testing::Test {
  11671. protected:
  11672. void SetUp() override {
  11673. svr_.Get("/hello", [](const Request &, Response &res) {
  11674. res.set_content("Hello World!", "text/plain");
  11675. });
  11676. svr_.Get("/large", [](const Request &, Response &res) {
  11677. res.set_content(std::string(10000, 'X'), "text/plain");
  11678. });
  11679. svr_.Get("/chunked", [](const Request &, Response &res) {
  11680. res.set_chunked_content_provider("text/plain",
  11681. [](size_t offset, DataSink &sink) {
  11682. if (offset < 15) {
  11683. sink.write("chunk", 5);
  11684. return true;
  11685. }
  11686. sink.done();
  11687. return true;
  11688. });
  11689. });
  11690. svr_.Get("/compressible", [](const Request &, Response &res) {
  11691. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11692. DataSink &sink) {
  11693. if (offset < 100 * 1024) {
  11694. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11695. sink.write(chunk.data(), chunk.size());
  11696. return true;
  11697. }
  11698. sink.done();
  11699. return true;
  11700. });
  11701. });
  11702. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11703. [](const Request & /*req*/, Response &res) {
  11704. auto i = new int(0);
  11705. res.set_header("Trailer", "Content-Length, X-Allowed");
  11706. res.set_chunked_content_provider(
  11707. "text/plain",
  11708. [i](size_t /*offset*/, DataSink &sink) {
  11709. switch (*i) {
  11710. case 0: sink.os << "123"; break;
  11711. case 1: sink.os << "456"; break;
  11712. case 2: sink.os << "789"; break;
  11713. case 3: {
  11714. sink.done_with_trailer(
  11715. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11716. } break;
  11717. }
  11718. (*i)++;
  11719. return true;
  11720. },
  11721. [i](bool success) {
  11722. EXPECT_TRUE(success);
  11723. delete i;
  11724. });
  11725. });
  11726. // Echo headers endpoint for header-related tests
  11727. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11728. std::string body;
  11729. for (const auto &h : req.headers) {
  11730. body.append(h.first);
  11731. body.push_back(':');
  11732. body.append(h.second);
  11733. body.push_back('\n');
  11734. }
  11735. res.set_content(body, "text/plain");
  11736. });
  11737. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11738. std::string body;
  11739. for (const auto &h : req.headers) {
  11740. body.append(h.first);
  11741. body.push_back(':');
  11742. body.append(h.second);
  11743. body.push_back('\n');
  11744. }
  11745. res.set_content(body, "text/plain");
  11746. });
  11747. port_ = svr_.bind_to_any_port("127.0.0.1");
  11748. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11749. svr_.wait_until_ready();
  11750. }
  11751. void TearDown() override {
  11752. svr_.stop();
  11753. if (thread_.joinable()) thread_.join();
  11754. }
  11755. Server svr_;
  11756. std::thread thread_;
  11757. int port_ = 0;
  11758. };
  11759. TEST_F(OpenStreamTest, Basic) {
  11760. Client cli("127.0.0.1", port_);
  11761. auto handle = cli.open_stream("GET", "/hello");
  11762. EXPECT_TRUE(handle.is_valid());
  11763. EXPECT_EQ("Hello World!", read_all(handle));
  11764. }
  11765. TEST_F(OpenStreamTest, SmallBuffer) {
  11766. Client cli("127.0.0.1", port_);
  11767. auto handle = cli.open_stream("GET", "/hello");
  11768. std::string result;
  11769. char buf[4];
  11770. ssize_t n;
  11771. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11772. result.append(buf, static_cast<size_t>(n));
  11773. EXPECT_EQ("Hello World!", result);
  11774. }
  11775. TEST_F(OpenStreamTest, DefaultHeaders) {
  11776. Client cli("127.0.0.1", port_);
  11777. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11778. {
  11779. auto handle = cli.open_stream("GET", "/echo-headers");
  11780. ASSERT_TRUE(handle.is_valid());
  11781. auto body = read_all(handle);
  11782. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11783. std::string::npos);
  11784. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11785. std::string::npos);
  11786. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11787. }
  11788. // open_stream POST with body and no explicit content_type should NOT add
  11789. // text/plain Content-Type (behavior differs from non-streaming path), but
  11790. // should include Content-Length
  11791. {
  11792. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11793. ASSERT_TRUE(handle.is_valid());
  11794. auto body = read_all(handle);
  11795. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11796. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11797. }
  11798. // open_stream POST with explicit Content-Type should preserve it
  11799. {
  11800. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11801. {{"Content-Type", "application/custom"}},
  11802. "{}", "application/custom");
  11803. ASSERT_TRUE(handle.is_valid());
  11804. auto body = read_all(handle);
  11805. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11806. }
  11807. // User-specified User-Agent must not be overwritten for stream API
  11808. {
  11809. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11810. {{"User-Agent", "MyAgent/1.2"}});
  11811. ASSERT_TRUE(handle.is_valid());
  11812. auto body = read_all(handle);
  11813. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11814. }
  11815. }
  11816. TEST_F(OpenStreamTest, Large) {
  11817. Client cli("127.0.0.1", port_);
  11818. auto handle = cli.open_stream("GET", "/large");
  11819. EXPECT_EQ(10000u, read_all(handle).size());
  11820. }
  11821. TEST_F(OpenStreamTest, ConnectionError) {
  11822. Client cli("127.0.0.1", 9999);
  11823. auto handle = cli.open_stream("GET", "/hello");
  11824. EXPECT_FALSE(handle.is_valid());
  11825. }
  11826. TEST_F(OpenStreamTest, Chunked) {
  11827. Client cli("127.0.0.1", port_);
  11828. auto handle = cli.open_stream("GET", "/chunked");
  11829. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11830. "Transfer-Encoding") == "chunked");
  11831. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11832. }
  11833. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11834. Client cli("127.0.0.1", port_);
  11835. auto handle =
  11836. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11837. ASSERT_TRUE(handle.is_valid());
  11838. // Consume body to allow trailers to be received/parsed
  11839. auto body = read_all(handle);
  11840. // Explicitly parse trailers (ensure trailers are available for assertion)
  11841. handle.parse_trailers_if_needed();
  11842. EXPECT_EQ(std::string("123456789"), body);
  11843. // The response should include a Trailer header declaring both names
  11844. ASSERT_TRUE(handle.response);
  11845. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11846. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11847. handle.response->get_header_value("Trailer"));
  11848. // Prohibited trailer must not be present
  11849. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11850. // Allowed trailer should be present
  11851. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11852. EXPECT_EQ(std::string("yes"),
  11853. handle.response->get_trailer_value("X-Allowed"));
  11854. // Verify trailers are NOT present as regular headers
  11855. EXPECT_EQ(std::string(""),
  11856. handle.response->get_header_value("Content-Length"));
  11857. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11858. }
  11859. static std::thread serve_single_response(std::promise<int> &port_promise,
  11860. const std::string &response) {
  11861. return std::thread([&port_promise, response] {
  11862. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11863. default_socket_options(srv);
  11864. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11865. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11866. sockaddr_in addr{};
  11867. addr.sin_family = AF_INET;
  11868. addr.sin_port = htons(0); // Let OS assign a free port
  11869. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11870. int opt = 1;
  11871. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11872. #ifdef _WIN32
  11873. reinterpret_cast<const char *>(&opt),
  11874. #else
  11875. &opt,
  11876. #endif
  11877. sizeof(opt));
  11878. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11879. ::listen(srv, 1) != 0) {
  11880. port_promise.set_value(-1);
  11881. detail::close_socket(srv);
  11882. return;
  11883. }
  11884. socklen_t addr_len = sizeof(addr);
  11885. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11886. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11887. sockaddr_in cli_addr{};
  11888. socklen_t cli_len = sizeof(cli_addr);
  11889. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11890. if (cli != INVALID_SOCKET) {
  11891. char buf[4096];
  11892. ::recv(cli, buf, sizeof(buf), 0);
  11893. ::send(cli,
  11894. #ifdef _WIN32
  11895. static_cast<const char *>(response.c_str()),
  11896. static_cast<int>(response.size()),
  11897. #else
  11898. response.c_str(), response.size(),
  11899. #endif
  11900. 0);
  11901. detail::close_socket(cli);
  11902. }
  11903. detail::close_socket(srv);
  11904. });
  11905. }
  11906. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11907. #ifndef _WIN32
  11908. signal(SIGPIPE, SIG_IGN);
  11909. #endif
  11910. std::promise<int> port_promise;
  11911. auto port_future = port_promise.get_future();
  11912. auto server_thread =
  11913. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11914. "Content-Type: text/plain\r\n"
  11915. "Content-Length: not-a-number\r\n"
  11916. "Connection: close\r\n"
  11917. "\r\n"
  11918. "hello");
  11919. auto port = port_future.get();
  11920. ASSERT_GT(port, 0);
  11921. Client cli("127.0.0.1", port);
  11922. auto handle = cli.open_stream("GET", "/");
  11923. EXPECT_FALSE(handle.is_valid());
  11924. server_thread.join();
  11925. }
  11926. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11927. #ifndef _WIN32
  11928. signal(SIGPIPE, SIG_IGN);
  11929. #endif
  11930. std::promise<int> port_promise;
  11931. auto port_future = port_promise.get_future();
  11932. auto server_thread = serve_single_response(
  11933. port_promise, "HTTP/1.1 200 OK\r\n"
  11934. "Content-Type: text/plain\r\n"
  11935. "Content-Length: 99999999999999999999999999\r\n"
  11936. "Connection: close\r\n"
  11937. "\r\n"
  11938. "hello");
  11939. auto port = port_future.get();
  11940. ASSERT_GT(port, 0);
  11941. // Before the fix, std::stoull would throw std::out_of_range here and
  11942. // crash the process. After the fix, strtoull silently clamps to
  11943. // ULLONG_MAX so the stream opens without crashing. The important thing
  11944. // is that the process does NOT terminate.
  11945. Client cli("127.0.0.1", port);
  11946. auto handle = cli.open_stream("GET", "/");
  11947. EXPECT_TRUE(handle.is_valid());
  11948. server_thread.join();
  11949. }
  11950. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11951. TEST_F(OpenStreamTest, Gzip) {
  11952. Client cli("127.0.0.1", port_);
  11953. auto handle = cli.open_stream("GET", "/compressible", {},
  11954. {{"Accept-Encoding", "gzip"}});
  11955. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11956. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11957. }
  11958. #endif
  11959. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11960. TEST_F(OpenStreamTest, Brotli) {
  11961. Client cli("127.0.0.1", port_);
  11962. auto handle =
  11963. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11964. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11965. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11966. }
  11967. #endif
  11968. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11969. TEST_F(OpenStreamTest, Zstd) {
  11970. Client cli("127.0.0.1", port_);
  11971. auto handle = cli.open_stream("GET", "/compressible", {},
  11972. {{"Accept-Encoding", "zstd"}});
  11973. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11974. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11975. }
  11976. #endif
  11977. #ifdef CPPHTTPLIB_SSL_ENABLED
  11978. class SSLOpenStreamTest : public ::testing::Test {
  11979. protected:
  11980. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11981. void SetUp() override {
  11982. svr_.Get("/hello", [](const Request &, Response &res) {
  11983. res.set_content("Hello SSL World!", "text/plain");
  11984. });
  11985. svr_.Get("/chunked", [](const Request &, Response &res) {
  11986. res.set_chunked_content_provider("text/plain",
  11987. [](size_t offset, DataSink &sink) {
  11988. if (offset < 15) {
  11989. sink.write("chunk", 5);
  11990. return true;
  11991. }
  11992. sink.done();
  11993. return true;
  11994. });
  11995. });
  11996. svr_.Post("/echo", [](const Request &req, Response &res) {
  11997. res.set_content(req.body, req.get_header_value("Content-Type"));
  11998. });
  11999. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12000. std::string body = req.body;
  12001. res.set_chunked_content_provider(
  12002. "text/plain", [body](size_t offset, DataSink &sink) {
  12003. if (offset < body.size()) {
  12004. sink.write(body.data() + offset, body.size() - offset);
  12005. }
  12006. sink.done();
  12007. return true;
  12008. });
  12009. });
  12010. port_ = svr_.bind_to_any_port("127.0.0.1");
  12011. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12012. svr_.wait_until_ready();
  12013. }
  12014. void TearDown() override {
  12015. svr_.stop();
  12016. if (thread_.joinable()) thread_.join();
  12017. }
  12018. SSLServer svr_;
  12019. std::thread thread_;
  12020. int port_ = 0;
  12021. };
  12022. TEST_F(SSLOpenStreamTest, Basic) {
  12023. SSLClient cli("127.0.0.1", port_);
  12024. cli.enable_server_certificate_verification(false);
  12025. auto handle = cli.open_stream("GET", "/hello");
  12026. ASSERT_TRUE(handle.is_valid());
  12027. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12028. }
  12029. TEST_F(SSLOpenStreamTest, Chunked) {
  12030. SSLClient cli("127.0.0.1", port_);
  12031. cli.enable_server_certificate_verification(false);
  12032. auto handle = cli.open_stream("GET", "/chunked");
  12033. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12034. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12035. "Transfer-Encoding") == "chunked");
  12036. auto body = read_all(handle);
  12037. EXPECT_EQ("chunkchunkchunk", body);
  12038. }
  12039. TEST_F(SSLOpenStreamTest, Post) {
  12040. SSLClient cli("127.0.0.1", port_);
  12041. cli.enable_server_certificate_verification(false);
  12042. auto handle =
  12043. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12044. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12045. EXPECT_EQ(200, handle.response->status);
  12046. auto body = read_all(handle);
  12047. EXPECT_EQ("Hello SSL POST", body);
  12048. }
  12049. TEST_F(SSLOpenStreamTest, PostChunked) {
  12050. SSLClient cli("127.0.0.1", port_);
  12051. cli.enable_server_certificate_verification(false);
  12052. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12053. "Chunked SSL Data", "text/plain");
  12054. ASSERT_TRUE(handle.is_valid());
  12055. EXPECT_EQ(200, handle.response->status);
  12056. auto body = read_all(handle);
  12057. EXPECT_EQ("Chunked SSL Data", body);
  12058. }
  12059. #endif // CPPHTTPLIB_SSL_ENABLED
  12060. //==============================================================================
  12061. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12062. // results for various scenarios.
  12063. //==============================================================================
  12064. TEST(ParityTest, GetVsOpenStream) {
  12065. Server svr;
  12066. const std::string path = "/parity";
  12067. const std::string content = "Parity test content: hello world";
  12068. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12069. res.set_content(content, "text/plain");
  12070. });
  12071. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12072. auto se = detail::scope_exit([&] {
  12073. svr.stop();
  12074. t.join();
  12075. ASSERT_FALSE(svr.is_running());
  12076. });
  12077. svr.wait_until_ready();
  12078. Client cli(HOST, PORT);
  12079. // Non-stream path
  12080. auto r1 = cli.Get(path);
  12081. ASSERT_TRUE(r1);
  12082. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12083. // Stream path
  12084. auto h = cli.open_stream("GET", path);
  12085. ASSERT_TRUE(h.is_valid());
  12086. EXPECT_EQ(r1->body, read_all(h));
  12087. }
  12088. // Helper to compress data with provided compressor type T
  12089. template <typename Compressor>
  12090. static std::string compress_payload_for_parity(const std::string &in) {
  12091. std::string out;
  12092. Compressor compressor;
  12093. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12094. [&](const char *data, size_t n) {
  12095. out.append(data, n);
  12096. return true;
  12097. });
  12098. EXPECT_TRUE(ok);
  12099. return out;
  12100. }
  12101. // Helper function for compression parity tests
  12102. template <typename Compressor>
  12103. static void test_compression_parity(const std::string &original,
  12104. const std::string &path,
  12105. const std::string &encoding) {
  12106. const std::string compressed =
  12107. compress_payload_for_parity<Compressor>(original);
  12108. Server svr;
  12109. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12110. res.set_content(compressed, "application/octet-stream");
  12111. res.set_header("Content-Encoding", encoding);
  12112. });
  12113. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12114. auto se = detail::scope_exit([&] {
  12115. svr.stop();
  12116. t.join();
  12117. ASSERT_FALSE(svr.is_running());
  12118. });
  12119. svr.wait_until_ready();
  12120. Client cli(HOST, PORT);
  12121. // Non-streaming
  12122. {
  12123. auto res = cli.Get(path);
  12124. ASSERT_TRUE(res);
  12125. EXPECT_EQ(StatusCode::OK_200, res->status);
  12126. EXPECT_EQ(original, res->body);
  12127. }
  12128. // Streaming
  12129. {
  12130. auto h = cli.open_stream("GET", path);
  12131. ASSERT_TRUE(h.is_valid());
  12132. EXPECT_EQ(original, read_all(h));
  12133. }
  12134. }
  12135. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12136. TEST(ParityTest, Gzip) {
  12137. test_compression_parity<detail::gzip_compressor>(
  12138. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12139. }
  12140. #endif
  12141. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12142. TEST(ParityTest, Brotli) {
  12143. test_compression_parity<detail::brotli_compressor>(
  12144. "Hello, brotli parity test payload", "/parity-br", "br");
  12145. }
  12146. #endif
  12147. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12148. TEST(ParityTest, Zstd) {
  12149. test_compression_parity<detail::zstd_compressor>(
  12150. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12151. }
  12152. #endif
  12153. //==============================================================================
  12154. // New Stream API Tests
  12155. //==============================================================================
  12156. inline std::string read_body(httplib::stream::Result &result) {
  12157. std::string body;
  12158. while (result.next()) {
  12159. body.append(result.data(), result.size());
  12160. }
  12161. return body;
  12162. }
  12163. TEST(ClientConnectionTest, Basic) {
  12164. httplib::ClientConnection conn;
  12165. EXPECT_FALSE(conn.is_open());
  12166. conn.sock = 1;
  12167. EXPECT_TRUE(conn.is_open());
  12168. httplib::ClientConnection conn2(std::move(conn));
  12169. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12170. conn2.sock = INVALID_SOCKET;
  12171. }
  12172. // Unified test server for all stream::* tests
  12173. class StreamApiTest : public ::testing::Test {
  12174. protected:
  12175. void SetUp() override {
  12176. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12177. res.set_content("Hello World!", "text/plain");
  12178. });
  12179. svr_.Get("/echo-params",
  12180. [](const httplib::Request &req, httplib::Response &res) {
  12181. std::string r;
  12182. for (const auto &p : req.params) {
  12183. if (!r.empty()) r += "&";
  12184. r += p.first + "=" + p.second;
  12185. }
  12186. res.set_content(r, "text/plain");
  12187. });
  12188. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12189. res.set_content(req.body, req.get_header_value("Content-Type"));
  12190. });
  12191. svr_.Post("/echo-headers",
  12192. [](const httplib::Request &req, httplib::Response &res) {
  12193. std::string r;
  12194. for (const auto &h : req.headers)
  12195. r += h.first + ": " + h.second + "\n";
  12196. res.set_content(r, "text/plain");
  12197. });
  12198. svr_.Post("/echo-params",
  12199. [](const httplib::Request &req, httplib::Response &res) {
  12200. std::string r = "params:";
  12201. for (const auto &p : req.params)
  12202. r += p.first + "=" + p.second + ";";
  12203. res.set_content(r + " body:" + req.body, "text/plain");
  12204. });
  12205. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12206. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12207. });
  12208. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12209. res.set_content("PUT:" + req.body, "text/plain");
  12210. });
  12211. svr_.Patch("/echo",
  12212. [](const httplib::Request &req, httplib::Response &res) {
  12213. res.set_content("PATCH:" + req.body, "text/plain");
  12214. });
  12215. svr_.Delete(
  12216. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12217. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12218. "text/plain");
  12219. });
  12220. svr_.Get("/head-test",
  12221. [](const httplib::Request &, httplib::Response &res) {
  12222. res.set_content("body for HEAD", "text/plain");
  12223. });
  12224. svr_.Options("/options",
  12225. [](const httplib::Request &, httplib::Response &res) {
  12226. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12227. });
  12228. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12229. svr_.wait_until_ready();
  12230. }
  12231. void TearDown() override {
  12232. svr_.stop();
  12233. if (thread_.joinable()) thread_.join();
  12234. }
  12235. httplib::Server svr_;
  12236. std::thread thread_;
  12237. };
  12238. // stream::Get tests
  12239. TEST_F(StreamApiTest, GetBasic) {
  12240. httplib::Client cli(HOST, PORT);
  12241. auto result = httplib::stream::Get(cli, "/hello");
  12242. ASSERT_TRUE(result.is_valid());
  12243. EXPECT_EQ(200, result.status());
  12244. EXPECT_EQ("Hello World!", read_body(result));
  12245. }
  12246. TEST_F(StreamApiTest, GetWithParams) {
  12247. httplib::Client cli(HOST, PORT);
  12248. httplib::Params params{{"foo", "bar"}};
  12249. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12250. ASSERT_TRUE(result.is_valid());
  12251. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12252. }
  12253. TEST_F(StreamApiTest, GetConnectionError) {
  12254. httplib::Client cli(HOST, 9999);
  12255. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12256. }
  12257. TEST_F(StreamApiTest, Get404) {
  12258. httplib::Client cli(HOST, PORT);
  12259. auto result = httplib::stream::Get(cli, "/nonexistent");
  12260. EXPECT_TRUE(result.is_valid());
  12261. EXPECT_EQ(404, result.status());
  12262. }
  12263. // stream::Post tests
  12264. TEST_F(StreamApiTest, PostBasic) {
  12265. httplib::Client cli(HOST, PORT);
  12266. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12267. "application/json");
  12268. ASSERT_TRUE(result.is_valid());
  12269. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12270. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12271. }
  12272. TEST_F(StreamApiTest, PostWithHeaders) {
  12273. httplib::Client cli(HOST, PORT);
  12274. httplib::Headers headers{{"X-Custom", "value"}};
  12275. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12276. "text/plain");
  12277. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12278. }
  12279. TEST_F(StreamApiTest, PostWithParams) {
  12280. httplib::Client cli(HOST, PORT);
  12281. httplib::Params params{{"k", "v"}};
  12282. auto result =
  12283. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12284. auto body = read_body(result);
  12285. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12286. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12287. }
  12288. TEST_F(StreamApiTest, PostLarge) {
  12289. httplib::Client cli(HOST, PORT);
  12290. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12291. size_t total = 0;
  12292. while (result.next()) {
  12293. total += result.size();
  12294. }
  12295. EXPECT_EQ(100u * 1024u, total);
  12296. }
  12297. // stream::Put/Patch tests
  12298. TEST_F(StreamApiTest, PutAndPatch) {
  12299. httplib::Client cli(HOST, PORT);
  12300. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12301. EXPECT_EQ("PUT:test", read_body(put));
  12302. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12303. EXPECT_EQ("PATCH:test", read_body(patch));
  12304. }
  12305. // stream::Delete tests
  12306. TEST_F(StreamApiTest, Delete) {
  12307. httplib::Client cli(HOST, PORT);
  12308. auto del1 = httplib::stream::Delete(cli, "/resource");
  12309. EXPECT_EQ("Deleted", read_body(del1));
  12310. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12311. EXPECT_EQ("Deleted:data", read_body(del2));
  12312. }
  12313. // stream::Head/Options tests
  12314. TEST_F(StreamApiTest, HeadAndOptions) {
  12315. httplib::Client cli(HOST, PORT);
  12316. auto head = httplib::stream::Head(cli, "/head-test");
  12317. EXPECT_TRUE(head.is_valid());
  12318. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12319. auto opts = httplib::stream::Options(cli, "/options");
  12320. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12321. }
  12322. // SSL stream::* tests
  12323. #ifdef CPPHTTPLIB_SSL_ENABLED
  12324. class SSLStreamApiTest : public ::testing::Test {
  12325. protected:
  12326. void SetUp() override {
  12327. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12328. res.set_content("Hello SSL!", "text/plain");
  12329. });
  12330. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12331. res.set_content(req.body, "text/plain");
  12332. });
  12333. port_ = svr_.bind_to_any_port("127.0.0.1");
  12334. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12335. svr_.wait_until_ready();
  12336. }
  12337. void TearDown() override {
  12338. svr_.stop();
  12339. if (thread_.joinable()) thread_.join();
  12340. }
  12341. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12342. std::thread thread_;
  12343. int port_ = 0;
  12344. };
  12345. TEST_F(SSLStreamApiTest, GetAndPost) {
  12346. httplib::SSLClient cli("127.0.0.1", port_);
  12347. cli.enable_server_certificate_verification(false);
  12348. auto get = httplib::stream::Get(cli, "/hello");
  12349. EXPECT_EQ("Hello SSL!", read_body(get));
  12350. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12351. EXPECT_EQ("test", read_body(post));
  12352. }
  12353. #endif
  12354. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12355. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12356. // BodyReader
  12357. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12358. // Test that read timeout during streaming is detected
  12359. // Use a large content-length response where server delays mid-stream
  12360. Server svr;
  12361. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12362. // Send a large response with delay in the middle
  12363. res.set_content_provider(
  12364. 1000, // content_length
  12365. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12366. if (offset < 100) {
  12367. // Send first 100 bytes immediately
  12368. std::string data(100, 'A');
  12369. sink.write(data.c_str(), data.size());
  12370. return true;
  12371. }
  12372. // Then delay longer than client timeout
  12373. std::this_thread::sleep_for(std::chrono::seconds(3));
  12374. std::string data(900, 'B');
  12375. sink.write(data.c_str(), data.size());
  12376. return true;
  12377. });
  12378. });
  12379. auto port = 8091;
  12380. std::thread t([&]() { svr.listen("localhost", port); });
  12381. svr.wait_until_ready();
  12382. Client cli("localhost", port);
  12383. cli.set_read_timeout(1, 0); // 1 second timeout
  12384. auto handle = cli.open_stream("GET", "/slow-stream");
  12385. ASSERT_TRUE(handle.is_valid());
  12386. char buf[256];
  12387. ssize_t total = 0;
  12388. ssize_t n;
  12389. bool got_error = false;
  12390. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12391. total += n;
  12392. }
  12393. if (n < 0) {
  12394. got_error = true;
  12395. // Should be timeout or read error
  12396. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12397. handle.get_read_error() == Error::Read)
  12398. << "Actual error: " << to_string(handle.get_read_error());
  12399. }
  12400. // Either we got an error, or we got less data than expected
  12401. EXPECT_TRUE(got_error || total < 1000)
  12402. << "Expected timeout but got all " << total << " bytes";
  12403. svr.stop();
  12404. t.join();
  12405. }
  12406. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12407. // Test connection closed detection via BodyReader
  12408. Server svr;
  12409. std::atomic<bool> close_now{false};
  12410. svr.Get("/will-close", [&](const Request &, Response &res) {
  12411. res.set_content_provider(
  12412. 10000, // Large content_length that we won't fully send
  12413. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12414. if (offset < 100) {
  12415. std::string data(100, 'X');
  12416. sink.write(data.c_str(), data.size());
  12417. return true;
  12418. }
  12419. // Wait for signal then abort
  12420. while (!close_now) {
  12421. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12422. }
  12423. return false; // Abort - server will close connection
  12424. });
  12425. });
  12426. auto port = 8092;
  12427. std::thread t([&]() { svr.listen("localhost", port); });
  12428. svr.wait_until_ready();
  12429. Client cli("localhost", port);
  12430. auto handle = cli.open_stream("GET", "/will-close");
  12431. ASSERT_TRUE(handle.is_valid());
  12432. char buf[256];
  12433. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12434. EXPECT_GT(n, 0) << "First read should succeed";
  12435. // Signal server to close
  12436. close_now = true;
  12437. // Keep reading until error or EOF
  12438. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12439. // Keep reading
  12440. }
  12441. // Should get an error since content_length wasn't satisfied
  12442. if (n < 0) {
  12443. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12444. handle.get_read_error() == Error::Read)
  12445. << "Actual error: " << to_string(handle.get_read_error());
  12446. }
  12447. svr.stop();
  12448. t.join();
  12449. }
  12450. #ifdef CPPHTTPLIB_SSL_ENABLED
  12451. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12452. // Test that read timeout during SSL streaming is detected
  12453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12454. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12455. res.set_content_provider(
  12456. 1000, "text/plain",
  12457. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12458. if (offset < 100) {
  12459. std::string data(100, 'A');
  12460. sink.write(data.c_str(), data.size());
  12461. return true;
  12462. }
  12463. std::this_thread::sleep_for(std::chrono::seconds(3));
  12464. std::string data(900, 'B');
  12465. sink.write(data.c_str(), data.size());
  12466. return true;
  12467. });
  12468. });
  12469. auto port = 8093;
  12470. std::thread t([&]() { svr.listen("localhost", port); });
  12471. svr.wait_until_ready();
  12472. SSLClient cli("localhost", port);
  12473. cli.enable_server_certificate_verification(false);
  12474. cli.set_read_timeout(1, 0); // 1 second timeout
  12475. auto handle = cli.open_stream("GET", "/slow-stream");
  12476. ASSERT_TRUE(handle.is_valid());
  12477. char buf[256];
  12478. ssize_t total = 0;
  12479. ssize_t n;
  12480. bool got_error = false;
  12481. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12482. total += n;
  12483. }
  12484. if (n < 0) {
  12485. got_error = true;
  12486. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12487. handle.get_read_error() == Error::Read)
  12488. << "Actual error: " << to_string(handle.get_read_error());
  12489. }
  12490. EXPECT_TRUE(got_error || total < 1000)
  12491. << "Expected timeout but got all " << total << " bytes";
  12492. svr.stop();
  12493. t.join();
  12494. }
  12495. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12496. // Test SSL connection closed detection
  12497. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12498. std::atomic<bool> close_now{false};
  12499. svr.Get("/will-close", [&](const Request &, Response &res) {
  12500. res.set_content_provider(
  12501. 10000, "text/plain",
  12502. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12503. if (offset < 100) {
  12504. std::string data(100, 'X');
  12505. sink.write(data.c_str(), data.size());
  12506. return true;
  12507. }
  12508. while (!close_now) {
  12509. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12510. }
  12511. return false;
  12512. });
  12513. });
  12514. auto port = 8094;
  12515. std::thread t([&]() { svr.listen("localhost", port); });
  12516. svr.wait_until_ready();
  12517. SSLClient cli("localhost", port);
  12518. cli.enable_server_certificate_verification(false);
  12519. auto handle = cli.open_stream("GET", "/will-close");
  12520. ASSERT_TRUE(handle.is_valid());
  12521. char buf[256];
  12522. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12523. EXPECT_GT(n, 0);
  12524. // Signal server to close
  12525. close_now = true;
  12526. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12527. // Keep reading
  12528. }
  12529. if (n < 0) {
  12530. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12531. handle.get_read_error() == Error::Read)
  12532. << "Actual error: " << to_string(handle.get_read_error());
  12533. }
  12534. svr.stop();
  12535. t.join();
  12536. }
  12537. #endif
  12538. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12539. using namespace httplib;
  12540. // Create a test file
  12541. const char *fname = "etag_testfile.txt";
  12542. const char *content = "etag-content";
  12543. {
  12544. std::ofstream ofs(fname);
  12545. ofs << content;
  12546. ASSERT_TRUE(ofs.good());
  12547. }
  12548. Server svr;
  12549. svr.set_mount_point("/static", ".");
  12550. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12551. svr.wait_until_ready();
  12552. Client cli(HOST, PORT);
  12553. // First request: should get 200 with ETag header
  12554. auto res1 = cli.Get("/static/etag_testfile.txt");
  12555. ASSERT_TRUE(res1);
  12556. ASSERT_EQ(200, res1->status);
  12557. ASSERT_TRUE(res1->has_header("ETag"));
  12558. std::string etag = res1->get_header_value("ETag");
  12559. EXPECT_FALSE(etag.empty());
  12560. // Verify ETag format: W/"hex-hex"
  12561. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12562. EXPECT_EQ('W', etag[0]);
  12563. EXPECT_EQ('/', etag[1]);
  12564. EXPECT_EQ('"', etag[2]);
  12565. EXPECT_EQ('"', etag.back());
  12566. // Exact match: expect 304 Not Modified
  12567. Headers h2 = {{"If-None-Match", etag}};
  12568. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12569. ASSERT_TRUE(res2);
  12570. EXPECT_EQ(304, res2->status);
  12571. // Wildcard match: expect 304 Not Modified
  12572. Headers h3 = {{"If-None-Match", "*"}};
  12573. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12574. ASSERT_TRUE(res3);
  12575. EXPECT_EQ(304, res3->status);
  12576. // Non-matching ETag: expect 200
  12577. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12578. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12579. ASSERT_TRUE(res4);
  12580. EXPECT_EQ(200, res4->status);
  12581. // Multiple ETags with one matching: expect 304
  12582. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12583. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12584. ASSERT_TRUE(res5);
  12585. EXPECT_EQ(304, res5->status);
  12586. svr.stop();
  12587. t.join();
  12588. std::remove(fname);
  12589. }
  12590. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12591. using namespace httplib;
  12592. Server svr;
  12593. svr.set_mount_point("/static", ".");
  12594. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12595. svr.wait_until_ready();
  12596. Client cli(HOST, PORT);
  12597. // Send If-None-Match: * to a non-existent file
  12598. Headers h = {{"If-None-Match", "*"}};
  12599. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12600. ASSERT_TRUE(res);
  12601. EXPECT_EQ(404, res->status);
  12602. svr.stop();
  12603. t.join();
  12604. }
  12605. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12606. using namespace httplib;
  12607. // Create a test file
  12608. const char *fname = "etag_boundary_testfile.txt";
  12609. const char *content = "boundary-test";
  12610. {
  12611. std::ofstream ofs(fname);
  12612. ofs << content;
  12613. ASSERT_TRUE(ofs.good());
  12614. }
  12615. Server svr;
  12616. svr.set_mount_point("/static", ".");
  12617. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12618. svr.wait_until_ready();
  12619. Client cli(HOST, PORT);
  12620. // Get the actual ETag
  12621. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12622. ASSERT_TRUE(res1);
  12623. ASSERT_EQ(200, res1->status);
  12624. ASSERT_TRUE(res1->has_header("ETag"));
  12625. std::string etag = res1->get_header_value("ETag");
  12626. // Test 1: Very long ETag value (longer than actual ETag)
  12627. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12628. Headers h1 = {{"If-None-Match", "W/"
  12629. "\"very-long-etag-value-that-is-much-longer-"
  12630. "than-the-actual-etag-value\""}};
  12631. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12632. ASSERT_TRUE(res2);
  12633. EXPECT_EQ(200, res2->status); // Should not match
  12634. // Test 2: Long string followed by wildcard
  12635. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12636. // string)
  12637. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12638. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12639. ASSERT_TRUE(res3);
  12640. EXPECT_EQ(304, res3->status); // Should match on "*"
  12641. // Test 3: Wildcard followed by long string
  12642. // Should match on "*" immediately and return 304
  12643. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12644. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12645. ASSERT_TRUE(res4);
  12646. EXPECT_EQ(304, res4->status); // Should match on "*"
  12647. // Test 4: Multiple long non-matching values
  12648. // Should NOT match and return 200 (test that all comparisons are safe)
  12649. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12650. "W/\"second-long-non-matching-value\", "
  12651. "W/\"third-long-non-matching-value\""}};
  12652. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12653. ASSERT_TRUE(res5);
  12654. EXPECT_EQ(200, res5->status); // Should not match
  12655. // Test 5: Single character that is not "*" (edge case)
  12656. Headers h5 = {{"If-None-Match", "X"}};
  12657. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12658. ASSERT_TRUE(res6);
  12659. EXPECT_EQ(200, res6->status); // Should not match
  12660. svr.stop();
  12661. t.join();
  12662. std::remove(fname);
  12663. }
  12664. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12665. using namespace httplib;
  12666. // Create a test file
  12667. const char *fname = "ims_testfile.txt";
  12668. const char *content = "if-modified-since-test";
  12669. {
  12670. std::ofstream ofs(fname);
  12671. ofs << content;
  12672. ASSERT_TRUE(ofs.good());
  12673. }
  12674. Server svr;
  12675. svr.set_mount_point("/static", ".");
  12676. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12677. svr.wait_until_ready();
  12678. Client cli(HOST, PORT);
  12679. // First request: should get 200 with Last-Modified header
  12680. auto res1 = cli.Get("/static/ims_testfile.txt");
  12681. ASSERT_TRUE(res1);
  12682. ASSERT_EQ(200, res1->status);
  12683. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12684. std::string last_modified = res1->get_header_value("Last-Modified");
  12685. EXPECT_FALSE(last_modified.empty());
  12686. // If-Modified-Since with same time: expect 304
  12687. Headers h2 = {{"If-Modified-Since", last_modified}};
  12688. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12689. ASSERT_TRUE(res2);
  12690. EXPECT_EQ(304, res2->status);
  12691. // If-Modified-Since with future time: expect 304
  12692. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12693. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12694. ASSERT_TRUE(res3);
  12695. EXPECT_EQ(304, res3->status);
  12696. // If-Modified-Since with past time: expect 200
  12697. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12698. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12699. ASSERT_TRUE(res4);
  12700. EXPECT_EQ(200, res4->status);
  12701. // If-None-Match takes precedence over If-Modified-Since
  12702. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12703. ASSERT_TRUE(res1->has_header("ETag"));
  12704. std::string etag = res1->get_header_value("ETag");
  12705. Headers h5 = {{"If-None-Match", etag},
  12706. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12707. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12708. ASSERT_TRUE(res5);
  12709. EXPECT_EQ(304, res5->status);
  12710. svr.stop();
  12711. t.join();
  12712. std::remove(fname);
  12713. }
  12714. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12715. using namespace httplib;
  12716. Server svr;
  12717. // Endpoint that returns compressible content
  12718. svr.Get("/compressible", [](const Request &, Response &res) {
  12719. // Return a large enough body to trigger compression
  12720. std::string body(1000, 'a');
  12721. res.set_content(body, "text/plain");
  12722. });
  12723. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12724. svr.wait_until_ready();
  12725. Client cli(HOST, PORT);
  12726. // Request with gzip support: should get Vary header when compressed
  12727. cli.set_compress(true);
  12728. auto res1 = cli.Get("/compressible");
  12729. ASSERT_TRUE(res1);
  12730. EXPECT_EQ(200, res1->status);
  12731. // If Content-Encoding is set, Vary should also be set
  12732. if (res1->has_header("Content-Encoding")) {
  12733. EXPECT_TRUE(res1->has_header("Vary"));
  12734. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12735. }
  12736. // Request without Accept-Encoding header: should not have compression
  12737. Headers h_no_compress;
  12738. auto res2 = cli.Get("/compressible", h_no_compress);
  12739. ASSERT_TRUE(res2);
  12740. EXPECT_EQ(200, res2->status);
  12741. // Verify Vary header is present when compression is applied
  12742. // (the exact behavior depends on server configuration)
  12743. svr.stop();
  12744. t.join();
  12745. }
  12746. TEST(ETagTest, IfRangeWithETag) {
  12747. using namespace httplib;
  12748. // Create a test file with known content
  12749. const char *fname = "if_range_testfile.txt";
  12750. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12751. {
  12752. std::ofstream ofs(fname);
  12753. ofs << content;
  12754. ASSERT_TRUE(ofs.good());
  12755. }
  12756. Server svr;
  12757. svr.set_mount_point("/static", ".");
  12758. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12759. svr.wait_until_ready();
  12760. Client cli(HOST, PORT);
  12761. // First request: get ETag
  12762. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12763. ASSERT_TRUE(res1);
  12764. ASSERT_EQ(200, res1->status);
  12765. ASSERT_TRUE(res1->has_header("ETag"));
  12766. std::string etag = res1->get_header_value("ETag");
  12767. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12768. // Since our server generates weak ETags (W/"..."), If-Range with our
  12769. // ETag should NOT result in partial content - it should return full content.
  12770. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12771. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12772. ASSERT_TRUE(res2);
  12773. // Weak ETag in If-Range -> full content (200), not partial (206)
  12774. EXPECT_EQ(200, res2->status);
  12775. EXPECT_EQ(content, res2->body);
  12776. EXPECT_FALSE(res2->has_header("Content-Range"));
  12777. // Range request with non-matching If-Range (ETag): should get 200 (full
  12778. // content)
  12779. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12780. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12781. ASSERT_TRUE(res3);
  12782. EXPECT_EQ(200, res3->status);
  12783. EXPECT_EQ(content, res3->body);
  12784. EXPECT_FALSE(res3->has_header("Content-Range"));
  12785. // Range request with strong ETag (hypothetical - our server doesn't generate
  12786. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12787. // should return full content)
  12788. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12789. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12790. ASSERT_TRUE(res4);
  12791. EXPECT_EQ(200, res4->status);
  12792. EXPECT_EQ(content, res4->body);
  12793. EXPECT_FALSE(res4->has_header("Content-Range"));
  12794. svr.stop();
  12795. t.join();
  12796. std::remove(fname);
  12797. }
  12798. TEST(ETagTest, IfRangeWithDate) {
  12799. using namespace httplib;
  12800. // Create a test file
  12801. const char *fname = "if_range_date_testfile.txt";
  12802. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12803. {
  12804. std::ofstream ofs(fname);
  12805. ofs << content;
  12806. ASSERT_TRUE(ofs.good());
  12807. }
  12808. Server svr;
  12809. svr.set_mount_point("/static", ".");
  12810. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12811. svr.wait_until_ready();
  12812. Client cli(HOST, PORT);
  12813. // First request: get Last-Modified
  12814. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12815. ASSERT_TRUE(res1);
  12816. ASSERT_EQ(200, res1->status);
  12817. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12818. std::string last_modified = res1->get_header_value("Last-Modified");
  12819. // Range request with matching If-Range (date): should get 206
  12820. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12821. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12822. ASSERT_TRUE(res2);
  12823. EXPECT_EQ(206, res2->status);
  12824. EXPECT_EQ("FGHIJ", res2->body);
  12825. // Range request with old If-Range date: should get 200 (full content)
  12826. Headers h3 = {{"Range", "bytes=5-9"},
  12827. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12828. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12829. ASSERT_TRUE(res3);
  12830. EXPECT_EQ(200, res3->status);
  12831. EXPECT_EQ(content, res3->body);
  12832. // Range request with future If-Range date: should get 206
  12833. Headers h4 = {{"Range", "bytes=0-4"},
  12834. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12835. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12836. ASSERT_TRUE(res4);
  12837. EXPECT_EQ(206, res4->status);
  12838. EXPECT_EQ("ABCDE", res4->body);
  12839. svr.stop();
  12840. t.join();
  12841. std::remove(fname);
  12842. }
  12843. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12844. using namespace httplib;
  12845. const char *fname = "etag_malformed.txt";
  12846. const char *content = "malformed-etag";
  12847. {
  12848. std::ofstream ofs(fname);
  12849. ofs << content;
  12850. ASSERT_TRUE(ofs.good());
  12851. }
  12852. Server svr;
  12853. svr.set_mount_point("/static", ".");
  12854. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12855. svr.wait_until_ready();
  12856. Client cli(HOST, PORT);
  12857. // baseline: should get 200 and an ETag
  12858. auto res1 = cli.Get("/static/etag_malformed.txt");
  12859. ASSERT_TRUE(res1);
  12860. ASSERT_EQ(200, res1->status);
  12861. ASSERT_TRUE(res1->has_header("ETag"));
  12862. // Malformed ETag value (missing quotes) should be treated as non-matching
  12863. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12864. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12865. ASSERT_TRUE(res_bad);
  12866. EXPECT_EQ(200, res_bad->status);
  12867. // Whitespace-only header value should be considered invalid / non-matching
  12868. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12869. "Host: localhost\r\n"
  12870. "If-None-Match: \r\n"
  12871. "Connection: close\r\n"
  12872. "\r\n";
  12873. std::string out;
  12874. ASSERT_TRUE(send_request(5, raw_req, &out));
  12875. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12876. svr.stop();
  12877. t.join();
  12878. std::remove(fname);
  12879. }
  12880. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12881. using namespace httplib;
  12882. const char *fname = "ims_invalid_format.txt";
  12883. const char *content = "ims-bad-format";
  12884. {
  12885. std::ofstream ofs(fname);
  12886. ofs << content;
  12887. ASSERT_TRUE(ofs.good());
  12888. }
  12889. Server svr;
  12890. svr.set_mount_point("/static", ".");
  12891. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12892. svr.wait_until_ready();
  12893. Client cli(HOST, PORT);
  12894. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12895. ASSERT_TRUE(res1);
  12896. ASSERT_EQ(200, res1->status);
  12897. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12898. // If-Modified-Since with invalid format should not result in 304
  12899. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12900. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12901. ASSERT_TRUE(res_bad);
  12902. EXPECT_EQ(200, res_bad->status);
  12903. // If-Range with invalid date format should be treated as mismatch -> full
  12904. // content (200)
  12905. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12906. {"If-Range", "invalid-date"}};
  12907. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12908. ASSERT_TRUE(res_ifrange);
  12909. EXPECT_EQ(200, res_ifrange->status);
  12910. svr.stop();
  12911. t.join();
  12912. std::remove(fname);
  12913. }
  12914. TEST(ETagTest, IfRangeWithMalformedETag) {
  12915. using namespace httplib;
  12916. const char *fname = "ifrange_malformed.txt";
  12917. const std::string content = "0123456789";
  12918. {
  12919. std::ofstream ofs(fname);
  12920. ofs << content;
  12921. ASSERT_TRUE(ofs.good());
  12922. }
  12923. Server svr;
  12924. svr.set_mount_point("/static", ".");
  12925. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12926. svr.wait_until_ready();
  12927. Client cli(HOST, PORT);
  12928. // First request: get ETag
  12929. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12930. ASSERT_TRUE(res1);
  12931. ASSERT_EQ(200, res1->status);
  12932. ASSERT_TRUE(res1->has_header("ETag"));
  12933. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12934. // full content (200)
  12935. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12936. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12937. ASSERT_TRUE(res2);
  12938. EXPECT_EQ(200, res2->status);
  12939. EXPECT_EQ(content, res2->body);
  12940. svr.stop();
  12941. t.join();
  12942. std::remove(fname);
  12943. }
  12944. TEST(ETagTest, ExtremeLargeDateValues) {
  12945. using namespace httplib;
  12946. const char *fname = "ims_extreme_date.txt";
  12947. const char *content = "ims-extreme-date";
  12948. {
  12949. std::ofstream ofs(fname);
  12950. ofs << content;
  12951. ASSERT_TRUE(ofs.good());
  12952. }
  12953. Server svr;
  12954. svr.set_mount_point("/static", ".");
  12955. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12956. svr.wait_until_ready();
  12957. Client cli(HOST, PORT);
  12958. auto res1 = cli.Get(std::string("/static/") + fname);
  12959. ASSERT_TRUE(res1);
  12960. ASSERT_EQ(200, res1->status);
  12961. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12962. // Extremely large year that may overflow date parsing routines.
  12963. Headers h_large_date = {
  12964. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12965. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12966. ASSERT_TRUE(res_bad);
  12967. // Expect server to treat this as invalid/mismatch and return full content
  12968. EXPECT_EQ(200, res_bad->status);
  12969. // If-Range with extremely large date should be treated as mismatch -> full
  12970. // content (200)
  12971. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12972. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12973. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12974. ASSERT_TRUE(res_ifrange);
  12975. EXPECT_EQ(200, res_ifrange->status);
  12976. svr.stop();
  12977. t.join();
  12978. std::remove(fname);
  12979. }
  12980. TEST(ETagTest, NegativeFileModificationTime) {
  12981. using namespace httplib;
  12982. const char *fname = "ims_negative_mtime.txt";
  12983. const std::string content = "negative-mtime";
  12984. {
  12985. std::ofstream ofs(fname);
  12986. ofs << content;
  12987. ASSERT_TRUE(ofs.good());
  12988. }
  12989. // Try to set file mtime to a negative value. This may fail on some
  12990. // platforms/filesystems; if it fails, the test will still verify server
  12991. // behaves safely by performing a regular conditional request.
  12992. #if defined(__APPLE__) || defined(__linux__)
  12993. bool set_negative = false;
  12994. do {
  12995. struct timeval times[2];
  12996. // access time: now
  12997. times[0].tv_sec = time(nullptr);
  12998. times[0].tv_usec = 0;
  12999. // modification time: negative (e.g., -1)
  13000. times[1].tv_sec = -1;
  13001. times[1].tv_usec = 0;
  13002. if (utimes(fname, times) == 0) { set_negative = true; }
  13003. } while (0);
  13004. #else
  13005. bool set_negative = false;
  13006. #endif
  13007. Server svr;
  13008. svr.set_mount_point("/static", ".");
  13009. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13010. svr.wait_until_ready();
  13011. Client cli(HOST, PORT);
  13012. auto res1 = cli.Get(std::string("/static/") + fname);
  13013. ASSERT_TRUE(res1);
  13014. ASSERT_EQ(200, res1->status);
  13015. bool has_last_modified = res1->has_header("Last-Modified");
  13016. std::string last_modified;
  13017. if (has_last_modified) {
  13018. last_modified = res1->get_header_value("Last-Modified");
  13019. }
  13020. if (set_negative) {
  13021. // If we successfully set a negative mtime, ensure server returns a
  13022. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13023. // with an old date and ensure server handles it without crash.
  13024. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13025. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13026. ASSERT_TRUE(res2);
  13027. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13028. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13029. } else {
  13030. // Could not set negative mtime on this platform; fall back to verifying
  13031. // that normal invalid/malformed dates are treated safely (non-304).
  13032. Headers h_bad_date = {
  13033. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13034. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13035. ASSERT_TRUE(res_bad);
  13036. EXPECT_EQ(200, res_bad->status);
  13037. }
  13038. svr.stop();
  13039. t.join();
  13040. std::remove(fname);
  13041. }
  13042. //==============================================================================
  13043. // SSE Parsing Tests
  13044. //==============================================================================
  13045. class SSEParsingTest : public ::testing::Test {
  13046. protected:
  13047. // Test helper that mimics SSE parsing behavior
  13048. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13049. int &retry_ms) {
  13050. // Blank line signals end of event
  13051. if (line.empty() || line == "\r") { return true; }
  13052. // Lines starting with ':' are comments (ignored)
  13053. if (!line.empty() && line[0] == ':') { return false; }
  13054. // Find the colon separator
  13055. auto colon_pos = line.find(':');
  13056. if (colon_pos == std::string::npos) {
  13057. // Line with no colon is treated as field name with empty value
  13058. return false;
  13059. }
  13060. std::string field = line.substr(0, colon_pos);
  13061. std::string value;
  13062. // Value starts after colon, skip optional single space
  13063. if (colon_pos + 1 < line.size()) {
  13064. size_t value_start = colon_pos + 1;
  13065. if (line[value_start] == ' ') { value_start++; }
  13066. value = line.substr(value_start);
  13067. // Remove trailing \r if present
  13068. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13069. }
  13070. // Handle known fields
  13071. if (field == "event") {
  13072. msg.event = value;
  13073. } else if (field == "data") {
  13074. // Multiple data lines are concatenated with newlines
  13075. if (!msg.data.empty()) { msg.data += "\n"; }
  13076. msg.data += value;
  13077. } else if (field == "id") {
  13078. // Empty id is valid (clears the last event ID)
  13079. msg.id = value;
  13080. } else if (field == "retry") {
  13081. // Parse retry interval in milliseconds
  13082. {
  13083. int v = 0;
  13084. auto res =
  13085. detail::from_chars(value.data(), value.data() + value.size(), v);
  13086. if (res.ec == std::errc{}) { retry_ms = v; }
  13087. }
  13088. }
  13089. // Unknown fields are ignored per SSE spec
  13090. return false;
  13091. }
  13092. };
  13093. // Test: Single-line data
  13094. TEST_F(SSEParsingTest, SingleLineData) {
  13095. sse::SSEMessage msg;
  13096. int retry_ms = 3000;
  13097. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13098. EXPECT_EQ(msg.data, "hello");
  13099. EXPECT_EQ(msg.event, "message");
  13100. // Blank line ends event
  13101. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13102. }
  13103. // Test: Multi-line data
  13104. TEST_F(SSEParsingTest, MultiLineData) {
  13105. sse::SSEMessage msg;
  13106. int retry_ms = 3000;
  13107. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13108. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13109. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13110. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13111. }
  13112. // Test: Custom event types
  13113. TEST_F(SSEParsingTest, CustomEventType) {
  13114. sse::SSEMessage msg;
  13115. int retry_ms = 3000;
  13116. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13117. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13118. EXPECT_EQ(msg.event, "update");
  13119. EXPECT_EQ(msg.data, "payload");
  13120. }
  13121. // Test: Event ID handling
  13122. TEST_F(SSEParsingTest, EventIdHandling) {
  13123. sse::SSEMessage msg;
  13124. int retry_ms = 3000;
  13125. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13126. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13127. EXPECT_EQ(msg.id, "12345");
  13128. }
  13129. // Test: Empty event ID (clears last event ID)
  13130. TEST_F(SSEParsingTest, EmptyEventId) {
  13131. sse::SSEMessage msg;
  13132. msg.id = "previous";
  13133. int retry_ms = 3000;
  13134. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13135. EXPECT_EQ(msg.id, "");
  13136. }
  13137. // Test: Retry field parsing
  13138. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13139. sse::SSEMessage msg;
  13140. int retry_ms = 3000;
  13141. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13142. EXPECT_EQ(retry_ms, 5000);
  13143. }
  13144. // Test: Invalid retry value
  13145. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13146. sse::SSEMessage msg;
  13147. int retry_ms = 3000;
  13148. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13149. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13150. }
  13151. // Test: Comments (lines starting with :)
  13152. TEST_F(SSEParsingTest, CommentsIgnored) {
  13153. sse::SSEMessage msg;
  13154. int retry_ms = 3000;
  13155. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13156. EXPECT_EQ(msg.data, "");
  13157. EXPECT_EQ(msg.event, "message");
  13158. }
  13159. // Test: Colon in value
  13160. TEST_F(SSEParsingTest, ColonInValue) {
  13161. sse::SSEMessage msg;
  13162. int retry_ms = 3000;
  13163. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13164. EXPECT_EQ(msg.data, "hello:world:test");
  13165. }
  13166. // Test: Line with no colon (field name only)
  13167. TEST_F(SSEParsingTest, FieldNameOnly) {
  13168. sse::SSEMessage msg;
  13169. int retry_ms = 3000;
  13170. // According to SSE spec, this is treated as field name with empty value
  13171. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13172. // Since we don't recognize "data" without colon, data should be empty
  13173. EXPECT_EQ(msg.data, "");
  13174. }
  13175. // Test: Trailing \r handling
  13176. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13177. sse::SSEMessage msg;
  13178. int retry_ms = 3000;
  13179. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13180. EXPECT_EQ(msg.data, "hello");
  13181. }
  13182. // Test: Unknown fields ignored
  13183. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13184. sse::SSEMessage msg;
  13185. int retry_ms = 3000;
  13186. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13187. EXPECT_EQ(msg.data, "");
  13188. EXPECT_EQ(msg.event, "message");
  13189. }
  13190. // Test: Space after colon is optional
  13191. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13192. sse::SSEMessage msg1, msg2;
  13193. int retry_ms = 3000;
  13194. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13195. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13196. EXPECT_EQ(msg1.data, "hello");
  13197. EXPECT_EQ(msg2.data, "hello");
  13198. }
  13199. // Test: SSEMessage clear
  13200. TEST_F(SSEParsingTest, MessageClear) {
  13201. sse::SSEMessage msg;
  13202. msg.event = "custom";
  13203. msg.data = "some data";
  13204. msg.id = "123";
  13205. msg.clear();
  13206. EXPECT_EQ(msg.event, "message");
  13207. EXPECT_EQ(msg.data, "");
  13208. EXPECT_EQ(msg.id, "");
  13209. }
  13210. // Test: Complete event parsing
  13211. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13212. sse::SSEMessage msg;
  13213. int retry_ms = 3000;
  13214. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13215. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13216. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13217. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13218. // Blank line ends event
  13219. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13220. EXPECT_EQ(msg.event, "notification");
  13221. EXPECT_EQ(msg.id, "evt-42");
  13222. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13223. EXPECT_EQ(retry_ms, 1000);
  13224. }
  13225. //==============================================================================
  13226. // Integration Tests with Server
  13227. //==============================================================================
  13228. class SSEIntegrationTest : public ::testing::Test {
  13229. protected:
  13230. void SetUp() override {
  13231. stop_server_.store(false);
  13232. events_.clear();
  13233. server_ = httplib::detail::make_unique<Server>();
  13234. setup_server();
  13235. start_server();
  13236. }
  13237. void TearDown() override {
  13238. stop_server_.store(true);
  13239. event_cv_.notify_all();
  13240. server_->stop();
  13241. if (server_thread_.joinable()) { server_thread_.join(); }
  13242. }
  13243. void setup_server() {
  13244. // Simple SSE endpoint
  13245. server_->Get("/events", [this](const Request &req, Response &res) {
  13246. auto last_id = req.get_header_value("Last-Event-ID");
  13247. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13248. res.set_chunked_content_provider(
  13249. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13250. std::unique_lock<std::mutex> lock(event_mutex_);
  13251. if (event_cv_.wait_for(
  13252. lock, std::chrono::milliseconds(200), [this] {
  13253. return !events_.empty() || stop_server_.load();
  13254. })) {
  13255. if (stop_server_.load()) { return false; }
  13256. if (!events_.empty()) {
  13257. std::string event = events_.front();
  13258. events_.erase(events_.begin());
  13259. sink.write(event.data(), event.size());
  13260. return true;
  13261. }
  13262. }
  13263. return !stop_server_.load();
  13264. });
  13265. });
  13266. // Endpoint that returns error
  13267. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13268. res.status = 500;
  13269. res.set_content("Internal Server Error", "text/plain");
  13270. });
  13271. // Endpoint for custom event types
  13272. server_->Get("/custom-events", [](const Request &, Response &res) {
  13273. res.set_chunked_content_provider(
  13274. "text/event-stream", [](size_t offset, DataSink &sink) {
  13275. if (offset == 0) {
  13276. std::string event = "event: update\ndata: updated\n\n"
  13277. "event: delete\ndata: deleted\n\n";
  13278. sink.write(event.data(), event.size());
  13279. }
  13280. return false; // End stream after sending
  13281. });
  13282. });
  13283. }
  13284. void start_server() {
  13285. port_ = server_->bind_to_any_port(HOST);
  13286. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13287. // Wait for server to start
  13288. while (!server_->is_running()) {
  13289. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13290. }
  13291. }
  13292. int get_port() const { return port_; }
  13293. void send_event(const std::string &event) {
  13294. std::lock_guard<std::mutex> lock(event_mutex_);
  13295. events_.push_back(event);
  13296. event_cv_.notify_all();
  13297. }
  13298. std::unique_ptr<Server> server_;
  13299. std::thread server_thread_;
  13300. std::mutex event_mutex_;
  13301. std::condition_variable event_cv_;
  13302. std::vector<std::string> events_;
  13303. std::atomic<bool> stop_server_{false};
  13304. std::string last_received_event_id_;
  13305. int port_ = 0;
  13306. };
  13307. // Test: Successful connection and on_open callback
  13308. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13309. // Add a simple endpoint that sends one event and closes
  13310. server_->Get("/simple-event", [](const Request &, Response &res) {
  13311. res.set_chunked_content_provider(
  13312. "text/event-stream", [](size_t offset, DataSink &sink) {
  13313. if (offset == 0) {
  13314. std::string event = "data: hello\n\n";
  13315. sink.write(event.data(), event.size());
  13316. }
  13317. return false; // Close stream after sending
  13318. });
  13319. });
  13320. Client client("localhost", get_port());
  13321. sse::SSEClient sse(client, "/simple-event");
  13322. std::atomic<bool> open_called{false};
  13323. std::atomic<bool> message_received{false};
  13324. sse.on_open([&open_called]() { open_called.store(true); });
  13325. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13326. if (msg.data == "hello") { message_received.store(true); }
  13327. });
  13328. sse.set_reconnect_interval(100);
  13329. sse.set_max_reconnect_attempts(1);
  13330. // Start async
  13331. sse.start_async();
  13332. // Wait for message to be processed
  13333. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13334. sse.stop();
  13335. EXPECT_TRUE(open_called.load());
  13336. EXPECT_TRUE(message_received.load());
  13337. }
  13338. // Test: on_message callback
  13339. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13340. // Endpoint that sends multiple events then closes
  13341. server_->Get("/multi-event", [](const Request &, Response &res) {
  13342. res.set_chunked_content_provider(
  13343. "text/event-stream", [](size_t offset, DataSink &sink) {
  13344. if (offset == 0) {
  13345. std::string events = "data: message1\n\ndata: message2\n\n";
  13346. sink.write(events.data(), events.size());
  13347. }
  13348. return false;
  13349. });
  13350. });
  13351. Client client("localhost", get_port());
  13352. sse::SSEClient sse(client, "/multi-event");
  13353. std::vector<std::string> received_messages;
  13354. std::mutex messages_mutex;
  13355. sse.on_message([&](const sse::SSEMessage &msg) {
  13356. std::lock_guard<std::mutex> lock(messages_mutex);
  13357. received_messages.push_back(msg.data);
  13358. });
  13359. sse.set_reconnect_interval(100);
  13360. sse.set_max_reconnect_attempts(1);
  13361. sse.start_async();
  13362. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13363. sse.stop();
  13364. std::lock_guard<std::mutex> lock(messages_mutex);
  13365. EXPECT_GE(received_messages.size(), 2u);
  13366. if (received_messages.size() >= 2) {
  13367. EXPECT_EQ(received_messages[0], "message1");
  13368. EXPECT_EQ(received_messages[1], "message2");
  13369. }
  13370. }
  13371. // Test: on_event for specific types
  13372. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13373. Client client("localhost", get_port());
  13374. sse::SSEClient sse(client, "/custom-events");
  13375. std::atomic<bool> update_received{false};
  13376. std::atomic<bool> delete_received{false};
  13377. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13378. if (msg.data == "updated") { update_received.store(true); }
  13379. });
  13380. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13381. if (msg.data == "deleted") { delete_received.store(true); }
  13382. });
  13383. sse.set_max_reconnect_attempts(1);
  13384. sse.start_async();
  13385. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13386. sse.stop();
  13387. EXPECT_TRUE(update_received.load());
  13388. EXPECT_TRUE(delete_received.load());
  13389. }
  13390. // Test: on_error callback on connection failure
  13391. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13392. // Connect to a non-existent port
  13393. Client client("localhost", 59999);
  13394. sse::SSEClient sse(client, "/events");
  13395. std::atomic<bool> error_called{false};
  13396. Error received_error = Error::Success;
  13397. sse.on_error([&](Error err) {
  13398. error_called.store(true);
  13399. received_error = err;
  13400. });
  13401. sse.set_reconnect_interval(50);
  13402. sse.set_max_reconnect_attempts(1);
  13403. sse.start_async();
  13404. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13405. sse.stop();
  13406. EXPECT_TRUE(error_called.load());
  13407. EXPECT_NE(received_error, Error::Success);
  13408. }
  13409. // Test: Last-Event-ID header sent on reconnect
  13410. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13411. // Endpoint that sends event with ID
  13412. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13413. res.set_chunked_content_provider(
  13414. "text/event-stream", [](size_t offset, DataSink &sink) {
  13415. if (offset == 0) {
  13416. std::string event = "id: evt-123\ndata: test\n\n";
  13417. sink.write(event.data(), event.size());
  13418. }
  13419. return false;
  13420. });
  13421. });
  13422. Client client("localhost", get_port());
  13423. sse::SSEClient sse(client, "/event-with-id");
  13424. std::atomic<bool> id_received{false};
  13425. sse.on_message([&](const sse::SSEMessage &msg) {
  13426. if (!msg.id.empty()) { id_received.store(true); }
  13427. });
  13428. sse.set_reconnect_interval(100);
  13429. sse.set_max_reconnect_attempts(1);
  13430. sse.start_async();
  13431. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13432. sse.stop();
  13433. EXPECT_TRUE(id_received.load());
  13434. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13435. }
  13436. // Test: Manual stop
  13437. TEST_F(SSEIntegrationTest, ManualStop) {
  13438. // Endpoint that sends one event and stays open briefly
  13439. std::atomic<bool> handler_running{true};
  13440. server_->Get("/stay-open", [&handler_running](const Request &,
  13441. Response &res) {
  13442. res.set_chunked_content_provider(
  13443. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13444. if (offset == 0) {
  13445. std::string event = "data: connected\n\n";
  13446. sink.write(event.data(), event.size());
  13447. }
  13448. // Keep connection open while handler_running is true
  13449. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13450. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13451. }
  13452. return false;
  13453. });
  13454. });
  13455. Client client("localhost", get_port());
  13456. sse::SSEClient sse(client, "/stay-open");
  13457. std::atomic<bool> connected{false};
  13458. sse.on_open([&connected]() { connected.store(true); });
  13459. sse.set_reconnect_interval(100);
  13460. sse.set_max_reconnect_attempts(1);
  13461. sse.start_async();
  13462. // Wait for connection to establish
  13463. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13464. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13465. }
  13466. EXPECT_TRUE(connected.load());
  13467. EXPECT_TRUE(sse.is_connected());
  13468. // Signal handler to stop
  13469. handler_running.store(false);
  13470. // Stop SSE client
  13471. sse.stop();
  13472. EXPECT_FALSE(sse.is_connected());
  13473. }
  13474. // Test: SSEClient with custom headers
  13475. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13476. // Setup a server endpoint that checks for custom header
  13477. std::atomic<bool> header_received{false};
  13478. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13479. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13480. header_received.store(true);
  13481. }
  13482. res.set_chunked_content_provider("text/event-stream",
  13483. [](size_t, DataSink &) { return false; });
  13484. });
  13485. Client client("localhost", get_port());
  13486. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13487. sse::SSEClient sse(client, "/header-check", headers);
  13488. sse.set_max_reconnect_attempts(1);
  13489. sse.start_async();
  13490. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13491. sse.stop();
  13492. EXPECT_TRUE(header_received.load());
  13493. }
  13494. // Test: Reconnect interval configuration
  13495. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13496. Client client("localhost", get_port());
  13497. sse::SSEClient sse(client, "/events");
  13498. auto &result = sse.set_reconnect_interval(500);
  13499. // Builder pattern should return reference to self
  13500. EXPECT_EQ(&result, &sse);
  13501. }
  13502. // Test: Max reconnect attempts
  13503. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13504. // Connect to non-existent port to force reconnects
  13505. Client client("localhost", 59998);
  13506. sse::SSEClient sse(client, "/events");
  13507. std::atomic<int> error_count{0};
  13508. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13509. sse.set_reconnect_interval(50);
  13510. sse.set_max_reconnect_attempts(2);
  13511. auto start = std::chrono::steady_clock::now();
  13512. sse.start(); // Blocking call
  13513. auto end = std::chrono::steady_clock::now();
  13514. // Should have stopped after 2 failed attempts
  13515. EXPECT_GE(error_count.load(), 2);
  13516. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13517. auto duration =
  13518. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13519. #ifdef _WIN32
  13520. // Windows is much slower for socket connection failures
  13521. EXPECT_LT(duration.count(), 7000);
  13522. #else
  13523. EXPECT_LT(duration.count(), 1000);
  13524. #endif
  13525. }
  13526. // Test: Multi-line data in integration
  13527. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13528. // Endpoint with multi-line data
  13529. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13530. res.set_chunked_content_provider(
  13531. "text/event-stream", [](size_t offset, DataSink &sink) {
  13532. if (offset == 0) {
  13533. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13534. sink.write(event.data(), event.size());
  13535. }
  13536. return false;
  13537. });
  13538. });
  13539. Client client("localhost", get_port());
  13540. sse::SSEClient sse(client, "/multiline-data");
  13541. std::string received_data;
  13542. std::mutex data_mutex;
  13543. sse.on_message([&](const sse::SSEMessage &msg) {
  13544. std::lock_guard<std::mutex> lock(data_mutex);
  13545. received_data = msg.data;
  13546. });
  13547. sse.set_reconnect_interval(100);
  13548. sse.set_max_reconnect_attempts(1);
  13549. sse.start_async();
  13550. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13551. sse.stop();
  13552. std::lock_guard<std::mutex> lock(data_mutex);
  13553. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13554. }
  13555. // Test: Auto-reconnect after server disconnection
  13556. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13557. std::atomic<int> connection_count{0};
  13558. std::atomic<int> message_count{0};
  13559. // Endpoint that sends one event and closes, forcing reconnect
  13560. server_->Get("/reconnect-test",
  13561. [&connection_count](const Request &, Response &res) {
  13562. connection_count.fetch_add(1);
  13563. res.set_chunked_content_provider(
  13564. "text/event-stream", [](size_t offset, DataSink &sink) {
  13565. if (offset == 0) {
  13566. std::string event = "data: hello\n\n";
  13567. sink.write(event.data(), event.size());
  13568. }
  13569. return false; // Close connection after sending
  13570. });
  13571. });
  13572. Client client("localhost", get_port());
  13573. sse::SSEClient sse(client, "/reconnect-test");
  13574. sse.on_message([&message_count](const sse::SSEMessage &) {
  13575. message_count.fetch_add(1);
  13576. });
  13577. sse.set_reconnect_interval(100);
  13578. sse.set_max_reconnect_attempts(3);
  13579. sse.start_async();
  13580. // Wait long enough for multiple reconnects
  13581. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13582. sse.stop();
  13583. // Should have connected multiple times (initial + reconnects)
  13584. EXPECT_GE(connection_count.load(), 2);
  13585. // Should have received messages from multiple connections
  13586. EXPECT_GE(message_count.load(), 2);
  13587. }
  13588. // Test: Last-Event-ID sent on reconnect
  13589. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13590. std::atomic<int> connection_count{0};
  13591. std::vector<std::string> received_last_event_ids;
  13592. std::mutex id_mutex;
  13593. // Endpoint that checks Last-Event-ID header and sends event with ID
  13594. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13595. int conn = connection_count.fetch_add(1);
  13596. // Capture the Last-Event-ID header from each connection
  13597. {
  13598. std::lock_guard<std::mutex> lock(id_mutex);
  13599. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13600. }
  13601. res.set_chunked_content_provider(
  13602. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13603. if (offset == 0) {
  13604. std::string event =
  13605. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13606. sink.write(event.data(), event.size());
  13607. }
  13608. return false;
  13609. });
  13610. });
  13611. Client client("localhost", get_port());
  13612. sse::SSEClient sse(client, "/reconnect-with-id");
  13613. sse.set_reconnect_interval(100);
  13614. sse.set_max_reconnect_attempts(3);
  13615. sse.start_async();
  13616. // Wait for at least 2 connections
  13617. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13618. sse.stop();
  13619. // Verify behavior
  13620. std::lock_guard<std::mutex> lock(id_mutex);
  13621. EXPECT_GE(received_last_event_ids.size(), 2u);
  13622. // First connection should have no Last-Event-ID
  13623. if (!received_last_event_ids.empty()) {
  13624. EXPECT_EQ(received_last_event_ids[0], "");
  13625. }
  13626. // Second connection should have Last-Event-ID from first connection
  13627. if (received_last_event_ids.size() >= 2) {
  13628. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13629. }
  13630. }
  13631. // Test: set_headers updates headers used on reconnect
  13632. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13633. std::vector<std::string> received_tokens;
  13634. std::mutex token_mutex;
  13635. // Endpoint that captures Authorization header
  13636. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13637. {
  13638. std::lock_guard<std::mutex> lock(token_mutex);
  13639. received_tokens.push_back(req.get_header_value("Authorization"));
  13640. }
  13641. res.set_chunked_content_provider(
  13642. "text/event-stream", [](size_t offset, DataSink &sink) {
  13643. if (offset == 0) {
  13644. std::string event = "data: hello\n\n";
  13645. sink.write(event.data(), event.size());
  13646. }
  13647. return false; // Close connection to trigger reconnect
  13648. });
  13649. });
  13650. Client client("localhost", get_port());
  13651. Headers headers = {{"Authorization", "Bearer old-token"}};
  13652. sse::SSEClient sse(client, "/auth-check", headers);
  13653. // Update headers on each successful connection
  13654. sse.on_open(
  13655. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13656. sse.set_reconnect_interval(100);
  13657. sse.set_max_reconnect_attempts(3);
  13658. sse.start_async();
  13659. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13660. sse.stop();
  13661. std::lock_guard<std::mutex> lock(token_mutex);
  13662. ASSERT_GE(received_tokens.size(), 2u);
  13663. // First connection uses original header
  13664. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13665. // Second connection uses updated header from set_headers
  13666. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13667. }
  13668. // Test: 401 allows reconnection (so on_error can refresh headers)
  13669. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13670. std::atomic<int> connection_count{0};
  13671. // Endpoint: returns 401 on first attempt, 200 on second
  13672. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13673. int conn = connection_count.fetch_add(1);
  13674. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13675. res.status = StatusCode::Unauthorized_401;
  13676. res.set_content("Unauthorized", "text/plain");
  13677. return;
  13678. }
  13679. res.set_chunked_content_provider(
  13680. "text/event-stream", [](size_t offset, DataSink &sink) {
  13681. if (offset == 0) {
  13682. std::string event = "data: authenticated\n\n";
  13683. sink.write(event.data(), event.size());
  13684. }
  13685. return false;
  13686. });
  13687. });
  13688. Client client("localhost", get_port());
  13689. Headers headers = {{"Authorization", "Bearer expired"}};
  13690. sse::SSEClient sse(client, "/auth-retry", headers);
  13691. std::atomic<bool> message_received{false};
  13692. // Refresh token on error
  13693. sse.on_error(
  13694. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13695. sse.on_message([&](const sse::SSEMessage &msg) {
  13696. if (msg.data == "authenticated") { message_received.store(true); }
  13697. });
  13698. sse.set_reconnect_interval(100);
  13699. sse.set_max_reconnect_attempts(3);
  13700. sse.start_async();
  13701. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13702. sse.stop();
  13703. // Should have reconnected after 401 and succeeded with new token
  13704. EXPECT_GE(connection_count.load(), 2);
  13705. EXPECT_TRUE(message_received.load());
  13706. }
  13707. TEST(Issue2318Test, EmptyHostString) {
  13708. {
  13709. httplib::Client cli_empty("", PORT);
  13710. auto res = cli_empty.Get("/");
  13711. ASSERT_FALSE(res);
  13712. EXPECT_EQ(httplib::Error::Connection, res.error());
  13713. }
  13714. {
  13715. httplib::Client cli(" ", PORT);
  13716. auto res = cli.Get("/");
  13717. ASSERT_FALSE(res);
  13718. EXPECT_EQ(httplib::Error::Connection, res.error());
  13719. }
  13720. }
  13721. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13722. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13723. Server svr;
  13724. // Set a small payload limit (1KB)
  13725. svr.set_payload_max_length(1024);
  13726. svr.Post("/test", [&](const Request &req, Response &res) {
  13727. res.set_content("Body size: " + std::to_string(req.body.size()),
  13728. "text/plain");
  13729. });
  13730. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13731. auto se = detail::scope_exit([&] {
  13732. svr.stop();
  13733. listen_thread.join();
  13734. });
  13735. svr.wait_until_ready();
  13736. // Create data that compresses well but exceeds limit when decompressed
  13737. // 8KB of repeated null bytes compresses to a very small size
  13738. std::string original_data(8 * 1024, '\0');
  13739. // Compress the data using gzip
  13740. std::string compressed_data;
  13741. detail::gzip_compressor compressor;
  13742. compressor.compress(original_data.data(), original_data.size(), true,
  13743. [&](const char *data, size_t size) {
  13744. compressed_data.append(data, size);
  13745. return true;
  13746. });
  13747. // Verify compression worked (compressed should be much smaller)
  13748. ASSERT_LT(compressed_data.size(), original_data.size());
  13749. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13750. // Send compressed data with Content-Encoding: gzip
  13751. Client cli(HOST, PORT);
  13752. Headers headers = {{"Content-Encoding", "gzip"}};
  13753. auto res =
  13754. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13755. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13756. ASSERT_TRUE(res);
  13757. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13758. }
  13759. #endif
  13760. // ============================================================================
  13761. // OpenSSL-Specific Tests
  13762. // ============================================================================
  13763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13764. X509 *readCertificate(const std::string &strFileName) {
  13765. std::ifstream inStream(strFileName);
  13766. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13767. std::istreambuf_iterator<char>());
  13768. if (strCertPEM.empty()) return (nullptr);
  13769. BIO *pbCert = BIO_new(BIO_s_mem());
  13770. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13771. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13772. BIO_free(pbCert);
  13773. return (pCert);
  13774. }
  13775. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13776. std::ifstream inStream(strFileName);
  13777. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13778. std::istreambuf_iterator<char>());
  13779. if (strPrivateKeyPEM.empty()) return (nullptr);
  13780. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13781. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13782. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13783. BIO_free(pbPrivKey);
  13784. return (pPrivateKey);
  13785. }
  13786. TEST(BindServerTest, UpdateCerts) {
  13787. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13788. int port = svr.bind_to_any_port("0.0.0.0");
  13789. ASSERT_TRUE(svr.is_valid());
  13790. ASSERT_TRUE(port > 0);
  13791. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13792. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13793. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13794. ASSERT_TRUE(cert != nullptr);
  13795. ASSERT_TRUE(ca_cert != nullptr);
  13796. ASSERT_TRUE(key != nullptr);
  13797. X509_STORE *cert_store = X509_STORE_new();
  13798. X509_STORE_add_cert(cert_store, ca_cert);
  13799. // svr.update_certs(cert, key, cert_store); // deprecated
  13800. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13801. CLIENT_CA_CERT_FILE);
  13802. ASSERT_TRUE(svr.is_valid());
  13803. svr.stop();
  13804. X509_STORE_free(cert_store);
  13805. X509_free(cert);
  13806. X509_free(ca_cert);
  13807. EVP_PKEY_free(key);
  13808. }
  13809. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13810. // client CA list correctly for TLS handshake
  13811. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13812. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13813. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13814. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13815. ASSERT_TRUE(cert != nullptr);
  13816. ASSERT_TRUE(ca_cert != nullptr);
  13817. ASSERT_TRUE(key != nullptr);
  13818. X509_STORE *cert_store = X509_STORE_new();
  13819. X509_STORE_add_cert(cert_store, ca_cert);
  13820. // Use X509-based constructor (deprecated but should still work correctly)
  13821. #pragma GCC diagnostic push
  13822. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13823. SSLServer svr(cert, key, cert_store);
  13824. #pragma GCC diagnostic pop
  13825. ASSERT_TRUE(svr.is_valid());
  13826. // Verify that client CA list is set in SSL_CTX
  13827. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13828. ASSERT_TRUE(ssl_ctx != nullptr);
  13829. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13830. ASSERT_TRUE(ca_list != nullptr);
  13831. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13832. X509_free(cert);
  13833. X509_free(ca_cert);
  13834. EVP_PKEY_free(key);
  13835. }
  13836. // Test that update_certs() updates client CA list correctly
  13837. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13838. // Start with file-based constructor
  13839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13840. ASSERT_TRUE(svr.is_valid());
  13841. // Initially no client CA list should be set
  13842. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13843. ASSERT_TRUE(ssl_ctx != nullptr);
  13844. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13845. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13846. EXPECT_EQ(0, count_before);
  13847. // Now update with client CA (PEM string)
  13848. std::string cert_pem, key_pem, ca_pem;
  13849. read_file(SERVER_CERT_FILE, cert_pem);
  13850. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13851. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13852. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13853. ASSERT_TRUE(svr.is_valid());
  13854. // Now client CA list should be set
  13855. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13856. ASSERT_TRUE(ca_list_after != nullptr);
  13857. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13858. }
  13859. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13860. // Test that the file-path SSLServer constructor properly sets the client CA
  13861. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13862. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13863. ASSERT_TRUE(svr.is_valid());
  13864. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13865. ASSERT_TRUE(ssl_ctx != nullptr);
  13866. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13867. ASSERT_TRUE(ca_list != nullptr);
  13868. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13869. }
  13870. #endif
  13871. // ============================================================================
  13872. // MbedTLS-Specific Tests
  13873. // ============================================================================
  13874. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13875. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13876. using namespace httplib::tls;
  13877. // Track if callback was invoked
  13878. bool callback_invoked = false;
  13879. // The callback receives void* ctx which is actually MbedTlsContext*
  13880. // We can access the mbedtls_ssl_config via the context
  13881. auto setup_callback = [&callback_invoked](void *ctx) {
  13882. callback_invoked = true;
  13883. // Cast to MbedTlsContext* to access the ssl config
  13884. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13885. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13886. // Use static variables to hold certificate data (simplified for test)
  13887. static mbedtls_x509_crt own_cert;
  13888. static mbedtls_pk_context own_key;
  13889. static mbedtls_x509_crt ca_chain;
  13890. static bool initialized = false;
  13891. if (!initialized) {
  13892. mbedtls_x509_crt_init(&own_cert);
  13893. mbedtls_pk_init(&own_key);
  13894. mbedtls_x509_crt_init(&ca_chain);
  13895. // Load server certificate
  13896. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13897. return false;
  13898. }
  13899. // Load server private key
  13900. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13901. #if MBEDTLS_VERSION_MAJOR >= 3
  13902. ,
  13903. mbedtls_ctr_drbg_random, nullptr
  13904. #endif
  13905. ) != 0) {
  13906. return false;
  13907. }
  13908. // Load CA chain for client verification
  13909. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13910. return false;
  13911. }
  13912. initialized = true;
  13913. }
  13914. // Configure the SSL config
  13915. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13916. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13917. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13918. // Set minimum TLS version using mbedTLS native API
  13919. #if MBEDTLS_VERSION_MAJOR >= 3
  13920. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13921. #else
  13922. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13923. MBEDTLS_SSL_MINOR_VERSION_3);
  13924. #endif
  13925. return true;
  13926. };
  13927. SSLServer svr(setup_callback);
  13928. ASSERT_TRUE(svr.is_valid());
  13929. ASSERT_TRUE(callback_invoked);
  13930. svr.Get("/test", [&](const Request &req, Response &res) {
  13931. res.set_content("test", "text/plain");
  13932. auto cert = req.peer_cert();
  13933. ASSERT_TRUE(static_cast<bool>(cert));
  13934. auto common_name = cert.subject_cn();
  13935. EXPECT_EQ("Common Name", common_name);
  13936. });
  13937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13938. auto se = detail::scope_exit([&] {
  13939. svr.stop();
  13940. t.join();
  13941. ASSERT_FALSE(svr.is_running());
  13942. });
  13943. svr.wait_until_ready();
  13944. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13945. cli.enable_server_certificate_verification(false);
  13946. cli.set_connection_timeout(30);
  13947. auto res = cli.Get("/test");
  13948. ASSERT_TRUE(res);
  13949. ASSERT_EQ(StatusCode::OK_200, res->status);
  13950. }
  13951. #endif
  13952. // WebSocket Tests
  13953. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13954. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13955. // defining the meaning of these bits has been negotiated.
  13956. auto make_frame = [](uint8_t first_byte) {
  13957. std::string frame;
  13958. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13959. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13960. frame += "Hello";
  13961. return frame;
  13962. };
  13963. // RSV1 set (0x40)
  13964. {
  13965. detail::BufferStream strm;
  13966. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13967. ws::Opcode opcode;
  13968. std::string payload;
  13969. bool fin;
  13970. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13971. false, 1024));
  13972. }
  13973. // RSV2 set (0x20)
  13974. {
  13975. detail::BufferStream strm;
  13976. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13977. ws::Opcode opcode;
  13978. std::string payload;
  13979. bool fin;
  13980. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13981. false, 1024));
  13982. }
  13983. // RSV3 set (0x10)
  13984. {
  13985. detail::BufferStream strm;
  13986. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  13987. ws::Opcode opcode;
  13988. std::string payload;
  13989. bool fin;
  13990. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13991. false, 1024));
  13992. }
  13993. // No RSV bits set - should succeed
  13994. {
  13995. detail::BufferStream strm;
  13996. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  13997. ws::Opcode opcode;
  13998. std::string payload;
  13999. bool fin;
  14000. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14001. false, 1024));
  14002. EXPECT_EQ(ws::Opcode::Text, opcode);
  14003. EXPECT_EQ("Hello", payload);
  14004. EXPECT_TRUE(fin);
  14005. }
  14006. }
  14007. TEST(WebSocketTest, ControlFrameValidation) {
  14008. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14009. // payload length <= 125.
  14010. // Ping with FIN=0 - must be rejected
  14011. {
  14012. detail::BufferStream strm;
  14013. std::string frame;
  14014. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14015. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14016. strm.write(frame.data(), frame.size());
  14017. ws::Opcode opcode;
  14018. std::string payload;
  14019. bool fin;
  14020. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14021. false, 1024));
  14022. }
  14023. // Close with FIN=0 - must be rejected
  14024. {
  14025. detail::BufferStream strm;
  14026. std::string frame;
  14027. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14028. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14029. strm.write(frame.data(), frame.size());
  14030. ws::Opcode opcode;
  14031. std::string payload;
  14032. bool fin;
  14033. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14034. false, 1024));
  14035. }
  14036. // Ping with payload_len=126 (extended length) - must be rejected
  14037. {
  14038. detail::BufferStream strm;
  14039. std::string frame;
  14040. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14041. frame += static_cast<char>(126); // payload_len=126 (>125)
  14042. frame += static_cast<char>(0x00); // extended length high byte
  14043. frame += static_cast<char>(126); // extended length low byte
  14044. frame += std::string(126, 'x');
  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 FIN=1 and payload_len=125 - should succeed
  14053. {
  14054. detail::BufferStream strm;
  14055. std::string frame;
  14056. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14057. frame += static_cast<char>(125); // payload_len=125
  14058. frame += std::string(125, 'x');
  14059. strm.write(frame.data(), frame.size());
  14060. ws::Opcode opcode;
  14061. std::string payload;
  14062. bool fin;
  14063. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14064. false, 1024));
  14065. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14066. EXPECT_EQ(125u, payload.size());
  14067. EXPECT_TRUE(fin);
  14068. }
  14069. }
  14070. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14071. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14072. // length MUST be 0.
  14073. // MSB set - must be rejected
  14074. {
  14075. detail::BufferStream strm;
  14076. std::string frame;
  14077. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14078. frame += static_cast<char>(127); // 64-bit extended length
  14079. frame += static_cast<char>(0x80); // MSB set (invalid)
  14080. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14081. strm.write(frame.data(), frame.size());
  14082. ws::Opcode opcode;
  14083. std::string payload;
  14084. bool fin;
  14085. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14086. false, 1024));
  14087. }
  14088. // MSB clear - should pass length parsing (will be rejected by max_len,
  14089. // but that's a different check; use a small length to verify)
  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 += std::string(7, '\0'); // high bytes = 0
  14096. frame += static_cast<char>(0x03); // length = 3
  14097. frame += "abc";
  14098. strm.write(frame.data(), frame.size());
  14099. ws::Opcode opcode;
  14100. std::string payload;
  14101. bool fin;
  14102. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14103. false, 1024));
  14104. EXPECT_EQ(ws::Opcode::Text, opcode);
  14105. EXPECT_EQ("abc", payload);
  14106. }
  14107. }
  14108. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14109. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14110. // Valid UTF-8
  14111. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14112. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14113. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14114. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14115. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14116. // Invalid UTF-8
  14117. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14118. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14119. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14120. EXPECT_FALSE(
  14121. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14122. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14123. }
  14124. TEST(WebSocketTest, ConnectAndDisconnect) {
  14125. Server svr;
  14126. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14127. std::string msg;
  14128. while (ws.read(msg)) {}
  14129. });
  14130. auto port = svr.bind_to_any_port(HOST);
  14131. std::thread t([&]() { svr.listen_after_bind(); });
  14132. svr.wait_until_ready();
  14133. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14134. ASSERT_TRUE(client.connect());
  14135. EXPECT_TRUE(client.is_open());
  14136. client.close();
  14137. EXPECT_FALSE(client.is_open());
  14138. svr.stop();
  14139. t.join();
  14140. }
  14141. TEST(WebSocketTest, ValidURL) {
  14142. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14143. EXPECT_TRUE(ws1.is_valid());
  14144. ws::WebSocketClient ws2("ws://example.com/path");
  14145. EXPECT_TRUE(ws2.is_valid());
  14146. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14147. EXPECT_TRUE(ws3.is_valid());
  14148. #ifdef CPPHTTPLIB_SSL_ENABLED
  14149. ws::WebSocketClient wss1("wss://example.com/path");
  14150. EXPECT_TRUE(wss1.is_valid());
  14151. ws::WebSocketClient wss2("wss://example.com:443/path");
  14152. EXPECT_TRUE(wss2.is_valid());
  14153. #endif
  14154. }
  14155. TEST(WebSocketTest, InvalidURL) {
  14156. // No scheme
  14157. ws::WebSocketClient ws1("localhost:8080/path");
  14158. EXPECT_FALSE(ws1.is_valid());
  14159. // No path
  14160. ws::WebSocketClient ws2("ws://localhost:8080");
  14161. EXPECT_FALSE(ws2.is_valid());
  14162. // Empty string
  14163. ws::WebSocketClient ws3("");
  14164. EXPECT_FALSE(ws3.is_valid());
  14165. // Missing host
  14166. ws::WebSocketClient ws4("ws://:8080/path");
  14167. EXPECT_FALSE(ws4.is_valid());
  14168. // Port number overflow — should not crash
  14169. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14170. EXPECT_FALSE(ws5.is_valid());
  14171. // Port out of range
  14172. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14173. EXPECT_FALSE(ws6.is_valid());
  14174. }
  14175. TEST(WebSocketTest, UnsupportedScheme) {
  14176. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14177. ws::WebSocketClient ws1("http://localhost:8080/path");
  14178. EXPECT_FALSE(ws1.is_valid());
  14179. ws::WebSocketClient ws2("https://localhost:8080/path");
  14180. EXPECT_FALSE(ws2.is_valid());
  14181. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14182. EXPECT_FALSE(ws3.is_valid());
  14183. #else
  14184. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14185. std::invalid_argument);
  14186. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14187. std::invalid_argument);
  14188. #endif
  14189. }
  14190. TEST(WebSocketTest, ConnectWhenInvalid) {
  14191. ws::WebSocketClient ws("not a valid url");
  14192. EXPECT_FALSE(ws.is_valid());
  14193. EXPECT_FALSE(ws.connect());
  14194. }
  14195. TEST(WebSocketTest, DefaultPort) {
  14196. ws::WebSocketClient ws1("ws://example.com/path");
  14197. EXPECT_TRUE(ws1.is_valid());
  14198. // ws:// defaults to port 80 (verified by successful parse)
  14199. #ifdef CPPHTTPLIB_SSL_ENABLED
  14200. ws::WebSocketClient ws2("wss://example.com/path");
  14201. EXPECT_TRUE(ws2.is_valid());
  14202. // wss:// defaults to port 443 (verified by successful parse)
  14203. #endif
  14204. }
  14205. TEST(WebSocketTest, IPv6LiteralAddress) {
  14206. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14207. EXPECT_TRUE(ws1.is_valid());
  14208. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14209. EXPECT_TRUE(ws2.is_valid());
  14210. }
  14211. TEST(WebSocketTest, ComplexPath) {
  14212. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14213. EXPECT_TRUE(ws1.is_valid());
  14214. ws::WebSocketClient ws2("ws://localhost:8080/");
  14215. EXPECT_TRUE(ws2.is_valid());
  14216. }
  14217. class WebSocketIntegrationTest : public ::testing::Test {
  14218. protected:
  14219. void SetUp() override {
  14220. server_ = httplib::detail::make_unique<Server>();
  14221. setup_server();
  14222. start_server();
  14223. }
  14224. void TearDown() override {
  14225. server_->stop();
  14226. if (server_thread_.joinable()) { server_thread_.join(); }
  14227. }
  14228. void setup_server() {
  14229. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14230. std::string msg;
  14231. ws::ReadResult ret;
  14232. while ((ret = ws.read(msg))) {
  14233. if (ret == ws::Binary) {
  14234. ws.send(msg.data(), msg.size());
  14235. } else {
  14236. ws.send(msg);
  14237. }
  14238. }
  14239. });
  14240. server_->WebSocket("/ws-echo-string",
  14241. [](const Request &, ws::WebSocket &ws) {
  14242. std::string msg;
  14243. while (ws.read(msg)) {
  14244. ws.send("echo: " + msg);
  14245. }
  14246. });
  14247. server_->WebSocket(
  14248. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14249. // Echo back request metadata
  14250. ws.send("path:" + req.path);
  14251. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14252. std::string msg;
  14253. while (ws.read(msg)) {}
  14254. });
  14255. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14256. std::string msg;
  14257. ws.read(msg); // wait for a message
  14258. ws.close();
  14259. });
  14260. server_->WebSocket("/ws-close-status",
  14261. [](const Request &, ws::WebSocket &ws) {
  14262. std::string msg;
  14263. ws.read(msg); // wait for a message
  14264. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14265. });
  14266. server_->WebSocket(
  14267. "/ws-subprotocol",
  14268. [](const Request &, ws::WebSocket &ws) {
  14269. std::string msg;
  14270. while (ws.read(msg)) {
  14271. ws.send(msg);
  14272. }
  14273. },
  14274. [](const std::vector<std::string> &protocols) -> std::string {
  14275. for (const auto &p : protocols) {
  14276. if (p == "graphql-ws") { return p; }
  14277. }
  14278. return "";
  14279. });
  14280. }
  14281. void start_server() {
  14282. port_ = server_->bind_to_any_port(HOST);
  14283. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14284. server_->wait_until_ready();
  14285. }
  14286. std::unique_ptr<Server> server_;
  14287. std::thread server_thread_;
  14288. int port_ = 0;
  14289. };
  14290. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14291. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14292. "/ws-echo");
  14293. ASSERT_TRUE(client.connect());
  14294. ASSERT_TRUE(client.is_open());
  14295. ASSERT_TRUE(client.send("Hello WebSocket"));
  14296. std::string msg;
  14297. EXPECT_EQ(ws::Text, client.read(msg));
  14298. EXPECT_EQ("Hello WebSocket", msg);
  14299. client.close();
  14300. }
  14301. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14303. "/ws-echo");
  14304. ASSERT_TRUE(client.connect());
  14305. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14306. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14307. std::string msg;
  14308. EXPECT_EQ(ws::Binary, client.read(msg));
  14309. EXPECT_EQ(binary_data, msg);
  14310. client.close();
  14311. }
  14312. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14313. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14314. "/ws-echo");
  14315. ASSERT_TRUE(client.connect());
  14316. for (int i = 0; i < 10; i++) {
  14317. auto text = "message " + std::to_string(i);
  14318. ASSERT_TRUE(client.send(text));
  14319. std::string msg;
  14320. ASSERT_TRUE(client.read(msg));
  14321. EXPECT_EQ(text, msg);
  14322. }
  14323. client.close();
  14324. }
  14325. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14326. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14327. "/ws-close");
  14328. ASSERT_TRUE(client.connect());
  14329. // Send a message to trigger the server to close
  14330. ASSERT_TRUE(client.send("trigger close"));
  14331. // The server will close, so read should return false
  14332. std::string msg;
  14333. EXPECT_FALSE(client.read(msg));
  14334. EXPECT_FALSE(client.is_open());
  14335. }
  14336. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14337. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14338. "/ws-echo");
  14339. ASSERT_TRUE(client.connect());
  14340. // 128KB message
  14341. std::string large_data(128 * 1024, 'X');
  14342. ASSERT_TRUE(client.send(large_data));
  14343. std::string msg;
  14344. ASSERT_TRUE(client.read(msg));
  14345. EXPECT_EQ(large_data, msg);
  14346. client.close();
  14347. }
  14348. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14349. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14350. "/ws-echo");
  14351. ASSERT_TRUE(client.connect());
  14352. const int num_threads = 4;
  14353. std::vector<std::thread> threads;
  14354. std::atomic<int> send_count{0};
  14355. for (int t = 0; t < num_threads; t++) {
  14356. threads.emplace_back([&client, &send_count, t]() {
  14357. for (int i = 0; i < 5; i++) {
  14358. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14359. if (client.send(text)) { send_count++; }
  14360. }
  14361. });
  14362. }
  14363. for (auto &th : threads) {
  14364. th.join();
  14365. }
  14366. int received = 0;
  14367. std::string msg;
  14368. while (received < send_count.load()) {
  14369. if (!client.read(msg)) { break; }
  14370. received++;
  14371. }
  14372. EXPECT_EQ(send_count.load(), received);
  14373. client.close();
  14374. }
  14375. TEST_F(WebSocketIntegrationTest, ReadString) {
  14376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14377. "/ws-echo-string");
  14378. ASSERT_TRUE(client.connect());
  14379. ASSERT_TRUE(client.send("hello"));
  14380. std::string msg;
  14381. ASSERT_TRUE(client.read(msg));
  14382. EXPECT_EQ("echo: hello", msg);
  14383. ASSERT_TRUE(client.send("world"));
  14384. ASSERT_TRUE(client.read(msg));
  14385. EXPECT_EQ("echo: world", msg);
  14386. client.close();
  14387. }
  14388. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14389. Headers headers = {{"X-Test-Header", "test-value"}};
  14390. ws::WebSocketClient client(
  14391. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14392. ASSERT_TRUE(client.connect());
  14393. std::string msg;
  14394. ASSERT_TRUE(client.read(msg));
  14395. EXPECT_EQ("path:/ws-request-info", msg);
  14396. ASSERT_TRUE(client.read(msg));
  14397. EXPECT_EQ("header:test-value", msg);
  14398. client.close();
  14399. }
  14400. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14401. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14402. "/ws-echo");
  14403. client.set_read_timeout(1, 0); // 1 second
  14404. ASSERT_TRUE(client.connect());
  14405. // Don't send anything — server echo handler waits for a message,
  14406. // so read() should time out and return false.
  14407. std::string msg;
  14408. EXPECT_FALSE(client.read(msg));
  14409. }
  14410. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14411. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14412. "/ws-echo");
  14413. client.set_read_timeout(5, 0);
  14414. ASSERT_TRUE(client.connect());
  14415. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14416. // The server should reject it and close the connection.
  14417. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14418. client.send(oversized);
  14419. // The server's read() should have failed due to payload limit,
  14420. // so our read() should return false (connection closed).
  14421. std::string msg;
  14422. EXPECT_FALSE(client.read(msg));
  14423. }
  14424. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14426. "/ws-echo");
  14427. client.set_read_timeout(10, 0);
  14428. ASSERT_TRUE(client.connect());
  14429. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14430. // This should succeed.
  14431. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14432. ASSERT_TRUE(client.send(at_limit));
  14433. std::string msg;
  14434. ASSERT_TRUE(client.read(msg));
  14435. EXPECT_EQ(at_limit.size(), msg.size());
  14436. client.close();
  14437. }
  14438. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14439. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14440. "/nonexistent");
  14441. EXPECT_FALSE(client.connect());
  14442. EXPECT_FALSE(client.is_open());
  14443. }
  14444. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14445. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14446. "/ws-echo");
  14447. ASSERT_TRUE(client.connect());
  14448. ASSERT_TRUE(client.send(""));
  14449. std::string msg;
  14450. EXPECT_EQ(ws::Text, client.read(msg));
  14451. EXPECT_EQ("", msg);
  14452. client.close();
  14453. }
  14454. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14455. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14456. "/ws-echo");
  14457. // First connection
  14458. ASSERT_TRUE(client.connect());
  14459. ASSERT_TRUE(client.send("first"));
  14460. std::string msg;
  14461. ASSERT_TRUE(client.read(msg));
  14462. EXPECT_EQ("first", msg);
  14463. client.close();
  14464. EXPECT_FALSE(client.is_open());
  14465. // Reconnect using the same client object
  14466. ASSERT_TRUE(client.connect());
  14467. ASSERT_TRUE(client.is_open());
  14468. ASSERT_TRUE(client.send("second"));
  14469. ASSERT_TRUE(client.read(msg));
  14470. EXPECT_EQ("second", msg);
  14471. client.close();
  14472. }
  14473. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14474. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14475. "/ws-close-status");
  14476. ASSERT_TRUE(client.connect());
  14477. // Trigger the server to close with GoingAway status
  14478. ASSERT_TRUE(client.send("trigger"));
  14479. // read() should return false after receiving the close frame
  14480. std::string msg;
  14481. EXPECT_FALSE(client.read(msg));
  14482. EXPECT_FALSE(client.is_open());
  14483. }
  14484. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14485. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14486. "/ws-echo");
  14487. ASSERT_TRUE(client.connect());
  14488. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14489. EXPECT_FALSE(client.is_open());
  14490. }
  14491. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14492. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14493. ws::WebSocketClient client(
  14494. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14495. ASSERT_TRUE(client.connect());
  14496. // Server should have selected graphql-ws
  14497. EXPECT_EQ("graphql-ws", client.subprotocol());
  14498. client.close();
  14499. }
  14500. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14501. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14502. ws::WebSocketClient client(
  14503. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14504. ASSERT_TRUE(client.connect());
  14505. // Server should not have selected any subprotocol
  14506. EXPECT_TRUE(client.subprotocol().empty());
  14507. client.close();
  14508. }
  14509. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14510. // Connect without requesting any subprotocol
  14511. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14512. "/ws-subprotocol");
  14513. ASSERT_TRUE(client.connect());
  14514. EXPECT_TRUE(client.subprotocol().empty());
  14515. client.close();
  14516. }
  14517. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14518. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14519. "/ws-echo");
  14520. client.set_tcp_nodelay(true);
  14521. client.set_address_family(AF_INET);
  14522. client.set_connection_timeout(3, 0);
  14523. bool socket_options_called = false;
  14524. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14525. ASSERT_TRUE(client.connect());
  14526. ASSERT_TRUE(client.is_open());
  14527. EXPECT_TRUE(socket_options_called);
  14528. ASSERT_TRUE(client.send("hello"));
  14529. std::string msg;
  14530. auto result = client.read(msg);
  14531. EXPECT_EQ(result, ws::ReadResult::Text);
  14532. EXPECT_EQ(msg, "hello");
  14533. client.close();
  14534. }
  14535. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14536. Server svr;
  14537. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14538. if (!req.has_header("Authorization")) {
  14539. res.status = StatusCode::Unauthorized_401;
  14540. res.set_content("Unauthorized", "text/plain");
  14541. return Server::HandlerResponse::Handled;
  14542. }
  14543. return Server::HandlerResponse::Unhandled;
  14544. });
  14545. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14546. std::string msg;
  14547. while (ws.read(msg)) {
  14548. ws.send(msg);
  14549. }
  14550. });
  14551. auto port = svr.bind_to_any_port("localhost");
  14552. std::thread t([&]() { svr.listen_after_bind(); });
  14553. svr.wait_until_ready();
  14554. // Without Authorization header - should be rejected before upgrade
  14555. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14556. EXPECT_FALSE(client1.connect());
  14557. // With Authorization header - should succeed
  14558. Headers headers = {{"Authorization", "Bearer token123"}};
  14559. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14560. headers);
  14561. ASSERT_TRUE(client2.connect());
  14562. ASSERT_TRUE(client2.send("hello"));
  14563. std::string msg;
  14564. ASSERT_TRUE(client2.read(msg));
  14565. EXPECT_EQ("hello", msg);
  14566. client2.close();
  14567. svr.stop();
  14568. t.join();
  14569. }
  14570. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14571. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14572. protected:
  14573. void SetUp() override {
  14574. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14575. SERVER_PRIVATE_KEY_FILE);
  14576. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14577. std::string msg;
  14578. ws::ReadResult ret;
  14579. while ((ret = ws.read(msg))) {
  14580. if (ret == ws::Binary) {
  14581. ws.send(msg.data(), msg.size());
  14582. } else {
  14583. ws.send(msg);
  14584. }
  14585. }
  14586. });
  14587. port_ = server_->bind_to_any_port(HOST);
  14588. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14589. server_->wait_until_ready();
  14590. }
  14591. void TearDown() override {
  14592. server_->stop();
  14593. if (server_thread_.joinable()) { server_thread_.join(); }
  14594. }
  14595. std::unique_ptr<SSLServer> server_;
  14596. std::thread server_thread_;
  14597. int port_ = 0;
  14598. };
  14599. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14600. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14601. "/ws-echo");
  14602. client.enable_server_certificate_verification(false);
  14603. ASSERT_TRUE(client.connect());
  14604. ASSERT_TRUE(client.is_open());
  14605. ASSERT_TRUE(client.send("Hello WSS"));
  14606. std::string msg;
  14607. EXPECT_EQ(ws::Text, client.read(msg));
  14608. EXPECT_EQ("Hello WSS", msg);
  14609. client.close();
  14610. }
  14611. #endif
  14612. #if !defined(_WIN32)
  14613. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14614. auto secret_dir = std::string("./symlink_test_secret");
  14615. auto served_dir = std::string("./symlink_test_served");
  14616. auto secret_file = secret_dir + "/secret.txt";
  14617. auto symlink_path = served_dir + "/escape";
  14618. // Setup: create directories and files
  14619. mkdir(secret_dir.c_str(), 0755);
  14620. mkdir(served_dir.c_str(), 0755);
  14621. {
  14622. std::ofstream ofs(secret_file);
  14623. ofs << "SECRET_DATA";
  14624. }
  14625. // Create symlink using absolute path so it resolves correctly
  14626. char abs_secret[PATH_MAX];
  14627. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14628. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14629. auto se = detail::scope_exit([&] {
  14630. unlink(symlink_path.c_str());
  14631. unlink(secret_file.c_str());
  14632. rmdir(served_dir.c_str());
  14633. rmdir(secret_dir.c_str());
  14634. });
  14635. Server svr;
  14636. svr.set_mount_point("/", served_dir);
  14637. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14638. auto se2 = detail::scope_exit([&] {
  14639. svr.stop();
  14640. listen_thread.join();
  14641. });
  14642. svr.wait_until_ready();
  14643. Client cli("localhost", PORT);
  14644. // Symlink pointing outside base dir should be blocked
  14645. auto res = cli.Get("/escape/secret.txt");
  14646. ASSERT_TRUE(res);
  14647. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14648. }
  14649. #endif
  14650. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14651. // A GET request with Content-Length to a static file handler must have its
  14652. // body drained before the keep-alive connection is reused. Otherwise the
  14653. // unread body bytes are interpreted as the next HTTP request.
  14654. //
  14655. // The body is sent AFTER receiving the first response (as in the original
  14656. // PoC) so that the stream_line_reader cannot buffer it together with the
  14657. // headers of the first request.
  14658. Server svr;
  14659. svr.set_mount_point("/", "./www");
  14660. std::atomic<int> smuggled_count(0);
  14661. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14662. smuggled_count++;
  14663. res.set_content("oops", "text/plain");
  14664. });
  14665. auto port = svr.bind_to_any_port("localhost");
  14666. thread t = thread([&] { svr.listen_after_bind(); });
  14667. auto se = detail::scope_exit([&] {
  14668. svr.stop();
  14669. t.join();
  14670. });
  14671. svr.wait_until_ready();
  14672. auto error = Error::Success;
  14673. auto sock = detail::create_client_socket(
  14674. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14675. /*connection_timeout_sec=*/2, 0,
  14676. /*read_timeout_sec=*/2, 0,
  14677. /*write_timeout_sec=*/2, 0, std::string(), error);
  14678. ASSERT_NE(INVALID_SOCKET, sock);
  14679. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14680. // The "smuggled" request will be sent as the body of the outer GET
  14681. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14682. "Host: localhost\r\n"
  14683. "Connection: close\r\n"
  14684. "\r\n";
  14685. // Step 1: Send only the outer request headers (no body yet)
  14686. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14687. "Host: localhost\r\n"
  14688. "Content-Length: " +
  14689. std::to_string(smuggled.size()) +
  14690. "\r\n"
  14691. "\r\n";
  14692. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  14693. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14694. // Step 2: Read the first response (server serves file without reading body)
  14695. std::string first_response;
  14696. char buf[4096];
  14697. for (;;) {
  14698. auto n = recv(sock, buf, sizeof(buf), 0);
  14699. if (n <= 0) break;
  14700. first_response.append(buf, static_cast<size_t>(n));
  14701. // Stop once we have a complete response (headers + body)
  14702. auto hdr_end = first_response.find("\r\n\r\n");
  14703. if (hdr_end != std::string::npos) {
  14704. // Check for Content-Length to know when the body is complete
  14705. auto cl_pos = first_response.find("Content-Length:");
  14706. if (cl_pos != std::string::npos) {
  14707. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14708. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14709. auto cl = std::stoul(
  14710. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14711. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14712. } else {
  14713. break; // No Content-Length, assume headers-only response
  14714. }
  14715. }
  14716. }
  14717. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14718. // Step 3: Now send the body, which looks like a new HTTP request.
  14719. // On a vulnerable server the keep-alive loop reads this as a second request.
  14720. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  14721. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14722. // Step 4: Try to read a second response (should NOT exist after fix)
  14723. std::string second_response;
  14724. for (;;) {
  14725. auto n = recv(sock, buf, sizeof(buf), 0);
  14726. if (n <= 0) break;
  14727. second_response.append(buf, static_cast<size_t>(n));
  14728. }
  14729. // The smuggled request must NOT have been processed
  14730. EXPECT_EQ(0, smuggled_count.load());
  14731. }
  14732. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14733. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14734. // must be rejected with 400 Bad Request.
  14735. Server svr;
  14736. svr.Post("/test", [&](const Request &, Response &res) {
  14737. res.set_content("ok", "text/plain");
  14738. });
  14739. thread t = thread([&] { svr.listen(HOST, PORT); });
  14740. auto se = detail::scope_exit([&] {
  14741. svr.stop();
  14742. t.join();
  14743. ASSERT_FALSE(svr.is_running());
  14744. });
  14745. svr.wait_until_ready();
  14746. // Exact "chunked"
  14747. {
  14748. auto req = "POST /test HTTP/1.1\r\n"
  14749. "Host: localhost\r\n"
  14750. "Content-Length: 5\r\n"
  14751. "Transfer-Encoding: chunked\r\n"
  14752. "Connection: close\r\n"
  14753. "\r\n"
  14754. "hello";
  14755. std::string response;
  14756. ASSERT_TRUE(send_request(1, req, &response));
  14757. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14758. response.substr(0, response.find("\r\n")));
  14759. }
  14760. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  14761. {
  14762. auto req = "POST /test HTTP/1.1\r\n"
  14763. "Host: localhost\r\n"
  14764. "Content-Length: 5\r\n"
  14765. "Transfer-Encoding: gzip, chunked\r\n"
  14766. "Connection: close\r\n"
  14767. "\r\n"
  14768. "hello";
  14769. std::string response;
  14770. ASSERT_TRUE(send_request(1, req, &response));
  14771. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14772. response.substr(0, response.find("\r\n")));
  14773. }
  14774. }