test.cc 543 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. static int get_base_port() {
  53. const char *shard = getenv("GTEST_SHARD_INDEX");
  54. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  55. }
  56. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  57. // New standalone tests MUST use svr.bind_to_any_port() instead.
  58. const int PORT = get_base_port();
  59. const string LONG_QUERY_VALUE = string(25000, '@');
  60. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  61. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  62. const string TOO_LONG_QUERY_URL =
  63. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  64. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  65. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  66. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  67. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  68. return file.name == key;
  69. });
  70. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  71. return *it;
  72. #else
  73. if (it != items.end()) { return *it; }
  74. throw std::runtime_error("invalid multipart form data name error");
  75. #endif
  76. }
  77. static void read_file(const std::string &path, std::string &out) {
  78. std::ifstream fs(path, std::ios_base::binary);
  79. if (!fs) {
  80. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  81. return;
  82. #else
  83. throw std::runtime_error("File not found: " + path);
  84. #endif
  85. }
  86. fs.seekg(0, std::ios_base::end);
  87. auto size = fs.tellg();
  88. fs.seekg(0);
  89. out.resize(static_cast<size_t>(size));
  90. fs.read(&out[0], static_cast<std::streamsize>(size));
  91. }
  92. class UnixSocketTest : public ::testing::Test {
  93. protected:
  94. void TearDown() override { std::remove(pathname_.c_str()); }
  95. void client_GET(const std::string &addr) {
  96. httplib::Client cli{addr};
  97. cli.set_address_family(AF_UNIX);
  98. ASSERT_TRUE(cli.is_valid());
  99. const auto &result = cli.Get(pattern_);
  100. ASSERT_TRUE(result) << "error: " << result.error();
  101. const auto &resp = result.value();
  102. EXPECT_EQ(resp.status, StatusCode::OK_200);
  103. EXPECT_EQ(resp.body, content_);
  104. }
  105. static std::string make_sock_path() {
  106. const char *shard = getenv("GTEST_SHARD_INDEX");
  107. return shard ? std::string("./httplib-server-") + shard + ".sock"
  108. : "./httplib-server.sock";
  109. }
  110. const std::string pathname_{make_sock_path()};
  111. const std::string pattern_{"/hi"};
  112. const std::string content_{"Hello World!"};
  113. };
  114. TEST_F(UnixSocketTest, pathname) {
  115. httplib::Server svr;
  116. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  117. res.set_content(content_, "text/plain");
  118. });
  119. std::thread t{[&] {
  120. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  121. }};
  122. auto se = detail::scope_exit([&] {
  123. svr.stop();
  124. t.join();
  125. ASSERT_FALSE(svr.is_running());
  126. });
  127. svr.wait_until_ready();
  128. ASSERT_TRUE(svr.is_running());
  129. client_GET(pathname_);
  130. }
  131. #if defined(__linux__) || \
  132. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  133. TEST_F(UnixSocketTest, PeerPid) {
  134. httplib::Server svr;
  135. std::string remote_port_val;
  136. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  137. res.set_content(content_, "text/plain");
  138. remote_port_val = std::to_string(req.remote_port);
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  152. }
  153. #endif
  154. #ifdef __linux__
  155. TEST_F(UnixSocketTest, abstract) {
  156. constexpr char svr_path[]{"\x00httplib-server.sock"};
  157. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  158. httplib::Server svr;
  159. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(abstract_addr);
  173. }
  174. #endif
  175. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  176. httplib::Server svr;
  177. std::string received_host_header;
  178. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  179. // Capture the Host header sent by the client
  180. auto host_iter = req.headers.find("Host");
  181. if (host_iter != req.headers.end()) {
  182. received_host_header = host_iter->second;
  183. }
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. // Test that Host header is automatically set to "localhost" for Unix socket
  197. // connections
  198. httplib::Client cli{pathname_};
  199. cli.set_address_family(AF_UNIX);
  200. ASSERT_TRUE(cli.is_valid());
  201. const auto &result = cli.Get(pattern_);
  202. ASSERT_TRUE(result) << "error: " << result.error();
  203. const auto &resp = result.value();
  204. EXPECT_EQ(resp.status, StatusCode::OK_200);
  205. EXPECT_EQ(resp.body, content_);
  206. // Verify that Host header was automatically set to "localhost"
  207. EXPECT_EQ(received_host_header, "localhost");
  208. }
  209. #ifndef _WIN32
  210. TEST(SocketStream, wait_writable_UNIX) {
  211. int fds[2];
  212. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  213. const auto asSocketStream = [&](socket_t fd,
  214. std::function<bool(Stream &)> func) {
  215. return detail::process_client_socket(
  216. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  217. };
  218. asSocketStream(fds[0], [&](Stream &s0) {
  219. EXPECT_EQ(s0.socket(), fds[0]);
  220. EXPECT_TRUE(s0.wait_writable());
  221. EXPECT_TRUE(s0.is_peer_alive());
  222. EXPECT_EQ(0, close(fds[1]));
  223. EXPECT_FALSE(s0.is_peer_alive());
  224. return true;
  225. });
  226. EXPECT_EQ(0, close(fds[0]));
  227. }
  228. TEST(SocketStream, wait_writable_INET) {
  229. sockaddr_in addr;
  230. memset(&addr, 0, sizeof(addr));
  231. addr.sin_family = AF_INET;
  232. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  233. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  234. int disconnected_svr_sock = -1;
  235. std::thread svr{[&] {
  236. const int s = socket(AF_INET, SOCK_STREAM, 0);
  237. ASSERT_LE(0, s);
  238. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  239. ASSERT_EQ(0, listen(s, 1));
  240. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  241. ASSERT_EQ(0, close(s));
  242. }};
  243. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  244. std::thread cli{[&] {
  245. const int s = socket(AF_INET, SOCK_STREAM, 0);
  246. ASSERT_LE(0, s);
  247. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  248. ASSERT_EQ(0, close(s));
  249. }};
  250. cli.join();
  251. svr.join();
  252. ASSERT_NE(disconnected_svr_sock, -1);
  253. const auto asSocketStream = [&](socket_t fd,
  254. std::function<bool(Stream &)> func) {
  255. return detail::process_client_socket(
  256. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  257. };
  258. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  259. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  260. // wait_writable() returns true because select_write() only checks if the
  261. // send buffer has space. Peer disconnection is detected later by send().
  262. EXPECT_TRUE(ss.wait_writable());
  263. return true;
  264. });
  265. ASSERT_EQ(0, close(disconnected_svr_sock));
  266. }
  267. #endif // #ifndef _WIN32
  268. TEST(SetSocketOptTest, TcpNoDelay) {
  269. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_NE(sock, INVALID_SOCKET);
  271. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  272. int val = 0;
  273. socklen_t len = sizeof(val);
  274. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  275. reinterpret_cast<char *>(&val), &len));
  276. EXPECT_NE(val, 0);
  277. detail::close_socket(sock);
  278. }
  279. TEST(ClientTest, MoveConstructible) {
  280. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  281. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  282. }
  283. TEST(ClientTest, MoveAssignable) {
  284. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  285. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  286. }
  287. #ifdef _WIN32
  288. TEST(StartupTest, WSAStartup) {
  289. WSADATA wsaData;
  290. int ret = WSAStartup(0x0002, &wsaData);
  291. ASSERT_EQ(0, ret);
  292. }
  293. #endif
  294. TEST(DecodePathTest, PercentCharacter) {
  295. EXPECT_EQ(
  296. decode_path_component(
  297. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  298. U8("descrip=Gastos áéíóúñÑ 6"));
  299. }
  300. TEST(DecodePathTest, PercentCharacterNUL) {
  301. string expected;
  302. expected.push_back('x');
  303. expected.push_back('\0');
  304. expected.push_back('x');
  305. EXPECT_EQ(decode_path_component("x%00x"), expected);
  306. }
  307. TEST(DecodePathTest, UnicodeEncoding) {
  308. // %u0041 = 'A' (1-byte UTF-8)
  309. EXPECT_EQ("A", decode_path_component("%u0041"));
  310. // %u00E9 = 'é' (2-byte UTF-8)
  311. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  312. // %u3042 = 'あ' (3-byte UTF-8)
  313. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  314. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  315. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  316. // %uD800 = surrogate (invalid, silently dropped)
  317. EXPECT_EQ("", decode_path_component("%uD800"));
  318. }
  319. TEST(SanitizeFilenameTest, VariousPatterns) {
  320. // Path traversal
  321. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  322. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  323. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  324. // Normal and edge cases
  325. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  326. EXPECT_EQ("filename.txt",
  327. httplib::sanitize_filename("/path/to/filename.txt"));
  328. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  329. EXPECT_EQ("", httplib::sanitize_filename(".."));
  330. EXPECT_EQ("", httplib::sanitize_filename(""));
  331. // Null bytes stripped
  332. EXPECT_EQ("safe.txt",
  333. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  334. // Whitespace-only rejected
  335. EXPECT_EQ("", httplib::sanitize_filename(" "));
  336. }
  337. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  338. string unescapedCharacters = "-_.!~*'()";
  339. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  340. }
  341. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  342. string reservedCharacters = ";,/?:@&=+$";
  343. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  344. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  345. }
  346. TEST(ClientQueryOrder, PreserveOrder) {
  347. // This test reproduces Issue #2259: client may reorder query parameters
  348. // when sending a GET request. The expected behavior is that the client
  349. // preserves the original query string order when the caller supplied it
  350. // as part of the path.
  351. Server svr;
  352. svr.Get("/", [&](const Request &req, Response &res) {
  353. // Echo back the raw target so the test can assert ordering
  354. res.set_content(req.target, "text/plain");
  355. });
  356. std::thread t{[&] { svr.listen(HOST, PORT); }};
  357. auto se = detail::scope_exit([&] {
  358. svr.stop();
  359. t.join();
  360. ASSERT_FALSE(svr.is_running());
  361. });
  362. svr.wait_until_ready();
  363. Client cli(HOST, PORT);
  364. ASSERT_TRUE(cli.is_valid());
  365. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  366. auto res = cli.Get(original);
  367. ASSERT_TRUE(res);
  368. // Expect the echoed target to exactly match the original path (order
  369. // preserved)
  370. EXPECT_EQ(res->body, original);
  371. }
  372. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  373. string chineseCharacters = U8("中国語");
  374. string russianCharacters = U8("дом");
  375. string brazilianCharacters = U8("óculos");
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  383. string unescapedCharacters = "-_.!~*'()";
  384. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  385. }
  386. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  387. string reservedCharacters = ";,/?:@&=+$";
  388. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  389. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  390. }
  391. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  392. string chineseCharacters = U8("中国語");
  393. string russianCharacters = U8("дом");
  394. string brazilianCharacters = U8("óculos");
  395. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  396. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  397. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  398. "%D0%B4%D0%BE%D0%BC");
  399. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  400. }
  401. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  402. // Issue #2082 use case: encoding path component with ampersand
  403. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  404. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  405. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  406. }
  407. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  408. string unescapedCharacters = "-_.!~*'()";
  409. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  410. }
  411. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  412. string reservedCharacters = ";,/?:@&=+$#";
  413. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  414. }
  415. TEST(EncodeUriTest, TestUTF8Characters) {
  416. string chineseCharacters = U8("中国語");
  417. string russianCharacters = U8("дом");
  418. string brazilianCharacters = U8("óculos");
  419. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  420. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  421. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  422. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  423. }
  424. TEST(EncodeUriTest, TestCompleteUri) {
  425. string uri =
  426. "https://example.com/path/to/resource?query=value&param=test#fragment";
  427. EXPECT_EQ(
  428. httplib::encode_uri(uri),
  429. "https://example.com/path/to/resource?query=value&param=test#fragment");
  430. }
  431. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  432. string uri =
  433. "https://example.com/path with spaces/file name.html?q=hello world";
  434. EXPECT_EQ(httplib::encode_uri(uri),
  435. "https://example.com/path%20with%20spaces/"
  436. "file%20name.html?q=hello%20world");
  437. }
  438. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  439. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  440. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  441. }
  442. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  443. string unescapedCharacters = "-_.!~*'()";
  444. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  445. }
  446. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  447. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  448. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  449. string encodedBrazilian = "%C3%B3culos";
  450. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  451. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  452. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  453. }
  454. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  455. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  456. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  457. "Piri Tommy Villiers - on & on");
  458. }
  459. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  460. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  461. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  462. }
  463. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  464. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  465. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  466. }
  467. TEST(DecodeUriTest, TestUTF8Characters) {
  468. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  469. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  470. string encodedBrazilian = "%C3%B3culos";
  471. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  472. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  473. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  474. }
  475. TEST(DecodeUriTest, TestCompleteUri) {
  476. string encodedUri = "https://example.com/path%20with%20spaces/"
  477. "file%20name.html?q=hello%20world";
  478. EXPECT_EQ(
  479. httplib::decode_uri(encodedUri),
  480. "https://example.com/path with spaces/file name.html?q=hello world");
  481. }
  482. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  483. string original =
  484. "https://example.com/path with spaces/file name.html?q=hello world";
  485. string encoded = httplib::encode_uri(original);
  486. string decoded = httplib::decode_uri(encoded);
  487. EXPECT_EQ(decoded, original);
  488. }
  489. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  490. string original = "Piri Tommy Villiers - on & on";
  491. string encoded = httplib::encode_uri_component(original);
  492. string decoded = httplib::decode_uri_component(encoded);
  493. EXPECT_EQ(decoded, original);
  494. }
  495. TEST(TrimTests, TrimStringTests) {
  496. EXPECT_EQ("abc", detail::trim_copy("abc"));
  497. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  498. EXPECT_TRUE(detail::trim_copy("").empty());
  499. }
  500. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  501. // Simple case without quality values
  502. std::vector<std::string> result1;
  503. EXPECT_TRUE(detail::parse_accept_header(
  504. "text/html,application/json,text/plain", result1));
  505. EXPECT_EQ(result1.size(), 3U);
  506. EXPECT_EQ(result1[0], "text/html");
  507. EXPECT_EQ(result1[1], "application/json");
  508. EXPECT_EQ(result1[2], "text/plain");
  509. // With quality values
  510. std::vector<std::string> result2;
  511. EXPECT_TRUE(detail::parse_accept_header(
  512. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  513. EXPECT_EQ(result2.size(), 3U);
  514. EXPECT_EQ(result2[0], "application/json"); // highest q value
  515. EXPECT_EQ(result2[1], "text/html");
  516. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  517. }
  518. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  519. // Mixed with and without quality values
  520. std::vector<std::string> result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  523. EXPECT_EQ(result.size(), 3U);
  524. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  525. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  526. EXPECT_EQ(result[2], "application/json"); // q=0.5
  527. }
  528. TEST(ParseAcceptHeaderTest, EdgeCases) {
  529. // Empty header
  530. std::vector<std::string> empty_result;
  531. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  532. EXPECT_TRUE(empty_result.empty());
  533. // Single type
  534. std::vector<std::string> single_result;
  535. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  536. EXPECT_EQ(single_result.size(), 1U);
  537. EXPECT_EQ(single_result[0], "application/json");
  538. // Wildcard types
  539. std::vector<std::string> wildcard_result;
  540. EXPECT_TRUE(detail::parse_accept_header(
  541. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  542. EXPECT_EQ(wildcard_result.size(), 3U);
  543. EXPECT_EQ(wildcard_result[0], "application/json");
  544. EXPECT_EQ(wildcard_result[1], "text/*");
  545. EXPECT_EQ(wildcard_result[2], "*/*");
  546. }
  547. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  548. // Common browser Accept header
  549. std::vector<std::string> browser_result;
  550. EXPECT_TRUE(
  551. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  552. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  553. browser_result));
  554. EXPECT_EQ(browser_result.size(), 6U);
  555. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  556. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  557. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  558. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  559. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  560. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  561. // API client header
  562. std::vector<std::string> api_result;
  563. EXPECT_TRUE(detail::parse_accept_header(
  564. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  565. api_result));
  566. EXPECT_EQ(api_result.size(), 3U);
  567. EXPECT_EQ(api_result[0], "application/json");
  568. EXPECT_EQ(api_result[1], "application/xml");
  569. EXPECT_EQ(api_result[2], "text/plain");
  570. }
  571. TEST(ParseAcceptHeaderTest, SpecialCases) {
  572. // Quality value with 3 decimal places
  573. std::vector<std::string> decimal_result;
  574. EXPECT_TRUE(detail::parse_accept_header(
  575. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  576. EXPECT_EQ(decimal_result.size(), 2U);
  577. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  578. EXPECT_EQ(decimal_result[1], "text/html");
  579. // Zero quality (should still be included but with lowest priority)
  580. std::vector<std::string> zero_q_result;
  581. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  582. zero_q_result));
  583. EXPECT_EQ(zero_q_result.size(), 2U);
  584. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  585. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  586. // No spaces around commas
  587. std::vector<std::string> no_space_result;
  588. EXPECT_TRUE(detail::parse_accept_header(
  589. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  590. no_space_result));
  591. EXPECT_EQ(no_space_result.size(), 3U);
  592. EXPECT_EQ(no_space_result[0], "text/html");
  593. EXPECT_EQ(no_space_result[1], "application/json");
  594. EXPECT_EQ(no_space_result[2], "text/plain");
  595. }
  596. TEST(ParseAcceptHeaderTest, InvalidCases) {
  597. std::vector<std::string> result;
  598. // Invalid quality value (> 1.0)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  601. // Invalid quality value (< 0.0)
  602. EXPECT_FALSE(
  603. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  604. // Invalid quality value (not a number)
  605. EXPECT_FALSE(detail::parse_accept_header(
  606. "text/html;q=invalid,application/json", result));
  607. // Empty quality value
  608. EXPECT_FALSE(
  609. detail::parse_accept_header("text/html;q=,application/json", result));
  610. // Invalid media type format (no slash and not wildcard)
  611. EXPECT_FALSE(
  612. detail::parse_accept_header("invalidtype,application/json", result));
  613. // Empty media type
  614. result.clear();
  615. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  616. // Only commas
  617. result.clear();
  618. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  619. // Valid cases should still work
  620. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  621. EXPECT_EQ(result.size(), 1U);
  622. EXPECT_EQ(result[0], "*/*");
  623. EXPECT_TRUE(detail::parse_accept_header("*", result));
  624. EXPECT_EQ(result.size(), 1U);
  625. EXPECT_EQ(result[0], "*");
  626. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  627. EXPECT_EQ(result.size(), 1U);
  628. EXPECT_EQ(result[0], "text/*");
  629. }
  630. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  631. Server svr;
  632. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  633. EXPECT_EQ(req.accept_content_types.size(), 3U);
  634. EXPECT_EQ(req.accept_content_types[0], "application/json");
  635. EXPECT_EQ(req.accept_content_types[1], "text/html");
  636. EXPECT_EQ(req.accept_content_types[2], "*/*");
  637. res.set_content("ok", "text/plain");
  638. });
  639. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  640. EXPECT_TRUE(false);
  641. res.set_content("bad request", "text/plain");
  642. });
  643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  644. auto se = detail::scope_exit([&] {
  645. svr.stop();
  646. listen_thread.join();
  647. ASSERT_FALSE(svr.is_running());
  648. });
  649. svr.wait_until_ready();
  650. Client cli("localhost", PORT);
  651. {
  652. auto res =
  653. cli.Get("/accept_ok",
  654. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  655. ASSERT_TRUE(res);
  656. EXPECT_EQ(StatusCode::OK_200, res->status);
  657. }
  658. {
  659. auto res = cli.Get("/accept_bad_request",
  660. {{"Accept", "text/html;q=abc,application/json"}});
  661. ASSERT_TRUE(res);
  662. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  663. }
  664. }
  665. TEST(DivideTest, DivideStringTests) {
  666. auto divide = [](const std::string &str, char d) {
  667. std::string lhs;
  668. std::string rhs;
  669. detail::divide(str, d,
  670. [&](const char *lhs_data, std::size_t lhs_size,
  671. const char *rhs_data, std::size_t rhs_size) {
  672. lhs.assign(lhs_data, lhs_size);
  673. rhs.assign(rhs_data, rhs_size);
  674. });
  675. return std::make_pair(std::move(lhs), std::move(rhs));
  676. };
  677. {
  678. const auto res = divide("", '=');
  679. EXPECT_EQ(res.first, "");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "");
  686. }
  687. {
  688. const auto res = divide(" ", '=');
  689. EXPECT_EQ(res.first, " ");
  690. EXPECT_EQ(res.second, "");
  691. }
  692. {
  693. const auto res = divide("a", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "");
  696. }
  697. {
  698. const auto res = divide("a=", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "");
  701. }
  702. {
  703. const auto res = divide("=b", '=');
  704. EXPECT_EQ(res.first, "");
  705. EXPECT_EQ(res.second, "b");
  706. }
  707. {
  708. const auto res = divide("a=b", '=');
  709. EXPECT_EQ(res.first, "a");
  710. EXPECT_EQ(res.second, "b");
  711. }
  712. {
  713. const auto res = divide("a=b=", '=');
  714. EXPECT_EQ(res.first, "a");
  715. EXPECT_EQ(res.second, "b=");
  716. }
  717. {
  718. const auto res = divide("a=b=c", '=');
  719. EXPECT_EQ(res.first, "a");
  720. EXPECT_EQ(res.second, "b=c");
  721. }
  722. }
  723. TEST(SplitTest, ParseQueryString) {
  724. string s = "key1=val1&key2=val2&key3=val3";
  725. Params dic;
  726. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  727. [&](const char *b, const char *e) {
  728. string key, val;
  729. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  730. if (key.empty()) {
  731. key.assign(b2, e2);
  732. } else {
  733. val.assign(b2, e2);
  734. }
  735. });
  736. dic.emplace(key, val);
  737. });
  738. EXPECT_EQ("val1", dic.find("key1")->second);
  739. EXPECT_EQ("val2", dic.find("key2")->second);
  740. EXPECT_EQ("val3", dic.find("key3")->second);
  741. }
  742. TEST(SplitTest, ParseInvalidQueryTests) {
  743. {
  744. string s = " ";
  745. Params dict;
  746. detail::parse_query_text(s, dict);
  747. EXPECT_TRUE(dict.empty());
  748. }
  749. {
  750. string s = " = =";
  751. Params dict;
  752. detail::parse_query_text(s, dict);
  753. EXPECT_TRUE(dict.empty());
  754. }
  755. }
  756. TEST(ParseQueryTest, ParseQueryString) {
  757. {
  758. std::string s = "key1=val1&key2=val2&key3=val3";
  759. Params dic;
  760. detail::parse_query_text(s, dic);
  761. EXPECT_EQ("val1", dic.find("key1")->second);
  762. EXPECT_EQ("val2", dic.find("key2")->second);
  763. EXPECT_EQ("val3", dic.find("key3")->second);
  764. }
  765. {
  766. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  767. Params dic;
  768. detail::parse_query_text(s, dic);
  769. EXPECT_EQ("", dic.find("key1")->second);
  770. EXPECT_EQ("val1", dic.find("key2")->second);
  771. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  772. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  773. }
  774. }
  775. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  776. Params dic;
  777. EXPECT_EQ(detail::params_to_query_str(dic), "");
  778. dic.emplace("key1", "val1");
  779. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  780. dic.emplace("key2", "val2");
  781. dic.emplace("key3", "val3");
  782. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  783. }
  784. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  785. string content_type = "multipart/form-data; boundary=something";
  786. string boundary;
  787. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  788. EXPECT_TRUE(ret);
  789. EXPECT_EQ(boundary, "something");
  790. }
  791. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  792. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  793. string boundary;
  794. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  795. EXPECT_TRUE(ret);
  796. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  797. }
  798. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  799. string content_type =
  800. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  801. string boundary;
  802. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  803. EXPECT_TRUE(ret);
  804. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  805. }
  806. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  807. string content_type =
  808. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  809. string boundary;
  810. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  811. EXPECT_TRUE(ret);
  812. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  813. }
  814. TEST(GetHeaderValueTest, DefaultValue) {
  815. Headers headers = {{"Dummy", "Dummy"}};
  816. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  817. EXPECT_STREQ("text/plain", val);
  818. }
  819. TEST(GetHeaderValueTest, DefaultValueInt) {
  820. Headers headers = {{"Dummy", "Dummy"}};
  821. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  822. EXPECT_EQ(100ull, val);
  823. }
  824. TEST(GetHeaderValueTest, RegularValue) {
  825. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  826. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  827. EXPECT_STREQ("text/html", val);
  828. }
  829. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  830. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  831. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  832. EXPECT_STREQ("text/html", val);
  833. }
  834. TEST(GetHeaderValueTest, SetContent) {
  835. Response res;
  836. res.set_content("html", "text/html");
  837. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  838. res.set_content("text", "text/plain");
  839. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  840. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  841. }
  842. TEST(GetHeaderValueTest, RegularValueInt) {
  843. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  844. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  845. EXPECT_EQ(100ull, val);
  846. }
  847. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  848. Headers headers = {{"Content-Length", "x"}};
  849. auto is_invalid_value = false;
  850. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  851. is_invalid_value);
  852. EXPECT_EQ(0ull, val);
  853. EXPECT_TRUE(is_invalid_value);
  854. }
  855. TEST(GetHeaderValueTest, Range) {
  856. {
  857. Headers headers = {make_range_header({{1, -1}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=-1", val);
  865. }
  866. {
  867. Headers headers = {make_range_header({{1, 10}})};
  868. auto val = detail::get_header_value(headers, "Range", 0, 0);
  869. EXPECT_STREQ("bytes=1-10", val);
  870. }
  871. {
  872. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  873. auto val = detail::get_header_value(headers, "Range", 0, 0);
  874. EXPECT_STREQ("bytes=1-10, 100-", val);
  875. }
  876. {
  877. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  878. auto val = detail::get_header_value(headers, "Range", 0, 0);
  879. EXPECT_STREQ("bytes=1-10, 100-200", val);
  880. }
  881. {
  882. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  883. auto val = detail::get_header_value(headers, "Range", 0, 0);
  884. EXPECT_STREQ("bytes=0-0, -1", val);
  885. }
  886. }
  887. TEST(ParseHeaderValueTest, Range) {
  888. {
  889. Ranges ranges;
  890. auto ret = detail::parse_range_header("bytes=1-", ranges);
  891. EXPECT_TRUE(ret);
  892. EXPECT_EQ(1u, ranges.size());
  893. EXPECT_EQ(1u, ranges[0].first);
  894. EXPECT_EQ(-1, ranges[0].second);
  895. }
  896. {
  897. Ranges ranges;
  898. auto ret = detail::parse_range_header("bytes=-1", ranges);
  899. EXPECT_TRUE(ret);
  900. EXPECT_EQ(1u, ranges.size());
  901. EXPECT_EQ(-1, ranges[0].first);
  902. EXPECT_EQ(1u, ranges[0].second);
  903. }
  904. {
  905. Ranges ranges;
  906. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  907. EXPECT_TRUE(ret);
  908. EXPECT_EQ(1u, ranges.size());
  909. EXPECT_EQ(1u, ranges[0].first);
  910. EXPECT_EQ(10u, ranges[0].second);
  911. }
  912. {
  913. Ranges ranges;
  914. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  915. EXPECT_FALSE(ret);
  916. }
  917. {
  918. Ranges ranges;
  919. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  920. EXPECT_TRUE(ret);
  921. EXPECT_EQ(2u, ranges.size());
  922. EXPECT_EQ(1u, ranges[0].first);
  923. EXPECT_EQ(10u, ranges[0].second);
  924. EXPECT_EQ(100u, ranges[1].first);
  925. EXPECT_EQ(-1, ranges[1].second);
  926. }
  927. {
  928. Ranges ranges;
  929. auto ret =
  930. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  931. EXPECT_TRUE(ret);
  932. EXPECT_EQ(3u, ranges.size());
  933. EXPECT_EQ(1u, ranges[0].first);
  934. EXPECT_EQ(10u, ranges[0].second);
  935. EXPECT_EQ(100u, ranges[1].first);
  936. EXPECT_EQ(200u, ranges[1].second);
  937. EXPECT_EQ(300u, ranges[2].first);
  938. EXPECT_EQ(400u, ranges[2].second);
  939. }
  940. {
  941. Ranges ranges;
  942. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  943. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  944. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  945. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  946. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  947. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  948. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  949. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  950. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  951. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  952. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  953. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  954. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  955. EXPECT_TRUE(ranges.empty());
  956. }
  957. }
  958. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  966. #else
  967. EXPECT_TRUE(ret == detail::EncodingType::None);
  968. #endif
  969. }
  970. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  971. Request req;
  972. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  973. Response res;
  974. res.set_header("Content-Type", "text/plain");
  975. auto ret = detail::encoding_type(req, res);
  976. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  978. #elif CPPHTTPLIB_ZLIB_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  980. #elif CPPHTTPLIB_ZSTD_SUPPORT
  981. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  982. #else
  983. EXPECT_TRUE(ret == detail::EncodingType::None);
  984. #endif
  985. }
  986. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  987. Request req;
  988. req.set_header("Accept-Encoding",
  989. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  990. Response res;
  991. res.set_header("Content-Type", "text/plain");
  992. auto ret = detail::encoding_type(req, res);
  993. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  994. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  995. #elif CPPHTTPLIB_ZLIB_SUPPORT
  996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  997. #elif CPPHTTPLIB_ZSTD_SUPPORT
  998. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  999. #else
  1000. EXPECT_TRUE(ret == detail::EncodingType::None);
  1001. #endif
  1002. }
  1003. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1004. // All supported encodings rejected with q=0 should return None
  1005. Request req;
  1006. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1007. Response res;
  1008. res.set_header("Content-Type", "text/plain");
  1009. auto ret = detail::encoding_type(req, res);
  1010. EXPECT_TRUE(ret == detail::EncodingType::None);
  1011. }
  1012. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1013. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1014. Request req;
  1015. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1016. Response res;
  1017. res.set_header("Content-Type", "text/plain");
  1018. auto ret = detail::encoding_type(req, res);
  1019. EXPECT_TRUE(ret == detail::EncodingType::None);
  1020. }
  1021. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1022. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1023. Request req;
  1024. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1025. Response res;
  1026. res.set_header("Content-Type", "text/plain");
  1027. auto ret = detail::encoding_type(req, res);
  1028. EXPECT_TRUE(ret == detail::EncodingType::None);
  1029. }
  1030. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1031. // RFC 7231: Accept-Encoding values are case-insensitive
  1032. Request req;
  1033. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1034. Response res;
  1035. res.set_header("Content-Type", "text/plain");
  1036. auto ret = detail::encoding_type(req, res);
  1037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1043. #else
  1044. EXPECT_TRUE(ret == detail::EncodingType::None);
  1045. #endif
  1046. }
  1047. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1048. // q value should determine priority, not hardcoded order
  1049. Request req;
  1050. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1051. Response res;
  1052. res.set_header("Content-Type", "text/plain");
  1053. auto ret = detail::encoding_type(req, res);
  1054. // gzip has highest q=1.0, so it should be selected even though
  1055. // br and zstd are also supported
  1056. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1060. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1062. #else
  1063. EXPECT_TRUE(ret == detail::EncodingType::None);
  1064. #endif
  1065. }
  1066. TEST(BufferStreamTest, read) {
  1067. detail::BufferStream strm1;
  1068. Stream &strm = strm1;
  1069. EXPECT_EQ(5, strm.write("hello"));
  1070. char buf[512];
  1071. EXPECT_EQ(2, strm.read(buf, 2));
  1072. EXPECT_EQ('h', buf[0]);
  1073. EXPECT_EQ('e', buf[1]);
  1074. EXPECT_EQ(2, strm.read(buf, 2));
  1075. EXPECT_EQ('l', buf[0]);
  1076. EXPECT_EQ('l', buf[1]);
  1077. EXPECT_EQ(1, strm.read(buf, 1));
  1078. EXPECT_EQ('o', buf[0]);
  1079. EXPECT_EQ(0, strm.read(buf, 1));
  1080. }
  1081. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1082. auto host = "www.httpwatch.com";
  1083. auto ip = hosted_at(host);
  1084. EXPECT_EQ("23.96.13.243", ip);
  1085. std::vector<std::string> addrs;
  1086. hosted_at(host, addrs);
  1087. EXPECT_EQ(1u, addrs.size());
  1088. }
  1089. #if 0 // It depends on each test environment...
  1090. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1091. auto host = "www.youtube.com";
  1092. std::vector<std::string> addrs;
  1093. hosted_at(host, addrs);
  1094. EXPECT_EQ(20u, addrs.size());
  1095. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1096. EXPECT_TRUE(it != addrs.end());
  1097. }
  1098. #endif
  1099. class ChunkedEncodingTest : public ::testing::Test {
  1100. protected:
  1101. ChunkedEncodingTest()
  1102. : cli_(HOST, PORT)
  1103. #ifdef CPPHTTPLIB_SSL_ENABLED
  1104. ,
  1105. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1106. #endif
  1107. {
  1108. cli_.set_connection_timeout(2);
  1109. #ifdef CPPHTTPLIB_SSL_ENABLED
  1110. cli_.enable_server_certificate_verification(false);
  1111. #endif
  1112. }
  1113. virtual void SetUp() {
  1114. read_file("./image.jpg", image_data_);
  1115. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. svr_.Get(
  1119. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1120. res.set_chunked_content_provider(
  1121. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1122. size_t remaining = image_data_.size() - offset;
  1123. if (remaining == 0) {
  1124. sink.done();
  1125. } else {
  1126. constexpr size_t CHUNK_SIZE = 1024;
  1127. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1128. sink.write(&image_data_[offset], send_size);
  1129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1130. }
  1131. return true;
  1132. });
  1133. });
  1134. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1135. svr_.wait_until_ready();
  1136. }
  1137. virtual void TearDown() {
  1138. svr_.stop();
  1139. if (!request_threads_.empty()) {
  1140. std::this_thread::sleep_for(std::chrono::seconds(1));
  1141. for (auto &t : request_threads_) {
  1142. t.join();
  1143. }
  1144. }
  1145. t_.join();
  1146. }
  1147. #ifdef CPPHTTPLIB_SSL_ENABLED
  1148. SSLClient cli_;
  1149. SSLServer svr_;
  1150. #else
  1151. Client cli_;
  1152. Server svr_;
  1153. #endif
  1154. thread t_;
  1155. std::vector<thread> request_threads_;
  1156. std::string image_data_;
  1157. };
  1158. TEST_F(ChunkedEncodingTest, NormalGet) {
  1159. auto res = cli_.Get("/chunked");
  1160. ASSERT_TRUE(res);
  1161. std::string out;
  1162. read_file("./image.jpg", out);
  1163. EXPECT_EQ(StatusCode::OK_200, res->status);
  1164. EXPECT_EQ(out, res->body);
  1165. }
  1166. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1167. std::string body;
  1168. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1169. body.append(data, data_length);
  1170. return true;
  1171. });
  1172. ASSERT_TRUE(res);
  1173. std::string out;
  1174. read_file("./image.jpg", out);
  1175. EXPECT_EQ(StatusCode::OK_200, res->status);
  1176. EXPECT_EQ(out, body);
  1177. }
  1178. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1179. std::string body;
  1180. auto res = cli_.Get(
  1181. "/chunked",
  1182. [&](const Response &response) {
  1183. EXPECT_EQ(StatusCode::OK_200, response.status);
  1184. return true;
  1185. },
  1186. [&](const char *data, size_t data_length) {
  1187. body.append(data, data_length);
  1188. return true;
  1189. });
  1190. ASSERT_TRUE(res);
  1191. std::string out;
  1192. read_file("./image.jpg", out);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. EXPECT_EQ(out, body);
  1195. }
  1196. TEST(RangeTest, FromHTTPBin_Online) {
  1197. auto host = "httpbingo.org";
  1198. auto path = std::string{"/range/32"};
  1199. #ifdef CPPHTTPLIB_SSL_ENABLED
  1200. auto port = 443;
  1201. SSLClient cli(host, port);
  1202. #else
  1203. auto port = 80;
  1204. Client cli(host, port);
  1205. #endif
  1206. cli.set_connection_timeout(5);
  1207. {
  1208. auto res = cli.Get(path);
  1209. ASSERT_TRUE(res);
  1210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1211. EXPECT_EQ(StatusCode::OK_200, res->status);
  1212. }
  1213. {
  1214. Headers headers = {make_range_header({{1, -1}})};
  1215. auto res = cli.Get(path, headers);
  1216. ASSERT_TRUE(res);
  1217. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1219. }
  1220. {
  1221. Headers headers = {make_range_header({{1, 10}})};
  1222. auto res = cli.Get(path, headers);
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("bcdefghijk", res->body);
  1225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1226. }
  1227. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1228. // entire resource, while the original httpbin returned 200. Both are
  1229. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1230. {
  1231. Headers headers = {make_range_header({{0, 31}})};
  1232. auto res = cli.Get(path, headers);
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1235. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1236. res->status == StatusCode::PartialContent_206);
  1237. }
  1238. {
  1239. Headers headers = {make_range_header({{0, -1}})};
  1240. auto res = cli.Get(path, headers);
  1241. ASSERT_TRUE(res);
  1242. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1243. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  1244. res->status == StatusCode::PartialContent_206);
  1245. }
  1246. // go-httpbin returns 206 with clamped range for over-range requests,
  1247. // while the original httpbin returned 416. Both behaviors are observed
  1248. // in real servers, so we only verify the request succeeds.
  1249. {
  1250. Headers headers = {make_range_header({{0, 32}})};
  1251. auto res = cli.Get(path, headers);
  1252. ASSERT_TRUE(res);
  1253. }
  1254. }
  1255. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1256. auto host = "unresolvableaddress.local";
  1257. auto path = std::string{"/"};
  1258. #ifdef CPPHTTPLIB_SSL_ENABLED
  1259. auto port = 443;
  1260. SSLClient cli(host, port);
  1261. #else
  1262. auto port = 80;
  1263. Client cli(host, port);
  1264. #endif
  1265. cli.set_connection_timeout(1);
  1266. {
  1267. auto res = cli.Get(path);
  1268. ASSERT_FALSE(res);
  1269. }
  1270. std::this_thread::sleep_for(std::chrono::seconds(8));
  1271. }
  1272. TEST(ConnectionErrorTest, InvalidHost) {
  1273. auto host = "-abcde.com";
  1274. #ifdef CPPHTTPLIB_SSL_ENABLED
  1275. auto port = 443;
  1276. SSLClient cli(host, port);
  1277. #else
  1278. auto port = 80;
  1279. Client cli(host, port);
  1280. #endif
  1281. cli.set_connection_timeout(std::chrono::seconds(2));
  1282. auto res = cli.Get("/");
  1283. ASSERT_TRUE(!res);
  1284. EXPECT_EQ(Error::Connection, res.error());
  1285. }
  1286. TEST(ConnectionErrorTest, InvalidHost2) {
  1287. auto host = "httpcan.org/";
  1288. #ifdef CPPHTTPLIB_SSL_ENABLED
  1289. SSLClient cli(host);
  1290. #else
  1291. Client cli(host);
  1292. #endif
  1293. cli.set_connection_timeout(std::chrono::seconds(2));
  1294. auto res = cli.Get("/");
  1295. ASSERT_TRUE(!res);
  1296. EXPECT_EQ(Error::Connection, res.error());
  1297. }
  1298. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1299. auto host = "httpcan.org/";
  1300. #ifdef CPPHTTPLIB_SSL_ENABLED
  1301. SSLClient cli(host);
  1302. #else
  1303. Client cli(host);
  1304. #endif
  1305. cli.set_connection_timeout(std::chrono::seconds(2));
  1306. auto res = cli.Get("/");
  1307. ASSERT_TRUE(!res);
  1308. stringstream s;
  1309. s << "error code: " << res.error();
  1310. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1311. }
  1312. TEST(ConnectionErrorTest, InvalidPort) {
  1313. auto host = "localhost";
  1314. auto port = 44380;
  1315. #ifdef CPPHTTPLIB_SSL_ENABLED
  1316. SSLClient cli(host, port);
  1317. #else
  1318. Client cli(host, port);
  1319. #endif
  1320. cli.set_connection_timeout(std::chrono::seconds(2));
  1321. auto res = cli.Get("/");
  1322. ASSERT_TRUE(!res);
  1323. EXPECT_TRUE(Error::Connection == res.error() ||
  1324. Error::ConnectionTimeout == res.error());
  1325. }
  1326. TEST(ConnectionErrorTest, Timeout_Online) {
  1327. auto host = "google.com";
  1328. #ifdef CPPHTTPLIB_SSL_ENABLED
  1329. auto port = 44380;
  1330. SSLClient cli(host, port);
  1331. #else
  1332. auto port = 8080;
  1333. Client cli(host, port);
  1334. #endif
  1335. cli.set_connection_timeout(std::chrono::seconds(2));
  1336. // only probe one address type so that the error reason
  1337. // correlates to the timed-out IPv4, not the unsupported
  1338. // IPv6 connection attempt
  1339. cli.set_address_family(AF_INET);
  1340. auto res = cli.Get("/");
  1341. ASSERT_TRUE(!res);
  1342. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1343. }
  1344. TEST(CancelTest, NoCancel_Online) {
  1345. auto host = "httpbingo.org";
  1346. auto path = std::string{"/range/32"};
  1347. #ifdef CPPHTTPLIB_SSL_ENABLED
  1348. auto port = 443;
  1349. SSLClient cli(host, port);
  1350. #else
  1351. auto port = 80;
  1352. Client cli(host, port);
  1353. #endif
  1354. cli.set_connection_timeout(std::chrono::seconds(5));
  1355. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1356. ASSERT_TRUE(res);
  1357. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1358. EXPECT_EQ(StatusCode::OK_200, res->status);
  1359. }
  1360. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1361. // Use /bytes with a large payload so that the DownloadProgress callback
  1362. // (which only fires for Content-Length responses) is invoked before the
  1363. // entire body is received, giving cancellation a chance to fire.
  1364. auto host = "httpbingo.org";
  1365. auto path = std::string{"/bytes/524288"};
  1366. #ifdef CPPHTTPLIB_SSL_ENABLED
  1367. auto port = 443;
  1368. SSLClient cli(host, port);
  1369. #else
  1370. auto port = 80;
  1371. Client cli(host, port);
  1372. #endif
  1373. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1374. cli.set_connection_timeout(std::chrono::seconds(5));
  1375. ASSERT_TRUE(!res);
  1376. EXPECT_EQ(Error::Canceled, res.error());
  1377. }
  1378. TEST(CancelTest, WithCancelLargePayload_Online) {
  1379. auto host = "httpbingo.org";
  1380. auto path = std::string{"/bytes/524288"};
  1381. #ifdef CPPHTTPLIB_SSL_ENABLED
  1382. auto port = 443;
  1383. SSLClient cli(host, port);
  1384. #else
  1385. auto port = 80;
  1386. Client cli(host, port);
  1387. #endif
  1388. cli.set_connection_timeout(std::chrono::seconds(5));
  1389. uint32_t count = 0;
  1390. auto res =
  1391. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1392. ASSERT_TRUE(!res);
  1393. EXPECT_EQ(Error::Canceled, res.error());
  1394. }
  1395. TEST(CancelTest, NoCancelPost) {
  1396. Server svr;
  1397. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1398. res.set_content("Hello World!", "text/plain");
  1399. });
  1400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1401. auto se = detail::scope_exit([&] {
  1402. svr.stop();
  1403. thread.join();
  1404. ASSERT_FALSE(svr.is_running());
  1405. });
  1406. svr.wait_until_ready();
  1407. Client cli(HOST, PORT);
  1408. cli.set_connection_timeout(std::chrono::seconds(5));
  1409. auto res =
  1410. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1411. "application/json", [](uint64_t, uint64_t) { return true; });
  1412. ASSERT_TRUE(res);
  1413. EXPECT_EQ("Hello World!", res->body);
  1414. EXPECT_EQ(StatusCode::OK_200, res->status);
  1415. }
  1416. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1417. Server svr;
  1418. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1419. res.set_content("Hello World!", "text/plain");
  1420. });
  1421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1422. auto se = detail::scope_exit([&] {
  1423. svr.stop();
  1424. thread.join();
  1425. ASSERT_FALSE(svr.is_running());
  1426. });
  1427. svr.wait_until_ready();
  1428. Client cli(HOST, PORT);
  1429. cli.set_connection_timeout(std::chrono::seconds(5));
  1430. auto res =
  1431. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1432. "application/json", [](uint64_t, uint64_t) { return false; });
  1433. ASSERT_TRUE(!res);
  1434. EXPECT_EQ(Error::Canceled, res.error());
  1435. }
  1436. TEST(CancelTest, WithCancelLargePayloadPost) {
  1437. Server svr;
  1438. svr.set_payload_max_length(200 * 1024 * 1024);
  1439. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1440. res.set_content(LARGE_DATA, "text/plain");
  1441. });
  1442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. thread.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. svr.wait_until_ready();
  1449. Client cli(HOST, PORT);
  1450. cli.set_payload_max_length(200 * 1024 * 1024);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, NoCancelPut) {
  1459. Server svr;
  1460. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content("Hello World!", "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return true; });
  1475. ASSERT_TRUE(res);
  1476. EXPECT_EQ("Hello World!", res->body);
  1477. EXPECT_EQ(StatusCode::OK_200, res->status);
  1478. }
  1479. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1480. Server svr;
  1481. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1482. res.set_content("Hello World!", "text/plain");
  1483. });
  1484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1485. auto se = detail::scope_exit([&] {
  1486. svr.stop();
  1487. thread.join();
  1488. ASSERT_FALSE(svr.is_running());
  1489. });
  1490. svr.wait_until_ready();
  1491. Client cli(HOST, PORT);
  1492. cli.set_connection_timeout(std::chrono::seconds(5));
  1493. auto res =
  1494. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1495. "application/json", [](uint64_t, uint64_t) { return false; });
  1496. ASSERT_TRUE(!res);
  1497. EXPECT_EQ(Error::Canceled, res.error());
  1498. }
  1499. TEST(CancelTest, WithCancelLargePayloadPut) {
  1500. Server svr;
  1501. svr.set_payload_max_length(200 * 1024 * 1024);
  1502. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1503. res.set_content(LARGE_DATA, "text/plain");
  1504. });
  1505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1506. auto se = detail::scope_exit([&] {
  1507. svr.stop();
  1508. thread.join();
  1509. ASSERT_FALSE(svr.is_running());
  1510. });
  1511. svr.wait_until_ready();
  1512. Client cli(HOST, PORT);
  1513. cli.set_payload_max_length(200 * 1024 * 1024);
  1514. cli.set_connection_timeout(std::chrono::seconds(5));
  1515. auto res =
  1516. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1517. "application/json", [](uint64_t, uint64_t) { return false; });
  1518. ASSERT_TRUE(!res);
  1519. EXPECT_EQ(Error::Canceled, res.error());
  1520. }
  1521. TEST(CancelTest, NoCancelPatch) {
  1522. Server svr;
  1523. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1524. res.set_content("Hello World!", "text/plain");
  1525. });
  1526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1527. auto se = detail::scope_exit([&] {
  1528. svr.stop();
  1529. thread.join();
  1530. ASSERT_FALSE(svr.is_running());
  1531. });
  1532. svr.wait_until_ready();
  1533. Client cli(HOST, PORT);
  1534. cli.set_connection_timeout(std::chrono::seconds(5));
  1535. auto res =
  1536. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1537. "application/json", [](uint64_t, uint64_t) { return true; });
  1538. ASSERT_TRUE(res);
  1539. EXPECT_EQ("Hello World!", res->body);
  1540. EXPECT_EQ(StatusCode::OK_200, res->status);
  1541. }
  1542. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1543. Server svr;
  1544. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1545. res.set_content("Hello World!", "text/plain");
  1546. });
  1547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1548. auto se = detail::scope_exit([&] {
  1549. svr.stop();
  1550. thread.join();
  1551. ASSERT_FALSE(svr.is_running());
  1552. });
  1553. svr.wait_until_ready();
  1554. Client cli(HOST, PORT);
  1555. cli.set_connection_timeout(std::chrono::seconds(5));
  1556. auto res =
  1557. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1558. "application/json", [](uint64_t, uint64_t) { return false; });
  1559. ASSERT_TRUE(!res);
  1560. EXPECT_EQ(Error::Canceled, res.error());
  1561. }
  1562. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1563. Server svr;
  1564. svr.set_payload_max_length(200 * 1024 * 1024);
  1565. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1566. res.set_content(LARGE_DATA, "text/plain");
  1567. });
  1568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. thread.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. Client cli(HOST, PORT);
  1576. cli.set_payload_max_length(200 * 1024 * 1024);
  1577. cli.set_connection_timeout(std::chrono::seconds(5));
  1578. auto res =
  1579. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1580. "application/json", [](uint64_t, uint64_t) { return false; });
  1581. ASSERT_TRUE(!res);
  1582. EXPECT_EQ(Error::Canceled, res.error());
  1583. }
  1584. TEST(CancelTest, NoCancelDelete) {
  1585. Server svr;
  1586. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1587. res.set_content("Hello World!", "text/plain");
  1588. });
  1589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1590. auto se = detail::scope_exit([&] {
  1591. svr.stop();
  1592. thread.join();
  1593. ASSERT_FALSE(svr.is_running());
  1594. });
  1595. svr.wait_until_ready();
  1596. Client cli(HOST, PORT);
  1597. cli.set_connection_timeout(std::chrono::seconds(5));
  1598. auto res =
  1599. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1600. "application/json", [](uint64_t, uint64_t) { return true; });
  1601. ASSERT_TRUE(res);
  1602. EXPECT_EQ("Hello World!", res->body);
  1603. EXPECT_EQ(StatusCode::OK_200, res->status);
  1604. }
  1605. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1606. Server svr;
  1607. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. thread.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. Client cli(HOST, PORT);
  1618. cli.set_connection_timeout(std::chrono::seconds(5));
  1619. auto res =
  1620. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1621. "application/json", [](uint64_t, uint64_t) { return false; });
  1622. ASSERT_TRUE(!res);
  1623. EXPECT_EQ(Error::Canceled, res.error());
  1624. }
  1625. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1626. Server svr;
  1627. svr.set_payload_max_length(200 * 1024 * 1024);
  1628. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1629. res.set_content(LARGE_DATA, "text/plain");
  1630. });
  1631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. thread.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. Client cli(HOST, PORT);
  1639. cli.set_payload_max_length(200 * 1024 * 1024);
  1640. cli.set_connection_timeout(std::chrono::seconds(5));
  1641. auto res =
  1642. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1643. "application/json", [](uint64_t, uint64_t) { return false; });
  1644. ASSERT_TRUE(!res);
  1645. EXPECT_EQ(Error::Canceled, res.error());
  1646. }
  1647. static std::string remove_whitespace(const std::string &input) {
  1648. std::string output;
  1649. output.reserve(input.size());
  1650. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1651. [](unsigned char c) { return !std::isspace(c); });
  1652. return output;
  1653. }
  1654. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1655. auto host = "httpbingo.org";
  1656. auto path = std::string{"/basic-auth/hello/world"};
  1657. #ifdef CPPHTTPLIB_SSL_ENABLED
  1658. auto port = 443;
  1659. SSLClient cli(host, port);
  1660. #else
  1661. auto port = 80;
  1662. Client cli(host, port);
  1663. #endif
  1664. {
  1665. auto res = cli.Get(path);
  1666. ASSERT_TRUE(res);
  1667. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1668. }
  1669. {
  1670. auto res =
  1671. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1672. ASSERT_TRUE(res);
  1673. auto body = remove_whitespace(res->body);
  1674. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1675. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1676. EXPECT_EQ(StatusCode::OK_200, res->status);
  1677. }
  1678. {
  1679. cli.set_basic_auth("hello", "world");
  1680. auto res = cli.Get(path);
  1681. ASSERT_TRUE(res);
  1682. auto body = remove_whitespace(res->body);
  1683. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1684. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1685. EXPECT_EQ(StatusCode::OK_200, res->status);
  1686. }
  1687. {
  1688. cli.set_basic_auth("hello", "bad");
  1689. auto res = cli.Get(path);
  1690. ASSERT_TRUE(res);
  1691. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1692. }
  1693. {
  1694. cli.set_basic_auth("bad", "world");
  1695. auto res = cli.Get(path);
  1696. ASSERT_TRUE(res);
  1697. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1698. }
  1699. }
  1700. #ifdef CPPHTTPLIB_SSL_ENABLED
  1701. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1702. auto host = "httpbingo.org";
  1703. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1704. auto paths = std::vector<std::string>{
  1705. "/digest-auth/auth/hello/world/MD5",
  1706. "/digest-auth/auth/hello/world/SHA-256",
  1707. };
  1708. auto port = 443;
  1709. SSLClient cli(host, port);
  1710. {
  1711. auto res = cli.Get(unauth_path);
  1712. ASSERT_TRUE(res);
  1713. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1714. }
  1715. {
  1716. cli.set_digest_auth("hello", "world");
  1717. for (const auto &path : paths) {
  1718. auto res = cli.Get(path.c_str());
  1719. ASSERT_TRUE(res);
  1720. auto body = remove_whitespace(res->body);
  1721. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  1722. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  1723. EXPECT_EQ(StatusCode::OK_200, res->status);
  1724. }
  1725. cli.set_digest_auth("hello", "bad");
  1726. for (const auto &path : paths) {
  1727. auto res = cli.Get(path.c_str());
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1730. }
  1731. }
  1732. }
  1733. #endif
  1734. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1735. auto host = "google.com";
  1736. auto another_host = "example.com";
  1737. auto wrong_ip = "0.0.0.0";
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1744. auto res = cli.Get("/");
  1745. ASSERT_TRUE(res);
  1746. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1747. }
  1748. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1749. auto host = "google.com";
  1750. auto wrong_ip = "0.0.0.0";
  1751. #ifdef CPPHTTPLIB_SSL_ENABLED
  1752. SSLClient cli(host);
  1753. #else
  1754. Client cli(host);
  1755. #endif
  1756. cli.set_hostname_addr_map({{host, wrong_ip}});
  1757. auto res = cli.Get("/");
  1758. ASSERT_TRUE(!res);
  1759. EXPECT_EQ(Error::Connection, res.error());
  1760. }
  1761. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1762. auto host = "httpbingo.org";
  1763. auto path = std::string{"/absolute-redirect/3"};
  1764. #ifdef CPPHTTPLIB_SSL_ENABLED
  1765. SSLClient cli(host);
  1766. #else
  1767. Client cli(host);
  1768. #endif
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get(path);
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. }
  1774. TEST(RedirectTest, Redirect_Online) {
  1775. auto host = "httpbingo.org";
  1776. auto path = std::string{"/redirect/3"};
  1777. #ifdef CPPHTTPLIB_SSL_ENABLED
  1778. SSLClient cli(host);
  1779. #else
  1780. Client cli(host);
  1781. #endif
  1782. cli.set_follow_location(true);
  1783. auto res = cli.Get(path);
  1784. ASSERT_TRUE(res);
  1785. EXPECT_EQ(StatusCode::OK_200, res->status);
  1786. }
  1787. TEST(RelativeRedirectTest, Redirect_Online) {
  1788. auto host = "httpbingo.org";
  1789. auto path = std::string{"/relative-redirect/3"};
  1790. #ifdef CPPHTTPLIB_SSL_ENABLED
  1791. SSLClient cli(host);
  1792. #else
  1793. Client cli(host);
  1794. #endif
  1795. cli.set_follow_location(true);
  1796. auto res = cli.Get(path);
  1797. ASSERT_TRUE(res);
  1798. EXPECT_EQ(StatusCode::OK_200, res->status);
  1799. }
  1800. TEST(TooManyRedirectTest, Redirect_Online) {
  1801. auto host = "httpbingo.org";
  1802. auto path = std::string{"/redirect/21"};
  1803. #ifdef CPPHTTPLIB_SSL_ENABLED
  1804. SSLClient cli(host);
  1805. #else
  1806. Client cli(host);
  1807. #endif
  1808. cli.set_follow_location(true);
  1809. auto res = cli.Get(path);
  1810. ASSERT_TRUE(!res);
  1811. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1812. }
  1813. #ifdef CPPHTTPLIB_SSL_ENABLED
  1814. TEST(YahooRedirectTest, Redirect_Online) {
  1815. Client cli("yahoo.com");
  1816. auto res = cli.Get("/");
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1819. cli.set_follow_location(true);
  1820. res = cli.Get("/");
  1821. ASSERT_TRUE(res);
  1822. EXPECT_EQ(StatusCode::OK_200, res->status);
  1823. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1824. }
  1825. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1826. #define REDIR_HOST "httpbingo.org"
  1827. #define REDIR_PATH "/redirect-to"
  1828. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1829. SSLClient cli(REDIR_HOST);
  1830. cli.set_follow_location(true);
  1831. auto res =
  1832. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1833. ASSERT_TRUE(res);
  1834. EXPECT_EQ(StatusCode::OK_200, res->status);
  1835. }
  1836. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1837. SSLClient cli(REDIR_HOST);
  1838. cli.set_follow_location(true);
  1839. Params params;
  1840. params.emplace("url", "http://example.com");
  1841. params.emplace("status_code", "302");
  1842. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1843. ASSERT_TRUE(res);
  1844. EXPECT_EQ(StatusCode::OK_200, res->status);
  1845. }
  1846. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1847. SSLClient cli(REDIR_HOST);
  1848. cli.set_follow_location(true);
  1849. Params params;
  1850. params.emplace("url", "http://example.com");
  1851. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. }
  1855. TEST(UrlWithSpace, Redirect_Online) {
  1856. SSLClient cli("edge.forgecdn.net");
  1857. cli.set_follow_location(true);
  1858. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1859. ASSERT_TRUE(res);
  1860. EXPECT_EQ(StatusCode::OK_200, res->status);
  1861. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1862. }
  1863. #endif
  1864. #if !defined(_WIN32) && !defined(_WIN64)
  1865. TEST(ReceiveSignals, Signal) {
  1866. auto setupSignalHandlers = []() {
  1867. struct sigaction act;
  1868. sigemptyset(&act.sa_mask);
  1869. act.sa_flags = SA_SIGINFO;
  1870. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1871. switch (sig) {
  1872. case SIGINT:
  1873. default: break;
  1874. }
  1875. };
  1876. ::sigaction(SIGINT, &act, nullptr);
  1877. };
  1878. Server svr;
  1879. int port = 0;
  1880. auto thread = std::thread([&]() {
  1881. setupSignalHandlers();
  1882. port = svr.bind_to_any_port(HOST);
  1883. svr.listen_after_bind();
  1884. });
  1885. auto se = detail::scope_exit([&] {
  1886. svr.stop();
  1887. thread.join();
  1888. ASSERT_FALSE(svr.is_running());
  1889. });
  1890. svr.wait_until_ready();
  1891. ASSERT_TRUE(svr.is_running());
  1892. pthread_kill(thread.native_handle(), SIGINT);
  1893. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1894. ASSERT_TRUE(svr.is_running());
  1895. }
  1896. #endif
  1897. TEST(RedirectToDifferentPort, Redirect) {
  1898. Server svr1;
  1899. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1900. res.set_content("Hello World!", "text/plain");
  1901. });
  1902. int svr1_port = 0;
  1903. auto thread1 = std::thread([&]() {
  1904. svr1_port = svr1.bind_to_any_port(HOST);
  1905. svr1.listen_after_bind();
  1906. });
  1907. Server svr2;
  1908. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1909. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1910. });
  1911. int svr2_port = 0;
  1912. auto thread2 = std::thread([&]() {
  1913. svr2_port = svr2.bind_to_any_port(HOST);
  1914. svr2.listen_after_bind();
  1915. });
  1916. auto se = detail::scope_exit([&] {
  1917. svr2.stop();
  1918. thread2.join();
  1919. svr1.stop();
  1920. thread1.join();
  1921. ASSERT_FALSE(svr2.is_running());
  1922. ASSERT_FALSE(svr1.is_running());
  1923. });
  1924. svr1.wait_until_ready();
  1925. svr2.wait_until_ready();
  1926. Client cli("localhost", svr2_port);
  1927. cli.set_follow_location(true);
  1928. auto res = cli.Get("/2");
  1929. ASSERT_TRUE(res);
  1930. EXPECT_EQ(StatusCode::OK_200, res->status);
  1931. EXPECT_EQ("Hello World!", res->body);
  1932. }
  1933. static void
  1934. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  1935. Server svr1;
  1936. std::string captured_authorization;
  1937. svr1.Get("/target", [&](const Request &req, Response &res) {
  1938. captured_authorization = req.get_header_value("Authorization");
  1939. res.set_content("OK", "text/plain");
  1940. });
  1941. int svr1_port = 0;
  1942. auto thread1 = std::thread([&]() {
  1943. svr1_port = svr1.bind_to_any_port(HOST);
  1944. svr1.listen_after_bind();
  1945. });
  1946. Server svr2;
  1947. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1948. res.set_redirect(
  1949. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  1950. });
  1951. int svr2_port = 0;
  1952. auto thread2 = std::thread([&]() {
  1953. svr2_port = svr2.bind_to_any_port(HOST);
  1954. svr2.listen_after_bind();
  1955. });
  1956. auto se = detail::scope_exit([&] {
  1957. svr2.stop();
  1958. thread2.join();
  1959. svr1.stop();
  1960. thread1.join();
  1961. ASSERT_FALSE(svr2.is_running());
  1962. ASSERT_FALSE(svr1.is_running());
  1963. });
  1964. svr1.wait_until_ready();
  1965. svr2.wait_until_ready();
  1966. Client cli("localhost", svr2_port);
  1967. cli.set_follow_location(true);
  1968. set_auth(cli);
  1969. auto res = cli.Get("/redir");
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(StatusCode::OK_200, res->status);
  1972. // RFC 9110: credentials MUST NOT be forwarded to a different host
  1973. EXPECT_TRUE(captured_authorization.empty());
  1974. }
  1975. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  1976. TestDoNotForwardCredentialsOnRedirect(
  1977. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  1978. }
  1979. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  1980. TestDoNotForwardCredentialsOnRedirect(
  1981. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  1982. }
  1983. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  1984. Server svr;
  1985. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  1986. // Port number that overflows int — should not crash
  1987. res.set_redirect("http://localhost:99999999999999999999/target");
  1988. });
  1989. auto port = svr.bind_to_any_port(HOST);
  1990. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  1991. auto se = detail::scope_exit([&] {
  1992. svr.stop();
  1993. thread.join();
  1994. ASSERT_FALSE(svr.is_running());
  1995. });
  1996. svr.wait_until_ready();
  1997. Client cli(HOST, port);
  1998. cli.set_follow_location(true);
  1999. auto res = cli.Get("/redir");
  2000. // Should fail gracefully, not crash (no valid response due to bad port)
  2001. EXPECT_FALSE(res);
  2002. }
  2003. TEST(RedirectFromPageWithContent, Redirect) {
  2004. Server svr;
  2005. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2006. res.set_content("___", "text/plain");
  2007. res.set_redirect("/2");
  2008. });
  2009. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  2010. res.set_content("Hello World!", "text/plain");
  2011. });
  2012. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. th.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. svr.wait_until_ready();
  2019. {
  2020. Client cli("localhost", PORT);
  2021. cli.set_follow_location(true);
  2022. std::string body;
  2023. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2024. body.append(data, data_length);
  2025. return true;
  2026. });
  2027. ASSERT_TRUE(res);
  2028. EXPECT_EQ(StatusCode::OK_200, res->status);
  2029. EXPECT_EQ("Hello World!", body);
  2030. }
  2031. {
  2032. Client cli("localhost", PORT);
  2033. std::string body;
  2034. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2035. body.append(data, data_length);
  2036. return true;
  2037. });
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::Found_302, res->status);
  2040. EXPECT_EQ("___", body);
  2041. }
  2042. }
  2043. TEST(RedirectFromPageWithContentIP6, Redirect) {
  2044. Server svr;
  2045. auto port_str = std::to_string(PORT);
  2046. auto redirect_url = "http://[::1]:" + port_str + "/2";
  2047. auto expected_host = "[::1]:" + port_str;
  2048. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2049. res.set_content("___", "text/plain");
  2050. // res.set_redirect("/2");
  2051. res.set_redirect(redirect_url);
  2052. });
  2053. svr.Get("/2", [&](const Request &req, Response &res) {
  2054. auto host_header = req.headers.find("Host");
  2055. ASSERT_TRUE(host_header != req.headers.end());
  2056. EXPECT_EQ(expected_host, host_header->second);
  2057. res.set_content("Hello World!", "text/plain");
  2058. });
  2059. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  2060. auto se = detail::scope_exit([&] {
  2061. svr.stop();
  2062. th.join();
  2063. ASSERT_FALSE(svr.is_running());
  2064. });
  2065. // When IPV6 support isn't available svr.listen("::1", PORT) never
  2066. // actually starts anything, so the condition !svr.is_running() will
  2067. // always remain true, and the loop never stops.
  2068. // This basically counts how many milliseconds have passed since the
  2069. // call to svr.listen(), and if after 5 seconds nothing started yet
  2070. // aborts the test.
  2071. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  2072. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2073. ASSERT_LT(milliseconds, 5000U);
  2074. }
  2075. {
  2076. Client cli("::1", PORT);
  2077. cli.set_follow_location(true);
  2078. std::string body;
  2079. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2080. body.append(data, data_length);
  2081. return true;
  2082. });
  2083. ASSERT_TRUE(res);
  2084. EXPECT_EQ(StatusCode::OK_200, res->status);
  2085. EXPECT_EQ("Hello World!", body);
  2086. }
  2087. {
  2088. Client cli("::1", PORT);
  2089. std::string body;
  2090. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  2091. body.append(data, data_length);
  2092. return true;
  2093. });
  2094. ASSERT_TRUE(res);
  2095. EXPECT_EQ(StatusCode::Found_302, res->status);
  2096. EXPECT_EQ("___", body);
  2097. }
  2098. }
  2099. TEST(PathUrlEncodeTest, PathUrlEncode) {
  2100. Server svr;
  2101. svr.Get("/foo", [](const Request &req, Response &res) {
  2102. auto a = req.params.find("a");
  2103. if (a != req.params.end()) {
  2104. res.set_content((*a).second, "text/plain");
  2105. res.status = StatusCode::OK_200;
  2106. } else {
  2107. res.status = StatusCode::BadRequest_400;
  2108. }
  2109. });
  2110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2111. auto se = detail::scope_exit([&] {
  2112. svr.stop();
  2113. thread.join();
  2114. ASSERT_FALSE(svr.is_running());
  2115. });
  2116. svr.wait_until_ready();
  2117. {
  2118. Client cli(HOST, PORT);
  2119. cli.set_path_encode(false);
  2120. auto res = cli.Get("/foo?a=explicitly+encoded");
  2121. ASSERT_TRUE(res);
  2122. EXPECT_EQ(StatusCode::OK_200, res->status);
  2123. // This expects it back with a space, as the `+` won't have been
  2124. // url-encoded, and server-side the params get decoded turning `+`
  2125. // into spaces.
  2126. EXPECT_EQ("explicitly encoded", res->body);
  2127. }
  2128. }
  2129. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2130. Server svr;
  2131. svr.Get("/", [](const Request &req, Response &) {
  2132. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2133. });
  2134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2135. auto se = detail::scope_exit([&] {
  2136. svr.stop();
  2137. thread.join();
  2138. ASSERT_FALSE(svr.is_running());
  2139. });
  2140. svr.wait_until_ready();
  2141. {
  2142. Client cli(HOST, PORT);
  2143. cli.set_path_encode(false);
  2144. auto res = cli.Get("/?something=%0A");
  2145. ASSERT_TRUE(res);
  2146. EXPECT_EQ(StatusCode::OK_200, res->status);
  2147. }
  2148. }
  2149. TEST(BindServerTest, BindDualStack) {
  2150. Server svr;
  2151. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2152. res.set_content("Hello World!", "text/plain");
  2153. });
  2154. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2155. auto se = detail::scope_exit([&] {
  2156. svr.stop();
  2157. thread.join();
  2158. ASSERT_FALSE(svr.is_running());
  2159. });
  2160. svr.wait_until_ready();
  2161. {
  2162. Client cli("127.0.0.1", PORT);
  2163. auto res = cli.Get("/1");
  2164. ASSERT_TRUE(res);
  2165. EXPECT_EQ(StatusCode::OK_200, res->status);
  2166. EXPECT_EQ("Hello World!", res->body);
  2167. }
  2168. {
  2169. Client cli("::1", PORT);
  2170. auto res = cli.Get("/1");
  2171. ASSERT_TRUE(res);
  2172. EXPECT_EQ(StatusCode::OK_200, res->status);
  2173. EXPECT_EQ("Hello World!", res->body);
  2174. }
  2175. }
  2176. TEST(BindServerTest, BindAndListenSeparately) {
  2177. Server svr;
  2178. int port = svr.bind_to_any_port("0.0.0.0");
  2179. ASSERT_TRUE(svr.is_valid());
  2180. ASSERT_TRUE(port > 0);
  2181. svr.stop();
  2182. }
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2186. CLIENT_CA_CERT_DIR);
  2187. int port = svr.bind_to_any_port("0.0.0.0");
  2188. ASSERT_TRUE(svr.is_valid());
  2189. ASSERT_TRUE(port > 0);
  2190. svr.stop();
  2191. }
  2192. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2193. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2194. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2195. int port = svr.bind_to_any_port("0.0.0.0");
  2196. ASSERT_TRUE(svr.is_valid());
  2197. ASSERT_TRUE(port > 0);
  2198. svr.stop();
  2199. }
  2200. TEST(BindServerTest, UpdateCertsPem) {
  2201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2202. int port = svr.bind_to_any_port("0.0.0.0");
  2203. ASSERT_TRUE(svr.is_valid());
  2204. ASSERT_TRUE(port > 0);
  2205. // Read PEM files
  2206. std::string cert_pem, key_pem, ca_pem;
  2207. read_file(SERVER_CERT_FILE, cert_pem);
  2208. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2209. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2210. // Update server certificates using PEM API
  2211. ASSERT_TRUE(
  2212. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2213. ASSERT_TRUE(svr.is_valid());
  2214. svr.stop();
  2215. }
  2216. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  2217. // Start server with client CA (enables client auth)
  2218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2219. ASSERT_TRUE(svr.is_valid());
  2220. bool handler_called = false;
  2221. svr.Get("/test", [&](const Request &req, Response &res) {
  2222. handler_called = true;
  2223. // Verify client certificate is present
  2224. auto cert = req.peer_cert();
  2225. EXPECT_TRUE(static_cast<bool>(cert));
  2226. res.set_content("ok", "text/plain");
  2227. });
  2228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  2229. auto se = detail::scope_exit([&] {
  2230. svr.stop();
  2231. t.join();
  2232. ASSERT_FALSE(svr.is_running());
  2233. });
  2234. svr.wait_until_ready();
  2235. // Read PEM files
  2236. std::string cert_pem, key_pem, ca_pem;
  2237. read_file(SERVER_CERT_FILE, cert_pem);
  2238. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  2239. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  2240. // Update server certificates and client CA using PEM API while server running
  2241. ASSERT_TRUE(
  2242. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  2243. // Connect with client certificate
  2244. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  2245. cli.enable_server_certificate_verification(false);
  2246. cli.set_connection_timeout(30);
  2247. auto res = cli.Get("/test");
  2248. ASSERT_TRUE(res);
  2249. ASSERT_EQ(StatusCode::OK_200, res->status);
  2250. ASSERT_TRUE(handler_called);
  2251. EXPECT_EQ("ok", res->body);
  2252. }
  2253. #endif
  2254. TEST(ErrorHandlerTest, ContentLength) {
  2255. Server svr;
  2256. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2257. res.status = StatusCode::OK_200;
  2258. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2259. "text/html"); // <= Content-Length still 13
  2260. });
  2261. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2262. res.set_content("Hello World!\n", "text/plain");
  2263. res.status = 524;
  2264. });
  2265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2266. auto se = detail::scope_exit([&] {
  2267. svr.stop();
  2268. thread.join();
  2269. ASSERT_FALSE(svr.is_running());
  2270. });
  2271. svr.wait_until_ready();
  2272. {
  2273. Client cli(HOST, PORT);
  2274. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2275. ASSERT_TRUE(res);
  2276. EXPECT_EQ(StatusCode::OK_200, res->status);
  2277. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2278. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2279. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2280. }
  2281. }
  2282. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2283. TEST(ExceptionTest, WithoutExceptionHandler) {
  2284. Server svr;
  2285. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2286. throw std::runtime_error("exception...");
  2287. });
  2288. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2289. throw std::runtime_error("exception\r\n...");
  2290. });
  2291. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2292. auto se = detail::scope_exit([&] {
  2293. svr.stop();
  2294. listen_thread.join();
  2295. ASSERT_FALSE(svr.is_running());
  2296. });
  2297. svr.wait_until_ready();
  2298. Client cli("localhost", PORT);
  2299. {
  2300. auto res = cli.Get("/exception");
  2301. ASSERT_TRUE(res);
  2302. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2303. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2304. }
  2305. {
  2306. auto res = cli.Get("/unknown");
  2307. ASSERT_TRUE(res);
  2308. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2309. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  2310. }
  2311. }
  2312. TEST(ExceptionTest, WithExceptionHandler) {
  2313. Server svr;
  2314. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2315. std::exception_ptr ep) {
  2316. EXPECT_FALSE(ep == nullptr);
  2317. try {
  2318. std::rethrow_exception(ep);
  2319. } catch (std::exception &e) {
  2320. EXPECT_EQ("abc", std::string(e.what()));
  2321. } catch (...) {}
  2322. res.status = StatusCode::InternalServerError_500;
  2323. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2324. "text/html"); // <= Content-Length still 13 at this point
  2325. });
  2326. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2327. res.set_content("Hello World!\n", "text/plain");
  2328. throw std::runtime_error("abc");
  2329. });
  2330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. thread.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. for (size_t i = 0; i < 10; i++) {
  2338. Client cli(HOST, PORT);
  2339. for (size_t j = 0; j < 100; j++) {
  2340. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2341. ASSERT_TRUE(res);
  2342. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2343. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2344. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2345. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2346. }
  2347. cli.set_keep_alive(true);
  2348. for (size_t j = 0; j < 100; j++) {
  2349. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2350. ASSERT_TRUE(res);
  2351. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2353. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2354. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2355. }
  2356. }
  2357. }
  2358. TEST(ExceptionTest, AndErrorHandler) {
  2359. Server svr;
  2360. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2361. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2362. });
  2363. svr.set_exception_handler(
  2364. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2365. EXPECT_FALSE(ep == nullptr);
  2366. try {
  2367. std::rethrow_exception(ep);
  2368. } catch (std::exception &e) {
  2369. res.set_content(e.what(), "text/html");
  2370. } catch (...) {}
  2371. res.status = StatusCode::InternalServerError_500;
  2372. });
  2373. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2374. throw std::runtime_error("EXCEPTION");
  2375. });
  2376. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2377. res.set_content("ERROR", "text/html");
  2378. res.status = StatusCode::InternalServerError_500;
  2379. });
  2380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2381. auto se = detail::scope_exit([&] {
  2382. svr.stop();
  2383. thread.join();
  2384. ASSERT_FALSE(svr.is_running());
  2385. });
  2386. svr.wait_until_ready();
  2387. Client cli(HOST, PORT);
  2388. {
  2389. auto res = cli.Get("/exception");
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2392. EXPECT_EQ("EXCEPTION", res->body);
  2393. }
  2394. {
  2395. auto res = cli.Get("/error");
  2396. ASSERT_TRUE(res);
  2397. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2398. EXPECT_EQ("ERROR", res->body);
  2399. }
  2400. {
  2401. auto res = cli.Get("/invalid");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2404. EXPECT_EQ("NOT_FOUND", res->body);
  2405. }
  2406. }
  2407. #endif
  2408. TEST(NoContentTest, ContentLength) {
  2409. Server svr;
  2410. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2411. res.status = StatusCode::NoContent_204;
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. {
  2421. Client cli(HOST, PORT);
  2422. auto res = cli.Get("/hi");
  2423. ASSERT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2425. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2426. }
  2427. }
  2428. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2429. #ifdef CPPHTTPLIB_SSL_ENABLED
  2430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2431. ASSERT_TRUE(svr.is_valid());
  2432. #else
  2433. Server svr;
  2434. #endif
  2435. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2436. if (req.path == "/routing_handler") {
  2437. res.set_header("PRE_ROUTING", "on");
  2438. res.set_content("Routing Handler", "text/plain");
  2439. return httplib::Server::HandlerResponse::Handled;
  2440. }
  2441. return httplib::Server::HandlerResponse::Unhandled;
  2442. });
  2443. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2444. res.set_content("Error", "text/html");
  2445. });
  2446. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2447. if (req.path == "/routing_handler") {
  2448. res.set_header("POST_ROUTING", "on");
  2449. }
  2450. });
  2451. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2452. res.set_content("Hello World!\n", "text/plain");
  2453. });
  2454. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2455. auto se = detail::scope_exit([&] {
  2456. svr.stop();
  2457. thread.join();
  2458. ASSERT_FALSE(svr.is_running());
  2459. });
  2460. svr.wait_until_ready();
  2461. {
  2462. #ifdef CPPHTTPLIB_SSL_ENABLED
  2463. SSLClient cli(HOST, PORT);
  2464. cli.enable_server_certificate_verification(false);
  2465. #else
  2466. Client cli(HOST, PORT);
  2467. #endif
  2468. auto res = cli.Get("/routing_handler");
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. EXPECT_EQ("Routing Handler", res->body);
  2472. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2473. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2474. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2475. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2476. }
  2477. {
  2478. #ifdef CPPHTTPLIB_SSL_ENABLED
  2479. SSLClient cli(HOST, PORT);
  2480. cli.enable_server_certificate_verification(false);
  2481. #else
  2482. Client cli(HOST, PORT);
  2483. #endif
  2484. auto res = cli.Get("/hi");
  2485. ASSERT_TRUE(res);
  2486. EXPECT_EQ(StatusCode::OK_200, res->status);
  2487. EXPECT_EQ("Hello World!\n", res->body);
  2488. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2489. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2490. }
  2491. {
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(HOST, PORT);
  2494. cli.enable_server_certificate_verification(false);
  2495. #else
  2496. Client cli(HOST, PORT);
  2497. #endif
  2498. auto res = cli.Get("/aaa");
  2499. ASSERT_TRUE(res);
  2500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2501. EXPECT_EQ("Error", res->body);
  2502. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2503. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2504. }
  2505. }
  2506. TEST(RequestHandlerTest, PreRequestHandler) {
  2507. auto route_path = "/user/:user";
  2508. Server svr;
  2509. svr.Get("/hi", [](const Request &, Response &res) {
  2510. res.set_content("hi", "text/plain");
  2511. });
  2512. svr.Get(route_path, [](const Request &req, Response &res) {
  2513. res.set_content(req.path_params.at("user"), "text/plain");
  2514. });
  2515. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2516. if (req.matched_route == route_path) {
  2517. auto user = req.path_params.at("user");
  2518. if (user != "john") {
  2519. res.status = StatusCode::Forbidden_403;
  2520. res.set_content("error", "text/html");
  2521. return Server::HandlerResponse::Handled;
  2522. }
  2523. }
  2524. return Server::HandlerResponse::Unhandled;
  2525. });
  2526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(HOST, PORT);
  2534. {
  2535. auto res = cli.Get("/hi");
  2536. ASSERT_TRUE(res);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. EXPECT_EQ("hi", res->body);
  2539. }
  2540. {
  2541. auto res = cli.Get("/user/john");
  2542. ASSERT_TRUE(res);
  2543. EXPECT_EQ(StatusCode::OK_200, res->status);
  2544. EXPECT_EQ("john", res->body);
  2545. }
  2546. {
  2547. auto res = cli.Get("/user/invalid-user");
  2548. ASSERT_TRUE(res);
  2549. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2550. EXPECT_EQ("error", res->body);
  2551. }
  2552. }
  2553. TEST(UserDataTest, BasicOperations) {
  2554. httplib::UserData ud;
  2555. // Initially empty
  2556. EXPECT_FALSE(ud.has("key"));
  2557. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2558. // set and get
  2559. ud.set("key", 42);
  2560. EXPECT_TRUE(ud.has("key"));
  2561. auto *p = ud.get<int>("key");
  2562. ASSERT_NE(nullptr, p);
  2563. EXPECT_EQ(42, *p);
  2564. // Type mismatch → nullptr
  2565. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  2566. // Overwrite with different type
  2567. ud.set("key", std::string("hello"));
  2568. EXPECT_EQ(nullptr, ud.get<int>("key"));
  2569. auto *s = ud.get<std::string>("key");
  2570. ASSERT_NE(nullptr, s);
  2571. EXPECT_EQ("hello", *s);
  2572. // erase
  2573. ud.erase("key");
  2574. EXPECT_FALSE(ud.has("key"));
  2575. // clear
  2576. ud.set("a", 1);
  2577. ud.set("b", 2);
  2578. ud.clear();
  2579. EXPECT_FALSE(ud.has("a"));
  2580. EXPECT_FALSE(ud.has("b"));
  2581. }
  2582. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  2583. struct AuthCtx {
  2584. std::string user_id;
  2585. };
  2586. Server svr;
  2587. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  2588. res.user_data.set("auth", AuthCtx{"alice"});
  2589. return Server::HandlerResponse::Unhandled;
  2590. });
  2591. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  2592. auto *ctx = res.user_data.get<AuthCtx>("auth");
  2593. ASSERT_NE(nullptr, ctx);
  2594. res.set_content("Hello " + ctx->user_id, "text/plain");
  2595. });
  2596. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2597. auto se = detail::scope_exit([&] {
  2598. svr.stop();
  2599. thread.join();
  2600. ASSERT_FALSE(svr.is_running());
  2601. });
  2602. svr.wait_until_ready();
  2603. Client cli(HOST, PORT);
  2604. auto res = cli.Get("/me");
  2605. ASSERT_TRUE(res);
  2606. EXPECT_EQ(StatusCode::OK_200, res->status);
  2607. EXPECT_EQ("Hello alice", res->body);
  2608. }
  2609. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  2610. struct RoleCtx {
  2611. std::string role;
  2612. };
  2613. Server svr;
  2614. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  2615. res.user_data.set("role", RoleCtx{"admin"});
  2616. return Server::HandlerResponse::Unhandled;
  2617. });
  2618. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  2619. auto *ctx = res.user_data.get<RoleCtx>("role");
  2620. ASSERT_NE(nullptr, ctx);
  2621. res.set_content(ctx->role, "text/plain");
  2622. });
  2623. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2624. auto se = detail::scope_exit([&] {
  2625. svr.stop();
  2626. thread.join();
  2627. ASSERT_FALSE(svr.is_running());
  2628. });
  2629. svr.wait_until_ready();
  2630. Client cli(HOST, PORT);
  2631. auto res = cli.Get("/role");
  2632. ASSERT_TRUE(res);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. EXPECT_EQ("admin", res->body);
  2635. }
  2636. TEST(InvalidFormatTest, StatusCode) {
  2637. Server svr;
  2638. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2639. res.set_content("Hello World!\n", "text/plain");
  2640. res.status = 9999; // Status should be a three-digit code...
  2641. });
  2642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2643. auto se = detail::scope_exit([&] {
  2644. svr.stop();
  2645. thread.join();
  2646. ASSERT_FALSE(svr.is_running());
  2647. });
  2648. svr.wait_until_ready();
  2649. {
  2650. Client cli(HOST, PORT);
  2651. auto res = cli.Get("/hi");
  2652. ASSERT_FALSE(res);
  2653. }
  2654. }
  2655. TEST(URLFragmentTest, WithFragment) {
  2656. Server svr;
  2657. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2658. EXPECT_TRUE(req.target == "/hi");
  2659. });
  2660. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2661. auto se = detail::scope_exit([&] {
  2662. svr.stop();
  2663. thread.join();
  2664. ASSERT_FALSE(svr.is_running());
  2665. });
  2666. svr.wait_until_ready();
  2667. {
  2668. Client cli(HOST, PORT);
  2669. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2670. EXPECT_TRUE(res);
  2671. EXPECT_EQ(StatusCode::OK_200, res->status);
  2672. res = cli.Get("/hi%23key1=val1=key2=val2");
  2673. EXPECT_TRUE(res);
  2674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2675. }
  2676. }
  2677. TEST(HeaderWriter, SetHeaderWriter) {
  2678. Server svr;
  2679. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2680. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2681. return detail::write_headers(strm, hdrs);
  2682. });
  2683. svr.Get("/hi", [](const Request &req, Response &res) {
  2684. auto it = req.headers.find("CustomClientHeader");
  2685. EXPECT_TRUE(it != req.headers.end());
  2686. EXPECT_EQ(it->second, "CustomClientValue");
  2687. res.set_content("Hello World!\n", "text/plain");
  2688. });
  2689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2690. auto se = detail::scope_exit([&] {
  2691. svr.stop();
  2692. thread.join();
  2693. ASSERT_FALSE(svr.is_running());
  2694. });
  2695. svr.wait_until_ready();
  2696. {
  2697. Client cli(HOST, PORT);
  2698. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2699. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2700. return detail::write_headers(strm, hdrs);
  2701. });
  2702. auto res = cli.Get("/hi");
  2703. EXPECT_TRUE(res);
  2704. EXPECT_EQ(StatusCode::OK_200, res->status);
  2705. auto it = res->headers.find("CustomServerHeader");
  2706. EXPECT_TRUE(it != res->headers.end());
  2707. EXPECT_EQ(it->second, "CustomServerValue");
  2708. }
  2709. }
  2710. class ServerTest : public ::testing::Test {
  2711. protected:
  2712. ServerTest()
  2713. : cli_(HOST, PORT)
  2714. #ifdef CPPHTTPLIB_SSL_ENABLED
  2715. ,
  2716. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2717. #endif
  2718. {
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. cli_.enable_server_certificate_verification(false);
  2721. #endif
  2722. // Allow LARGE_DATA (100MB) responses
  2723. cli_.set_payload_max_length(200 * 1024 * 1024);
  2724. }
  2725. virtual void SetUp() {
  2726. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  2727. svr_.set_payload_max_length(200 * 1024 * 1024);
  2728. svr_.set_mount_point("/", "./www");
  2729. svr_.set_mount_point("/mount", "./www2");
  2730. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2731. svr_.Get("/hi",
  2732. [&](const Request & /*req*/, Response &res) {
  2733. res.set_content("Hello World!", "text/plain");
  2734. })
  2735. .Get("/file_content",
  2736. [&](const Request & /*req*/, Response &res) {
  2737. res.set_file_content("./www/dir/test.html");
  2738. })
  2739. .Get("/file_content_with_content_type",
  2740. [&](const Request & /*req*/, Response &res) {
  2741. res.set_file_content("./www/file", "text/plain");
  2742. })
  2743. .Get("/invalid_file_content",
  2744. [&](const Request & /*req*/, Response &res) {
  2745. res.set_file_content("./www/dir/invalid_file_path");
  2746. })
  2747. .Get("/http_response_splitting",
  2748. [&](const Request & /*req*/, Response &res) {
  2749. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2750. EXPECT_EQ(0U, res.headers.size());
  2751. EXPECT_FALSE(res.has_header("a"));
  2752. res.set_header("a", "1\nSet-Cookie: a=1");
  2753. EXPECT_EQ(0U, res.headers.size());
  2754. EXPECT_FALSE(res.has_header("a"));
  2755. res.set_header("a", "1\rSet-Cookie: a=1");
  2756. EXPECT_EQ(0U, res.headers.size());
  2757. EXPECT_FALSE(res.has_header("a"));
  2758. res.set_header("a\r\nb", "0");
  2759. EXPECT_EQ(0U, res.headers.size());
  2760. EXPECT_FALSE(res.has_header("a"));
  2761. res.set_header("a\rb", "0");
  2762. EXPECT_EQ(0U, res.headers.size());
  2763. EXPECT_FALSE(res.has_header("a"));
  2764. res.set_header("a\nb", "0");
  2765. EXPECT_EQ(0U, res.headers.size());
  2766. EXPECT_FALSE(res.has_header("a"));
  2767. res.set_redirect("1\r\nSet-Cookie: a=1");
  2768. EXPECT_EQ(0U, res.headers.size());
  2769. EXPECT_FALSE(res.has_header("Location"));
  2770. })
  2771. .Get("/slow",
  2772. [&](const Request & /*req*/, Response &res) {
  2773. std::this_thread::sleep_for(std::chrono::seconds(2));
  2774. res.set_content("slow", "text/plain");
  2775. })
  2776. #if 0
  2777. .Post("/slowpost",
  2778. [&](const Request & /*req*/, Response &res) {
  2779. std::this_thread::sleep_for(std::chrono::seconds(2));
  2780. res.set_content("slow", "text/plain");
  2781. })
  2782. #endif
  2783. .Get("/remote_addr",
  2784. [&](const Request &req, Response &res) {
  2785. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2786. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2787. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2788. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2789. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2790. #endif
  2791. res.set_content(req.remote_addr, "text/plain");
  2792. })
  2793. .Get("/local_addr",
  2794. [&](const Request &req, Response &res) {
  2795. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2796. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2797. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2798. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2799. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2800. #endif
  2801. auto local_addr = req.local_addr;
  2802. auto local_port = std::to_string(req.local_port);
  2803. res.set_content(local_addr.append(":").append(local_port),
  2804. "text/plain");
  2805. })
  2806. .Get("/endwith%",
  2807. [&](const Request & /*req*/, Response &res) {
  2808. res.set_content("Hello World!", "text/plain");
  2809. })
  2810. .Get("/a\\+\\+b",
  2811. [&](const Request &req, Response &res) {
  2812. ASSERT_TRUE(req.has_param("a +b"));
  2813. auto val = req.get_param_value("a +b");
  2814. res.set_content(val, "text/plain");
  2815. })
  2816. .Get("/", [&](const Request & /*req*/,
  2817. Response &res) { res.set_redirect("/hi"); })
  2818. .Post("/1",
  2819. [](const Request & /*req*/, Response &res) {
  2820. res.set_redirect("/2", StatusCode::SeeOther_303);
  2821. })
  2822. .Get("/2",
  2823. [](const Request & /*req*/, Response &res) {
  2824. res.set_content("redirected.", "text/plain");
  2825. res.status = StatusCode::OK_200;
  2826. })
  2827. .Post("/person",
  2828. [&](const Request &req, Response &res) {
  2829. if (req.has_param("name") && req.has_param("note")) {
  2830. persons_[req.get_param_value("name")] =
  2831. req.get_param_value("note");
  2832. } else {
  2833. res.status = StatusCode::BadRequest_400;
  2834. }
  2835. })
  2836. .Put("/person",
  2837. [&](const Request &req, Response &res) {
  2838. if (req.has_param("name") && req.has_param("note")) {
  2839. persons_[req.get_param_value("name")] =
  2840. req.get_param_value("note");
  2841. } else {
  2842. res.status = StatusCode::BadRequest_400;
  2843. }
  2844. })
  2845. .Get("/person/(.*)",
  2846. [&](const Request &req, Response &res) {
  2847. string name = req.matches[1];
  2848. if (persons_.find(name) != persons_.end()) {
  2849. auto note = persons_[name];
  2850. res.set_content(note, "text/plain");
  2851. } else {
  2852. res.status = StatusCode::NotFound_404;
  2853. }
  2854. })
  2855. .Delete("/person",
  2856. [&](const Request &req, Response &res) {
  2857. if (req.has_param("name")) {
  2858. string name = req.get_param_value("name");
  2859. if (persons_.find(name) != persons_.end()) {
  2860. persons_.erase(name);
  2861. res.set_content("DELETED", "text/plain");
  2862. } else {
  2863. res.status = StatusCode::NotFound_404;
  2864. }
  2865. } else {
  2866. res.status = StatusCode::BadRequest_400;
  2867. }
  2868. })
  2869. .Post("/x-www-form-urlencoded-json",
  2870. [&](const Request &req, Response &res) {
  2871. auto json = req.get_param_value("json");
  2872. ASSERT_EQ(JSON_DATA, json);
  2873. res.set_content(json, "appliation/json");
  2874. res.status = StatusCode::OK_200;
  2875. })
  2876. .Get("/streamed-chunked",
  2877. [&](const Request & /*req*/, Response &res) {
  2878. res.set_chunked_content_provider(
  2879. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2880. sink.os << "123";
  2881. sink.os << "456";
  2882. sink.os << "789";
  2883. sink.done();
  2884. return true;
  2885. });
  2886. })
  2887. .Get("/streamed-chunked-with-prohibited-trailer",
  2888. [&](const Request & /*req*/, Response &res) {
  2889. auto i = new int(0);
  2890. // Declare both a prohibited trailer (Content-Length) and an
  2891. // allowed one
  2892. res.set_header("Trailer", "Content-Length, X-Allowed");
  2893. res.set_chunked_content_provider(
  2894. "text/plain",
  2895. [i](size_t /*offset*/, DataSink &sink) {
  2896. switch (*i) {
  2897. case 0: sink.os << "123"; break;
  2898. case 1: sink.os << "456"; break;
  2899. case 2: sink.os << "789"; break;
  2900. case 3: {
  2901. sink.done_with_trailer(
  2902. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2903. } break;
  2904. }
  2905. (*i)++;
  2906. return true;
  2907. },
  2908. [i](bool success) {
  2909. EXPECT_TRUE(success);
  2910. delete i;
  2911. });
  2912. })
  2913. .Get("/streamed-chunked2",
  2914. [&](const Request & /*req*/, Response &res) {
  2915. auto i = new int(0);
  2916. res.set_chunked_content_provider(
  2917. "text/plain",
  2918. [i](size_t /*offset*/, DataSink &sink) {
  2919. switch (*i) {
  2920. case 0: sink.os << "123"; break;
  2921. case 1: sink.os << "456"; break;
  2922. case 2: sink.os << "789"; break;
  2923. case 3: sink.done(); break;
  2924. }
  2925. (*i)++;
  2926. return true;
  2927. },
  2928. [i](bool success) {
  2929. EXPECT_TRUE(success);
  2930. delete i;
  2931. });
  2932. })
  2933. .Get("/streamed-chunked-with-trailer",
  2934. [&](const Request & /*req*/, Response &res) {
  2935. auto i = new int(0);
  2936. res.set_header("Trailer", "Dummy1, Dummy2");
  2937. res.set_chunked_content_provider(
  2938. "text/plain",
  2939. [i](size_t /*offset*/, DataSink &sink) {
  2940. switch (*i) {
  2941. case 0: sink.os << "123"; break;
  2942. case 1: sink.os << "456"; break;
  2943. case 2: sink.os << "789"; break;
  2944. case 3: {
  2945. sink.done_with_trailer(
  2946. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2947. } break;
  2948. }
  2949. (*i)++;
  2950. return true;
  2951. },
  2952. [i](bool success) {
  2953. EXPECT_TRUE(success);
  2954. delete i;
  2955. });
  2956. })
  2957. .Get("/streamed",
  2958. [&](const Request & /*req*/, Response &res) {
  2959. res.set_content_provider(
  2960. 6, "text/plain",
  2961. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2962. sink.os << (offset < 3 ? "a" : "b");
  2963. return true;
  2964. });
  2965. })
  2966. .Get("/streamed-with-range",
  2967. [&](const Request &req, Response &res) {
  2968. auto data = new std::string("abcdefg");
  2969. res.set_content_provider(
  2970. data->size(), "text/plain",
  2971. [data](size_t offset, size_t length, DataSink &sink) {
  2972. size_t DATA_CHUNK_SIZE = 4;
  2973. const auto &d = *data;
  2974. auto out_len =
  2975. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2976. auto ret =
  2977. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2978. EXPECT_TRUE(ret);
  2979. return true;
  2980. },
  2981. [data, &req](bool success) {
  2982. EXPECT_EQ(success, !req.has_param("error"));
  2983. delete data;
  2984. });
  2985. })
  2986. .Get("/streamed-cancel",
  2987. [&](const Request & /*req*/, Response &res) {
  2988. res.set_content_provider(
  2989. size_t(-1), "text/plain",
  2990. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2991. sink.os << "data_chunk";
  2992. return true;
  2993. });
  2994. })
  2995. .Get("/regex-with-delimiter",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. ASSERT_TRUE(req.has_param("key"));
  2998. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2999. })
  3000. .Get("/with-range",
  3001. [&](const Request & /*req*/, Response &res) {
  3002. res.set_content("abcdefg", "text/plain");
  3003. })
  3004. .Get("/test-start-time",
  3005. [&](const Request &req, Response & /*res*/) {
  3006. EXPECT_NE(req.start_time_,
  3007. std::chrono::steady_clock::time_point::min());
  3008. })
  3009. .Get("/with-range-customized-response",
  3010. [&](const Request & /*req*/, Response &res) {
  3011. res.status = StatusCode::BadRequest_400;
  3012. res.set_content(JSON_DATA, "application/json");
  3013. })
  3014. .Post("/chunked",
  3015. [&](const Request &req, Response & /*res*/) {
  3016. EXPECT_EQ(req.body, "dechunked post body");
  3017. })
  3018. .Post("/large-chunked",
  3019. [&](const Request &req, Response & /*res*/) {
  3020. std::string expected(6 * 30 * 1024u, 'a');
  3021. EXPECT_EQ(req.body, expected);
  3022. })
  3023. .Post("/multipart",
  3024. [&](const Request &req, Response & /*res*/) {
  3025. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  3026. req.form.get_field_count("text2") +
  3027. req.form.get_field_count("file3") +
  3028. req.form.get_field_count("file4"));
  3029. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  3030. req.form.get_file_count("file2"));
  3031. ASSERT_TRUE(!req.form.has_file("???"));
  3032. ASSERT_TRUE(!req.form.has_field("???"));
  3033. ASSERT_TRUE(req.body.empty());
  3034. {
  3035. const auto &text = req.form.get_field("text1");
  3036. EXPECT_EQ("text default", text);
  3037. }
  3038. {
  3039. const auto &text = req.form.get_field("text2");
  3040. EXPECT_EQ("aωb", text);
  3041. }
  3042. {
  3043. const auto &file = req.form.get_file("file1");
  3044. EXPECT_EQ("hello.txt", file.filename);
  3045. EXPECT_EQ("text/plain", file.content_type);
  3046. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3047. }
  3048. {
  3049. const auto &file = req.form.get_file("file2");
  3050. EXPECT_EQ("world.json", file.filename);
  3051. EXPECT_EQ("application/json", file.content_type);
  3052. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  3053. }
  3054. {
  3055. const auto &text = req.form.get_field("file3");
  3056. EXPECT_EQ(0u, text.size());
  3057. }
  3058. {
  3059. const auto &text = req.form.get_field("file4");
  3060. EXPECT_EQ(0u, text.size());
  3061. }
  3062. })
  3063. .Post("/multipart/multi_file_values",
  3064. [&](const Request &req, Response & /*res*/) {
  3065. EXPECT_EQ(3u, req.form.get_field_count("text") +
  3066. req.form.get_field_count("multi_text1"));
  3067. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  3068. ASSERT_TRUE(!req.form.has_file("???"));
  3069. ASSERT_TRUE(!req.form.has_field("???"));
  3070. ASSERT_TRUE(req.body.empty());
  3071. {
  3072. const auto &text = req.form.get_field("text");
  3073. EXPECT_EQ("default text", text);
  3074. }
  3075. {
  3076. const auto &text1_values = req.form.get_fields("multi_text1");
  3077. EXPECT_EQ(2u, text1_values.size());
  3078. EXPECT_EQ("aaaaa", text1_values[0]);
  3079. EXPECT_EQ("bbbbb", text1_values[1]);
  3080. }
  3081. {
  3082. const auto &file1_values = req.form.get_files("multi_file1");
  3083. EXPECT_EQ(2u, file1_values.size());
  3084. auto file1 = file1_values[0];
  3085. EXPECT_EQ(file1.filename, "hello.txt");
  3086. EXPECT_EQ(file1.content_type, "text/plain");
  3087. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  3088. auto file2 = file1_values[1];
  3089. EXPECT_EQ(file2.filename, "world.json");
  3090. EXPECT_EQ(file2.content_type, "application/json");
  3091. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  3092. }
  3093. })
  3094. .Post("/empty",
  3095. [&](const Request &req, Response &res) {
  3096. EXPECT_EQ(req.body, "");
  3097. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  3098. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3099. res.set_content("empty", "text/plain");
  3100. })
  3101. .Post("/empty-no-content-type",
  3102. [&](const Request &req, Response &res) {
  3103. EXPECT_EQ(req.body, "");
  3104. EXPECT_FALSE(req.has_header("Content-Type"));
  3105. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3106. res.set_content("empty-no-content-type", "text/plain");
  3107. })
  3108. .Post("/path-only",
  3109. [&](const Request &req, Response &res) {
  3110. EXPECT_EQ(req.body, "");
  3111. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3112. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3113. res.set_content("path-only", "text/plain");
  3114. })
  3115. .Post("/path-headers-only",
  3116. [&](const Request &req, Response &res) {
  3117. EXPECT_EQ(req.body, "");
  3118. EXPECT_EQ("", req.get_header_value("Content-Type"));
  3119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3120. EXPECT_EQ("world", req.get_header_value("hello"));
  3121. EXPECT_EQ("world2", req.get_header_value("hello2"));
  3122. res.set_content("path-headers-only", "text/plain");
  3123. })
  3124. .Post("/post-large",
  3125. [&](const Request &req, Response &res) {
  3126. EXPECT_EQ(req.body, LARGE_DATA);
  3127. res.set_content(req.body, "text/plain");
  3128. })
  3129. .Post("/post-loopback",
  3130. [&](const Request &, Response &res,
  3131. ContentReader const &content_reader) {
  3132. std::string body;
  3133. content_reader([&](const char *data, size_t data_length) {
  3134. body.append(data, data_length);
  3135. return true;
  3136. });
  3137. res.set_content(body, "text/plain");
  3138. })
  3139. .Put("/put-loopback",
  3140. [&](const Request &, Response &res,
  3141. ContentReader const &content_reader) {
  3142. std::string body;
  3143. content_reader([&](const char *data, size_t data_length) {
  3144. body.append(data, data_length);
  3145. return true;
  3146. });
  3147. res.set_content(body, "text/plain");
  3148. })
  3149. .Patch("/patch-loopback",
  3150. [&](const Request &, Response &res,
  3151. ContentReader const &content_reader) {
  3152. std::string body;
  3153. content_reader([&](const char *data, size_t data_length) {
  3154. body.append(data, data_length);
  3155. return true;
  3156. });
  3157. res.set_content(body, "text/plain");
  3158. })
  3159. .Put("/empty-no-content-type",
  3160. [&](const Request &req, Response &res) {
  3161. EXPECT_EQ(req.body, "");
  3162. EXPECT_FALSE(req.has_header("Content-Type"));
  3163. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3164. res.set_content("empty-no-content-type", "text/plain");
  3165. })
  3166. .Put("/put",
  3167. [&](const Request &req, Response &res) {
  3168. EXPECT_EQ(req.body, "PUT");
  3169. res.set_content(req.body, "text/plain");
  3170. })
  3171. .Put("/put-large",
  3172. [&](const Request &req, Response &res) {
  3173. EXPECT_EQ(req.body, LARGE_DATA);
  3174. res.set_content(req.body, "text/plain");
  3175. })
  3176. .Patch("/patch",
  3177. [&](const Request &req, Response &res) {
  3178. EXPECT_EQ(req.body, "PATCH");
  3179. res.set_content(req.body, "text/plain");
  3180. })
  3181. .Delete("/delete",
  3182. [&](const Request & /*req*/, Response &res) {
  3183. res.set_content("DELETE", "text/plain");
  3184. })
  3185. .Delete("/delete-body",
  3186. [&](const Request &req, Response &res) {
  3187. EXPECT_EQ(req.body, "content");
  3188. res.set_content(req.body, "text/plain");
  3189. })
  3190. .Options(R"(\*)",
  3191. [&](const Request & /*req*/, Response &res) {
  3192. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3193. })
  3194. .Get("/request-target",
  3195. [&](const Request &req, Response & /*res*/) {
  3196. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3197. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3198. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3199. })
  3200. .Get("/long-query-value",
  3201. [&](const Request &req, Response & /*res*/) {
  3202. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3203. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3204. })
  3205. .Get("/too-long-query-value",
  3206. [&](const Request &req, Response & /*res*/) {
  3207. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3208. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3209. })
  3210. .Get("/array-param",
  3211. [&](const Request &req, Response & /*res*/) {
  3212. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3213. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3214. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3215. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3216. })
  3217. .Get("/array-param-values",
  3218. [&](const Request &req, Response & /*res*/) {
  3219. auto values = req.get_param_values("array");
  3220. EXPECT_EQ(3u, values.size());
  3221. EXPECT_EQ("value1", values[0]);
  3222. EXPECT_EQ("value2", values[1]);
  3223. EXPECT_EQ("value3", values[2]);
  3224. auto empty = req.get_param_values("nonexistent");
  3225. EXPECT_TRUE(empty.empty());
  3226. })
  3227. .Post("/validate-no-multiple-headers",
  3228. [&](const Request &req, Response & /*res*/) {
  3229. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3230. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3231. })
  3232. .Post("/content_receiver",
  3233. [&](const Request &req, Response &res,
  3234. const ContentReader &content_reader) {
  3235. if (req.is_multipart_form_data()) {
  3236. std::vector<FormData> items;
  3237. content_reader(
  3238. [&](const FormData &file) {
  3239. items.push_back(file);
  3240. return true;
  3241. },
  3242. [&](const char *data, size_t data_length) {
  3243. items.back().content.append(data, data_length);
  3244. return true;
  3245. });
  3246. EXPECT_EQ(5u, items.size());
  3247. {
  3248. const auto &file = get_file_value(items, "text1");
  3249. EXPECT_TRUE(file.filename.empty());
  3250. EXPECT_EQ("text default", file.content);
  3251. }
  3252. {
  3253. const auto &file = get_file_value(items, "text2");
  3254. EXPECT_TRUE(file.filename.empty());
  3255. EXPECT_EQ("aωb", file.content);
  3256. }
  3257. {
  3258. const auto &file = get_file_value(items, "file1");
  3259. EXPECT_EQ("hello.txt", file.filename);
  3260. EXPECT_EQ("text/plain", file.content_type);
  3261. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3262. }
  3263. {
  3264. const auto &file = get_file_value(items, "file2");
  3265. EXPECT_EQ("world.json", file.filename);
  3266. EXPECT_EQ("application/json", file.content_type);
  3267. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3268. }
  3269. {
  3270. const auto &file = get_file_value(items, "file3");
  3271. EXPECT_TRUE(file.filename.empty());
  3272. EXPECT_EQ("application/octet-stream", file.content_type);
  3273. EXPECT_EQ(0u, file.content.size());
  3274. }
  3275. } else {
  3276. std::string body;
  3277. content_reader([&](const char *data, size_t data_length) {
  3278. EXPECT_EQ(7U, data_length);
  3279. body.append(data, data_length);
  3280. return true;
  3281. });
  3282. EXPECT_EQ(body, "content");
  3283. res.set_content(body, "text/plain");
  3284. }
  3285. })
  3286. .Put("/content_receiver",
  3287. [&](const Request & /*req*/, Response &res,
  3288. const ContentReader &content_reader) {
  3289. std::string body;
  3290. content_reader([&](const char *data, size_t data_length) {
  3291. body.append(data, data_length);
  3292. return true;
  3293. });
  3294. EXPECT_EQ(body, "content");
  3295. res.set_content(body, "text/plain");
  3296. })
  3297. .Patch("/content_receiver",
  3298. [&](const Request & /*req*/, Response &res,
  3299. const ContentReader &content_reader) {
  3300. std::string body;
  3301. content_reader([&](const char *data, size_t data_length) {
  3302. body.append(data, data_length);
  3303. return true;
  3304. });
  3305. EXPECT_EQ(body, "content");
  3306. res.set_content(body, "text/plain");
  3307. })
  3308. .Post("/query-string-and-body",
  3309. [&](const Request &req, Response & /*res*/) {
  3310. ASSERT_TRUE(req.has_param("key"));
  3311. EXPECT_EQ(req.get_param_value("key"), "value");
  3312. EXPECT_EQ(req.body, "content");
  3313. })
  3314. .Get("/last-request",
  3315. [&](const Request &req, Response & /*res*/) {
  3316. EXPECT_EQ("close", req.get_header_value("Connection"));
  3317. })
  3318. .Get(R"(/redirect/(\d+))",
  3319. [&](const Request &req, Response &res) {
  3320. auto num = std::stoi(req.matches[1]) + 1;
  3321. std::string url = "/redirect/" + std::to_string(num);
  3322. res.set_redirect(url);
  3323. })
  3324. .Post("/binary",
  3325. [&](const Request &req, Response &res) {
  3326. EXPECT_EQ(4U, req.body.size());
  3327. EXPECT_EQ("application/octet-stream",
  3328. req.get_header_value("Content-Type"));
  3329. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3330. res.set_content(req.body, "application/octet-stream");
  3331. })
  3332. .Put("/binary",
  3333. [&](const Request &req, Response &res) {
  3334. EXPECT_EQ(4U, req.body.size());
  3335. EXPECT_EQ("application/octet-stream",
  3336. req.get_header_value("Content-Type"));
  3337. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3338. res.set_content(req.body, "application/octet-stream");
  3339. })
  3340. .Patch("/binary",
  3341. [&](const Request &req, Response &res) {
  3342. EXPECT_EQ(4U, req.body.size());
  3343. EXPECT_EQ("application/octet-stream",
  3344. req.get_header_value("Content-Type"));
  3345. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3346. res.set_content(req.body, "application/octet-stream");
  3347. })
  3348. .Delete("/binary",
  3349. [&](const Request &req, Response &res) {
  3350. EXPECT_EQ(4U, req.body.size());
  3351. EXPECT_EQ("application/octet-stream",
  3352. req.get_header_value("Content-Type"));
  3353. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3354. res.set_content(req.body, "application/octet-stream");
  3355. })
  3356. .Get("/issue1772",
  3357. [&](const Request & /*req*/, Response &res) {
  3358. res.status = 401;
  3359. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3360. })
  3361. .Delete("/issue609",
  3362. [](const httplib::Request &, httplib::Response &res,
  3363. const httplib::ContentReader &) {
  3364. res.set_content("ok", "text/plain");
  3365. })
  3366. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3367. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3368. .Get("/compress",
  3369. [&](const Request & /*req*/, Response &res) {
  3370. res.set_content(
  3371. "12345678901234567890123456789012345678901234567890123456789"
  3372. "01234567890123456789012345678901234567890",
  3373. "text/plain");
  3374. })
  3375. .Get("/compress-with-charset",
  3376. [&](const Request & /*req*/, Response &res) {
  3377. res.set_content(
  3378. "12345678901234567890123456789012345678901234567890123456789"
  3379. "01234567890123456789012345678901234567890",
  3380. "application/json; charset=utf-8");
  3381. })
  3382. .Get("/nocompress",
  3383. [&](const Request & /*req*/, Response &res) {
  3384. res.set_content(
  3385. "12345678901234567890123456789012345678901234567890123456789"
  3386. "01234567890123456789012345678901234567890",
  3387. "application/octet-stream");
  3388. })
  3389. .Post("/compress-multipart",
  3390. [&](const Request &req, Response & /*res*/) {
  3391. EXPECT_EQ(2u, req.form.fields.size());
  3392. ASSERT_TRUE(!req.form.has_field("???"));
  3393. {
  3394. const auto &text = req.form.get_field("key1");
  3395. EXPECT_EQ("test", text);
  3396. }
  3397. {
  3398. const auto &text = req.form.get_field("key2");
  3399. EXPECT_EQ("--abcdefg123", text);
  3400. }
  3401. })
  3402. #endif
  3403. ;
  3404. persons_["john"] = "programmer";
  3405. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3406. svr_.wait_until_ready();
  3407. }
  3408. virtual void TearDown() {
  3409. svr_.stop();
  3410. if (!request_threads_.empty()) {
  3411. std::this_thread::sleep_for(std::chrono::seconds(1));
  3412. for (auto &t : request_threads_) {
  3413. t.join();
  3414. }
  3415. }
  3416. t_.join();
  3417. }
  3418. map<string, string> persons_;
  3419. #ifdef CPPHTTPLIB_SSL_ENABLED
  3420. SSLClient cli_;
  3421. SSLServer svr_;
  3422. #else
  3423. Client cli_;
  3424. Server svr_;
  3425. #endif
  3426. thread t_;
  3427. std::vector<thread> request_threads_;
  3428. };
  3429. TEST_F(ServerTest, GetMethod200) {
  3430. auto res = cli_.Get("/hi");
  3431. ASSERT_TRUE(res);
  3432. EXPECT_EQ("HTTP/1.1", res->version);
  3433. EXPECT_EQ(StatusCode::OK_200, res->status);
  3434. EXPECT_EQ("OK", res->reason);
  3435. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3436. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3437. EXPECT_EQ("Hello World!", res->body);
  3438. }
  3439. TEST_F(ServerTest, GetEmptyFile) {
  3440. auto res = cli_.Get("/empty_file");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3444. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3445. EXPECT_EQ("", res->body);
  3446. }
  3447. TEST_F(ServerTest, GetFileContent) {
  3448. auto res = cli_.Get("/file_content");
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3452. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3453. EXPECT_EQ("test.html", res->body);
  3454. }
  3455. TEST_F(ServerTest, GetFileContentWithRange) {
  3456. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3457. ASSERT_TRUE(res);
  3458. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3459. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3460. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3461. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3462. EXPECT_EQ("est", res->body);
  3463. }
  3464. TEST_F(ServerTest, GetFileContentWithContentType) {
  3465. auto res = cli_.Get("/file_content_with_content_type");
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3469. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3470. EXPECT_EQ("file\n", res->body);
  3471. }
  3472. TEST_F(ServerTest, GetInvalidFileContent) {
  3473. auto res = cli_.Get("/invalid_file_content");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3476. }
  3477. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3478. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3479. ASSERT_TRUE(res);
  3480. EXPECT_EQ("HTTP/1.1", res->version);
  3481. EXPECT_EQ(StatusCode::OK_200, res->status);
  3482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3483. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3484. EXPECT_EQ("Hello World!", res->body);
  3485. }
  3486. TEST_F(ServerTest, GetMethod302) {
  3487. auto res = cli_.Get("/");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::Found_302, res->status);
  3490. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3491. }
  3492. TEST_F(ServerTest, GetMethod302Redirect) {
  3493. cli_.set_follow_location(true);
  3494. auto res = cli_.Get("/");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("Hello World!", res->body);
  3498. EXPECT_EQ("/hi", res->location);
  3499. }
  3500. TEST_F(ServerTest, GetMethod404) {
  3501. auto res = cli_.Get("/invalid");
  3502. ASSERT_TRUE(res);
  3503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3504. }
  3505. TEST_F(ServerTest, HeadMethod200) {
  3506. auto res = cli_.Head("/hi");
  3507. ASSERT_TRUE(res);
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3510. EXPECT_TRUE(res->body.empty());
  3511. }
  3512. TEST_F(ServerTest, HeadMethod200Static) {
  3513. auto res = cli_.Head("/mount/dir/index.html");
  3514. ASSERT_TRUE(res);
  3515. EXPECT_EQ(StatusCode::OK_200, res->status);
  3516. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3517. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3518. EXPECT_TRUE(res->body.empty());
  3519. }
  3520. TEST_F(ServerTest, HeadMethod404) {
  3521. auto res = cli_.Head("/invalid");
  3522. ASSERT_TRUE(res);
  3523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3524. EXPECT_TRUE(res->body.empty());
  3525. }
  3526. TEST_F(ServerTest, GetMethodPersonJohn) {
  3527. auto res = cli_.Get("/person/john");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3531. EXPECT_EQ("programmer", res->body);
  3532. }
  3533. TEST_F(ServerTest, PostMethod1) {
  3534. auto res = cli_.Get("/person/john1");
  3535. ASSERT_TRUE(res);
  3536. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3537. res = cli_.Post("/person", "name=john1&note=coder",
  3538. "application/x-www-form-urlencoded");
  3539. ASSERT_TRUE(res);
  3540. ASSERT_EQ(StatusCode::OK_200, res->status);
  3541. res = cli_.Get("/person/john1");
  3542. ASSERT_TRUE(res);
  3543. ASSERT_EQ(StatusCode::OK_200, res->status);
  3544. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3545. ASSERT_EQ("coder", res->body);
  3546. }
  3547. TEST_F(ServerTest, PostMethod2) {
  3548. auto res = cli_.Get("/person/john2");
  3549. ASSERT_TRUE(res);
  3550. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3551. Params params;
  3552. params.emplace("name", "john2");
  3553. params.emplace("note", "coder");
  3554. res = cli_.Post("/person", params);
  3555. ASSERT_TRUE(res);
  3556. ASSERT_EQ(StatusCode::OK_200, res->status);
  3557. res = cli_.Get("/person/john2");
  3558. ASSERT_TRUE(res);
  3559. ASSERT_EQ(StatusCode::OK_200, res->status);
  3560. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3561. ASSERT_EQ("coder", res->body);
  3562. }
  3563. TEST_F(ServerTest, PutMethod3) {
  3564. auto res = cli_.Get("/person/john3");
  3565. ASSERT_TRUE(res);
  3566. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3567. Params params;
  3568. params.emplace("name", "john3");
  3569. params.emplace("note", "coder");
  3570. res = cli_.Put("/person", params);
  3571. ASSERT_TRUE(res);
  3572. ASSERT_EQ(StatusCode::OK_200, res->status);
  3573. res = cli_.Get("/person/john3");
  3574. ASSERT_TRUE(res);
  3575. ASSERT_EQ(StatusCode::OK_200, res->status);
  3576. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3577. ASSERT_EQ("coder", res->body);
  3578. }
  3579. TEST_F(ServerTest, DeleteMethod1) {
  3580. auto res = cli_.Get("/person/john4");
  3581. ASSERT_TRUE(res);
  3582. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3583. Params params;
  3584. params.emplace("name", "john4");
  3585. params.emplace("note", "coder");
  3586. res = cli_.Post("/person", params);
  3587. ASSERT_TRUE(res);
  3588. ASSERT_EQ(StatusCode::OK_200, res->status);
  3589. res = cli_.Get("/person/john4");
  3590. ASSERT_TRUE(res);
  3591. ASSERT_EQ(StatusCode::OK_200, res->status);
  3592. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3593. ASSERT_EQ("coder", res->body);
  3594. Params delete_params;
  3595. delete_params.emplace("name", "john4");
  3596. res = cli_.Delete("/person", delete_params);
  3597. ASSERT_TRUE(res);
  3598. ASSERT_EQ(StatusCode::OK_200, res->status);
  3599. ASSERT_EQ("DELETED", res->body);
  3600. res = cli_.Get("/person/john4");
  3601. ASSERT_TRUE(res);
  3602. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3603. }
  3604. TEST_F(ServerTest, DeleteMethod2) {
  3605. auto res = cli_.Get("/person/john5");
  3606. ASSERT_TRUE(res);
  3607. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3608. Params params;
  3609. params.emplace("name", "john5");
  3610. params.emplace("note", "developer");
  3611. res = cli_.Post("/person", params);
  3612. ASSERT_TRUE(res);
  3613. ASSERT_EQ(StatusCode::OK_200, res->status);
  3614. res = cli_.Get("/person/john5");
  3615. ASSERT_TRUE(res);
  3616. ASSERT_EQ(StatusCode::OK_200, res->status);
  3617. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3618. ASSERT_EQ("developer", res->body);
  3619. Params delete_params;
  3620. delete_params.emplace("name", "john5");
  3621. Headers headers;
  3622. headers.emplace("Custom-Header", "test-value");
  3623. res = cli_.Delete("/person", headers, delete_params);
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ("DELETED", res->body);
  3627. res = cli_.Get("/person/john5");
  3628. ASSERT_TRUE(res);
  3629. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3630. }
  3631. TEST_F(ServerTest, DeleteMethod3) {
  3632. auto res = cli_.Get("/person/john6");
  3633. ASSERT_TRUE(res);
  3634. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3635. Params params;
  3636. params.emplace("name", "john6");
  3637. params.emplace("note", "tester");
  3638. res = cli_.Post("/person", params);
  3639. ASSERT_TRUE(res);
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. res = cli_.Get("/person/john6");
  3642. ASSERT_TRUE(res);
  3643. ASSERT_EQ(StatusCode::OK_200, res->status);
  3644. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3645. ASSERT_EQ("tester", res->body);
  3646. Params delete_params;
  3647. delete_params.emplace("name", "john6");
  3648. Headers headers;
  3649. headers.emplace("Custom-Header", "test-value");
  3650. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3651. ASSERT_TRUE(res);
  3652. ASSERT_EQ(StatusCode::OK_200, res->status);
  3653. ASSERT_EQ("DELETED", res->body);
  3654. res = cli_.Get("/person/john6");
  3655. ASSERT_TRUE(res);
  3656. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3657. }
  3658. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3659. Params params;
  3660. params.emplace("json", JSON_DATA);
  3661. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3662. ASSERT_TRUE(res);
  3663. ASSERT_EQ(StatusCode::OK_200, res->status);
  3664. ASSERT_EQ(JSON_DATA, res->body);
  3665. }
  3666. TEST_F(ServerTest, PostEmptyContent) {
  3667. auto res = cli_.Post("/empty", "", "text/plain");
  3668. ASSERT_TRUE(res);
  3669. ASSERT_EQ(StatusCode::OK_200, res->status);
  3670. ASSERT_EQ("empty", res->body);
  3671. }
  3672. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3673. auto res = cli_.Post("/empty-no-content-type");
  3674. ASSERT_TRUE(res);
  3675. ASSERT_EQ(StatusCode::OK_200, res->status);
  3676. ASSERT_EQ("empty-no-content-type", res->body);
  3677. }
  3678. TEST_F(ServerTest, PostPathOnly) {
  3679. auto res = cli_.Post("/path-only");
  3680. ASSERT_TRUE(res);
  3681. ASSERT_EQ(StatusCode::OK_200, res->status);
  3682. ASSERT_EQ("path-only", res->body);
  3683. }
  3684. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3685. auto res = cli_.Post("/path-headers-only",
  3686. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3687. ASSERT_TRUE(res);
  3688. ASSERT_EQ(StatusCode::OK_200, res->status);
  3689. ASSERT_EQ("path-headers-only", res->body);
  3690. }
  3691. TEST_F(ServerTest, PostLarge) {
  3692. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3693. ASSERT_TRUE(res);
  3694. ASSERT_EQ(StatusCode::OK_200, res->status);
  3695. EXPECT_EQ(LARGE_DATA, res->body);
  3696. }
  3697. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3698. auto res = cli_.Put("/empty-no-content-type");
  3699. ASSERT_TRUE(res);
  3700. ASSERT_EQ(StatusCode::OK_200, res->status);
  3701. ASSERT_EQ("empty-no-content-type", res->body);
  3702. }
  3703. TEST_F(ServerTest, GetMethodDir) {
  3704. auto res = cli_.Get("/dir/");
  3705. ASSERT_TRUE(res);
  3706. EXPECT_EQ(StatusCode::OK_200, res->status);
  3707. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3708. auto body = R"(<html>
  3709. <head>
  3710. </head>
  3711. <body>
  3712. <a href="/dir/test.html">Test</a>
  3713. <a href="/hi">hi</a>
  3714. </body>
  3715. </html>
  3716. )";
  3717. EXPECT_EQ(body, res->body);
  3718. }
  3719. TEST_F(ServerTest, GetMethodDirTest) {
  3720. auto res = cli_.Get("/dir/test.html");
  3721. ASSERT_TRUE(res);
  3722. EXPECT_EQ(StatusCode::OK_200, res->status);
  3723. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3724. EXPECT_EQ("test.html", res->body);
  3725. }
  3726. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3727. auto res = cli_.Get("/dir/../dir/test.html");
  3728. ASSERT_TRUE(res);
  3729. EXPECT_EQ(StatusCode::OK_200, res->status);
  3730. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3731. EXPECT_EQ("test.html", res->body);
  3732. }
  3733. TEST_F(ServerTest, GetMethodInvalidPath) {
  3734. auto res = cli_.Get("/dir/../test.html");
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3737. }
  3738. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3739. auto res = cli_.Get("/../www/dir/test.html");
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3742. }
  3743. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3744. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3745. ASSERT_TRUE(res);
  3746. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3747. }
  3748. TEST_F(ServerTest, GetMethodDirMountTest) {
  3749. auto res = cli_.Get("/mount/dir/test.html");
  3750. ASSERT_TRUE(res);
  3751. EXPECT_EQ(StatusCode::OK_200, res->status);
  3752. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3753. EXPECT_EQ("test.html", res->body);
  3754. }
  3755. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3756. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3760. EXPECT_EQ("test.html", res->body);
  3761. }
  3762. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3763. auto res = cli_.Get("/mount/dir/../test.html");
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3766. }
  3767. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3768. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3769. ASSERT_TRUE(res);
  3770. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3771. }
  3772. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3773. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3774. ASSERT_TRUE(res);
  3775. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3776. }
  3777. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3778. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3779. ASSERT_TRUE(res);
  3780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3781. }
  3782. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3783. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3784. ASSERT_TRUE(res);
  3785. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3786. }
  3787. TEST_F(ServerTest, PostMethod303) {
  3788. auto res = cli_.Post("/1", "body", "text/plain");
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3791. EXPECT_EQ("/2", res->get_header_value("Location"));
  3792. }
  3793. TEST_F(ServerTest, PostMethod303Redirect) {
  3794. cli_.set_follow_location(true);
  3795. auto res = cli_.Post("/1", "body", "text/plain");
  3796. ASSERT_TRUE(res);
  3797. EXPECT_EQ(StatusCode::OK_200, res->status);
  3798. EXPECT_EQ("redirected.", res->body);
  3799. EXPECT_EQ("/2", res->location);
  3800. }
  3801. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3802. auto res = cli_.Get("/dir/test.abcde");
  3803. ASSERT_TRUE(res);
  3804. EXPECT_EQ(StatusCode::OK_200, res->status);
  3805. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3806. EXPECT_EQ("abcde", res->body);
  3807. }
  3808. TEST_F(ServerTest, StaticFileRange) {
  3809. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3810. ASSERT_TRUE(res);
  3811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3812. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3813. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3814. EXPECT_EQ(true, res->has_header("Content-Range"));
  3815. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3816. EXPECT_EQ(std::string("cd"), res->body);
  3817. }
  3818. TEST_F(ServerTest, StaticFileRanges) {
  3819. auto res =
  3820. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3821. ASSERT_TRUE(res);
  3822. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3823. EXPECT_TRUE(
  3824. res->get_header_value("Content-Type")
  3825. .find(
  3826. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3827. 0);
  3828. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3829. }
  3830. TEST_F(ServerTest, StaticFileRangeHead) {
  3831. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3832. ASSERT_TRUE(res);
  3833. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3834. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3835. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3836. EXPECT_EQ(true, res->has_header("Content-Range"));
  3837. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3838. }
  3839. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3840. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3841. ASSERT_TRUE(res);
  3842. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3843. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3844. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3845. EXPECT_EQ(true, res->has_header("Content-Range"));
  3846. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3847. res->get_header_value("Content-Range"));
  3848. EXPECT_EQ("LAST\n", res->body);
  3849. }
  3850. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3851. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3855. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3856. EXPECT_EQ(true, res->has_header("Content-Range"));
  3857. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3858. }
  3859. TEST_F(ServerTest, StaticFileBigFile) {
  3860. auto res = cli_.Get("/dir/1MB.txt");
  3861. ASSERT_TRUE(res);
  3862. EXPECT_EQ(StatusCode::OK_200, res->status);
  3863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3864. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3865. }
  3866. TEST_F(ServerTest, InvalidBaseDirMount) {
  3867. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3868. }
  3869. TEST_F(ServerTest, Binary) {
  3870. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3871. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3872. "application/octet-stream");
  3873. ASSERT_TRUE(res);
  3874. ASSERT_EQ(StatusCode::OK_200, res->status);
  3875. ASSERT_EQ(4U, res->body.size());
  3876. res = cli_.Put("/binary", binary.data(), binary.size(),
  3877. "application/octet-stream");
  3878. ASSERT_TRUE(res);
  3879. ASSERT_EQ(StatusCode::OK_200, res->status);
  3880. ASSERT_EQ(4U, res->body.size());
  3881. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3882. "application/octet-stream");
  3883. ASSERT_TRUE(res);
  3884. ASSERT_EQ(StatusCode::OK_200, res->status);
  3885. ASSERT_EQ(4U, res->body.size());
  3886. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3887. "application/octet-stream");
  3888. ASSERT_TRUE(res);
  3889. ASSERT_EQ(StatusCode::OK_200, res->status);
  3890. ASSERT_EQ(4U, res->body.size());
  3891. }
  3892. TEST_F(ServerTest, BinaryString) {
  3893. auto binary = std::string("\x00\x01\x02\x03", 4);
  3894. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3895. ASSERT_TRUE(res);
  3896. ASSERT_EQ(StatusCode::OK_200, res->status);
  3897. ASSERT_EQ(4U, res->body.size());
  3898. res = cli_.Put("/binary", binary, "application/octet-stream");
  3899. ASSERT_TRUE(res);
  3900. ASSERT_EQ(StatusCode::OK_200, res->status);
  3901. ASSERT_EQ(4U, res->body.size());
  3902. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3903. ASSERT_TRUE(res);
  3904. ASSERT_EQ(StatusCode::OK_200, res->status);
  3905. ASSERT_EQ(4U, res->body.size());
  3906. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3907. ASSERT_TRUE(res);
  3908. ASSERT_EQ(StatusCode::OK_200, res->status);
  3909. ASSERT_EQ(4U, res->body.size());
  3910. }
  3911. TEST_F(ServerTest, EmptyRequest) {
  3912. auto res = cli_.Get("");
  3913. ASSERT_TRUE(!res);
  3914. EXPECT_EQ(Error::Connection, res.error());
  3915. }
  3916. TEST_F(ServerTest, LongRequest) {
  3917. std::string request;
  3918. for (size_t i = 0; i < 545; i++) {
  3919. request += "/TooLongRequest";
  3920. }
  3921. request += "OK";
  3922. auto res = cli_.Get(request.c_str());
  3923. ASSERT_TRUE(res);
  3924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3925. }
  3926. TEST_F(ServerTest, TooLongRequest) {
  3927. std::string request;
  3928. for (size_t i = 0; i < 546; i++) {
  3929. request += "/TooLongRequest";
  3930. }
  3931. request += "_NG";
  3932. auto start = std::chrono::high_resolution_clock::now();
  3933. cli_.set_keep_alive(true);
  3934. auto res = cli_.Get(request.c_str());
  3935. auto end = std::chrono::high_resolution_clock::now();
  3936. auto elapsed =
  3937. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3938. .count();
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3941. EXPECT_LE(elapsed, 1000);
  3942. EXPECT_EQ("close", res->get_header_value("Connection"));
  3943. EXPECT_FALSE(cli_.is_socket_open());
  3944. }
  3945. TEST_F(ServerTest, AlmostTooLongRequest) {
  3946. // test for #2046 - URI length check shouldn't include other content on req
  3947. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3948. // leading /, space, HTTP/1.1)
  3949. std::string request =
  3950. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3951. auto res = cli_.Get(request.c_str());
  3952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3953. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3954. }
  3955. TEST_F(ServerTest, LongHeader) {
  3956. Request req;
  3957. req.method = "GET";
  3958. req.path = "/hi";
  3959. std::string host_and_port;
  3960. host_and_port += HOST;
  3961. host_and_port += ":";
  3962. host_and_port += std::to_string(PORT);
  3963. req.headers.emplace("Host", host_and_port.c_str());
  3964. req.headers.emplace("Accept", "*/*");
  3965. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3966. req.headers.emplace(
  3967. "Header-Name",
  3968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3980. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3981. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3982. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3983. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3984. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3985. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3986. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3987. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3996. "@@@@@@@@@@@@@@@@");
  3997. auto res = std::make_shared<Response>();
  3998. auto error = Error::Success;
  3999. auto ret = cli_.send(req, *res, error);
  4000. ASSERT_TRUE(ret);
  4001. EXPECT_EQ(StatusCode::OK_200, res->status);
  4002. }
  4003. TEST_F(ServerTest, LongQueryValue) {
  4004. auto start = std::chrono::high_resolution_clock::now();
  4005. cli_.set_keep_alive(true);
  4006. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  4007. auto end = std::chrono::high_resolution_clock::now();
  4008. auto elapsed =
  4009. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  4010. .count();
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  4013. EXPECT_LE(elapsed, 1000);
  4014. EXPECT_EQ("close", res->get_header_value("Connection"));
  4015. EXPECT_FALSE(cli_.is_socket_open());
  4016. }
  4017. TEST_F(ServerTest, TooLongQueryValue) {
  4018. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  4019. ASSERT_FALSE(res);
  4020. EXPECT_EQ(Error::Read, res.error());
  4021. }
  4022. TEST_F(ServerTest, TooLongHeader) {
  4023. Request req;
  4024. req.method = "GET";
  4025. req.path = "/hi";
  4026. std::string host_and_port;
  4027. host_and_port += HOST;
  4028. host_and_port += ":";
  4029. host_and_port += std::to_string(PORT);
  4030. req.headers.emplace("Host", host_and_port.c_str());
  4031. req.headers.emplace("Accept", "*/*");
  4032. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4033. req.headers.emplace(
  4034. "Header-Name",
  4035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4056. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4057. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  4063. "@@@@@@@@@@@@@@@@@");
  4064. auto res = std::make_shared<Response>();
  4065. auto error = Error::Success;
  4066. auto ret = cli_.send(req, *res, error);
  4067. ASSERT_TRUE(ret);
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. }
  4070. TEST_F(ServerTest, HeaderCountAtLimit) {
  4071. // Test with headers just under the 100 limit
  4072. httplib::Headers headers;
  4073. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  4074. // This should keep us just under the 100 header limit
  4075. for (int i = 0; i < 95; i++) {
  4076. std::string name = "X-Test-Header-" + std::to_string(i);
  4077. std::string value = "value" + std::to_string(i);
  4078. headers.emplace(name, value);
  4079. }
  4080. // This should work fine as we're under the limit
  4081. auto res = cli_.Get("/hi", headers);
  4082. EXPECT_TRUE(res);
  4083. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  4084. }
  4085. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  4086. // Test with many headers to exceed the 100 limit
  4087. httplib::Headers headers;
  4088. // Add 150 headers to definitely exceed the 100 limit
  4089. for (int i = 0; i < 150; i++) {
  4090. std::string name = "X-Test-Header-" + std::to_string(i);
  4091. std::string value = "value" + std::to_string(i);
  4092. headers.emplace(name, value);
  4093. }
  4094. // This should fail due to exceeding header count limit
  4095. cli_.set_keep_alive(true);
  4096. auto res = cli_.Get("/hi", headers);
  4097. // The server should respond with 400 Bad Request
  4098. ASSERT_TRUE(res);
  4099. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4100. EXPECT_EQ("close", res->get_header_value("Connection"));
  4101. EXPECT_FALSE(cli_.is_socket_open());
  4102. }
  4103. TEST_F(ServerTest, PercentEncoding) {
  4104. auto res = cli_.Get("/e%6edwith%");
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::OK_200, res->status);
  4107. }
  4108. TEST_F(ServerTest, PercentEncodingUnicode) {
  4109. auto res = cli_.Get("/e%u006edwith%");
  4110. ASSERT_TRUE(res);
  4111. EXPECT_EQ(StatusCode::OK_200, res->status);
  4112. }
  4113. TEST_F(ServerTest, InvalidPercentEncoding) {
  4114. auto res = cli_.Get("/%endwith%");
  4115. ASSERT_TRUE(res);
  4116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4117. }
  4118. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  4119. auto res = cli_.Get("/%uendwith%");
  4120. ASSERT_TRUE(res);
  4121. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4122. }
  4123. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  4124. auto res = cli_.Get("/hello?aaa=bbb%");
  4125. ASSERT_TRUE(res);
  4126. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4127. }
  4128. TEST_F(ServerTest, PlusSignEncoding) {
  4129. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  4130. ASSERT_TRUE(res);
  4131. EXPECT_EQ(StatusCode::OK_200, res->status);
  4132. EXPECT_EQ("a +b", res->body);
  4133. }
  4134. TEST_F(ServerTest, HeaderCountSecurityTest) {
  4135. // This test simulates a potential DoS attack using many headers
  4136. // to verify our security fix prevents memory exhaustion
  4137. httplib::Headers attack_headers;
  4138. // Attempt to add many headers like an attacker would (200 headers to far
  4139. // exceed limit)
  4140. for (int i = 0; i < 200; i++) {
  4141. std::string name = "X-Attack-Header-" + std::to_string(i);
  4142. std::string value = "attack_payload_" + std::to_string(i);
  4143. attack_headers.emplace(name, value);
  4144. }
  4145. // Try to POST with excessive headers
  4146. cli_.set_keep_alive(true);
  4147. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  4148. // Should either fail or return 400 Bad Request due to security limit
  4149. if (res) {
  4150. // If we get a response, it should be 400 Bad Request
  4151. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4152. EXPECT_EQ("close", res->get_header_value("Connection"));
  4153. }
  4154. EXPECT_FALSE(cli_.is_socket_open());
  4155. }
  4156. TEST_F(ServerTest, MultipartFormData) {
  4157. UploadFormDataItems items = {
  4158. {"text1", "text default", "", ""},
  4159. {"text2", "aωb", "", ""},
  4160. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4161. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4162. {"file3", "", "", "application/octet-stream"},
  4163. {"file4", "", "", " application/json tmp-string "}};
  4164. auto res = cli_.Post("/multipart", items);
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::OK_200, res->status);
  4167. }
  4168. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4169. UploadFormDataItems items = {
  4170. {"text", "default text", "", ""},
  4171. {"multi_text1", "aaaaa", "", ""},
  4172. {"multi_text1", "bbbbb", "", ""},
  4173. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4174. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4175. "application/json"},
  4176. };
  4177. auto res = cli_.Post("/multipart/multi_file_values", items);
  4178. ASSERT_TRUE(res);
  4179. EXPECT_EQ(StatusCode::OK_200, res->status);
  4180. }
  4181. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4182. auto res = cli_.Get("/hi");
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::OK_200, res->status);
  4185. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4186. EXPECT_EQ("Hello World!", res->body);
  4187. }
  4188. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4189. Request req;
  4190. req.method = "POST";
  4191. req.path = "/chunked";
  4192. std::string host_and_port;
  4193. host_and_port += HOST;
  4194. host_and_port += ":";
  4195. host_and_port += std::to_string(PORT);
  4196. req.headers.emplace("Host", host_and_port.c_str());
  4197. req.headers.emplace("Accept", "*/*");
  4198. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4199. req.headers.emplace("Content-Type", "text/plain");
  4200. req.headers.emplace("Content-Length", "0");
  4201. req.headers.emplace(
  4202. "Transfer-Encoding",
  4203. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4204. // Client does not chunk, so make a chunked body manually.
  4205. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4206. auto res = std::make_shared<Response>();
  4207. auto error = Error::Success;
  4208. auto ret = cli_.send(req, *res, error);
  4209. ASSERT_TRUE(ret);
  4210. EXPECT_EQ(StatusCode::OK_200, res->status);
  4211. }
  4212. TEST_F(ServerTest, GetStreamed2) {
  4213. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4216. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4217. EXPECT_EQ(true, res->has_header("Content-Range"));
  4218. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4219. EXPECT_EQ(std::string("ab"), res->body);
  4220. }
  4221. TEST_F(ServerTest, GetStreamed) {
  4222. auto res = cli_.Get("/streamed");
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::OK_200, res->status);
  4225. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4226. EXPECT_EQ(std::string("aaabbb"), res->body);
  4227. }
  4228. TEST_F(ServerTest, GetStreamedWithRange1) {
  4229. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4232. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4233. EXPECT_EQ(true, res->has_header("Content-Range"));
  4234. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4235. EXPECT_EQ(std::string("def"), res->body);
  4236. }
  4237. TEST_F(ServerTest, GetStreamedWithRange2) {
  4238. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("bcdefg"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4247. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4250. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4251. EXPECT_EQ(true, res->has_header("Content-Range"));
  4252. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4253. EXPECT_EQ(std::string("efg"), res->body);
  4254. }
  4255. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4256. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4257. ASSERT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4259. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4260. EXPECT_EQ(false, res->has_header("Content-Range"));
  4261. EXPECT_EQ(0U, res->body.size());
  4262. }
  4263. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4264. auto res = cli_.Get("/streamed-with-range",
  4265. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4266. "92233720368547758079223372036854775807"}});
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4269. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4270. EXPECT_EQ(false, res->has_header("Content-Range"));
  4271. EXPECT_EQ(0U, res->body.size());
  4272. }
  4273. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4274. auto res = cli_.Get(
  4275. "/with-range",
  4276. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4277. {"Accept-Encoding", ""}});
  4278. ASSERT_TRUE(res);
  4279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4280. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4281. EXPECT_EQ(true, res->has_header("Content-Range"));
  4282. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4283. EXPECT_EQ(std::string("abcdefg"), res->body);
  4284. }
  4285. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4286. auto res = cli_.Get("/with-range", {
  4287. {"Range", "bytes=0-"},
  4288. {"Accept-Encoding", ""},
  4289. });
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4292. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4293. EXPECT_EQ(true, res->has_header("Content-Range"));
  4294. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4295. EXPECT_EQ(std::string("abcdefg"), res->body);
  4296. }
  4297. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4298. auto res =
  4299. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4300. ASSERT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4302. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4303. EXPECT_EQ(false, res->has_header("Content-Range"));
  4304. EXPECT_EQ(267U, res->body.size());
  4305. // Check that both range contents are present
  4306. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4307. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4308. // Check that Content-Range headers are present for both ranges
  4309. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4310. std::string::npos);
  4311. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4312. std::string::npos);
  4313. }
  4314. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4315. Ranges ranges;
  4316. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4317. ranges.emplace_back(0, -1);
  4318. }
  4319. auto res =
  4320. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4321. ASSERT_TRUE(res);
  4322. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4323. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4324. EXPECT_EQ(false, res->has_header("Content-Range"));
  4325. EXPECT_EQ(0U, res->body.size());
  4326. }
  4327. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4328. auto res =
  4329. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4330. ASSERT_TRUE(res);
  4331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4332. EXPECT_EQ(5U, res->body.size());
  4333. // Check that overlapping ranges are coalesced into a single range
  4334. EXPECT_EQ("bcdef", res->body);
  4335. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4336. // Should be single range, not multipart
  4337. EXPECT_TRUE(res->has_header("Content-Range"));
  4338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4339. }
  4340. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4341. auto res =
  4342. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4343. ASSERT_TRUE(res);
  4344. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4345. EXPECT_EQ(268U, res->body.size());
  4346. // Check that both range contents are present
  4347. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4348. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4349. // Check that Content-Range headers are present for both ranges
  4350. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4351. std::string::npos);
  4352. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4353. std::string::npos);
  4354. }
  4355. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4356. auto res =
  4357. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4358. ASSERT_TRUE(res);
  4359. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4360. EXPECT_EQ(269U, res->body.size());
  4361. // Check that both duplicate range contents are present
  4362. size_t first_abc = res->body.find("abc\r\n");
  4363. EXPECT_TRUE(first_abc != std::string::npos);
  4364. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4365. EXPECT_TRUE(second_abc != std::string::npos);
  4366. // Check that Content-Range headers are present for both ranges
  4367. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4368. EXPECT_TRUE(first_range != std::string::npos);
  4369. size_t second_range =
  4370. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4371. EXPECT_TRUE(second_range != std::string::npos);
  4372. }
  4373. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4374. auto res = cli_.Get("/streamed-with-range?error",
  4375. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4376. ASSERT_TRUE(res);
  4377. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4378. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4379. EXPECT_EQ(false, res->has_header("Content-Range"));
  4380. EXPECT_EQ(0U, res->body.size());
  4381. }
  4382. TEST_F(ServerTest, GetStreamedEndless) {
  4383. uint64_t offset = 0;
  4384. auto res = cli_.Get("/streamed-cancel",
  4385. [&](const char * /*data*/, uint64_t data_length) {
  4386. if (offset < 100) {
  4387. offset += data_length;
  4388. return true;
  4389. }
  4390. return false;
  4391. });
  4392. ASSERT_TRUE(!res);
  4393. EXPECT_EQ(Error::Canceled, res.error());
  4394. }
  4395. TEST_F(ServerTest, ClientStop) {
  4396. std::atomic_size_t count{4};
  4397. std::vector<std::thread> threads;
  4398. for (auto i = count.load(); i != 0; --i) {
  4399. threads.emplace_back([&]() {
  4400. auto res = cli_.Get("/streamed-cancel",
  4401. [&](const char *, uint64_t) { return true; });
  4402. --count;
  4403. ASSERT_TRUE(!res);
  4404. EXPECT_TRUE(res.error() == Error::Canceled ||
  4405. res.error() == Error::Read || res.error() == Error::Write);
  4406. });
  4407. }
  4408. std::this_thread::sleep_for(std::chrono::seconds(2));
  4409. while (count != 0) {
  4410. cli_.stop();
  4411. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4412. }
  4413. for (auto &t : threads) {
  4414. t.join();
  4415. }
  4416. }
  4417. TEST_F(ServerTest, GetWithRange1) {
  4418. auto res = cli_.Get("/with-range", {
  4419. make_range_header({{3, 5}}),
  4420. {"Accept-Encoding", ""},
  4421. });
  4422. ASSERT_TRUE(res);
  4423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4424. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4425. EXPECT_EQ(true, res->has_header("Content-Range"));
  4426. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4427. EXPECT_EQ(std::string("def"), res->body);
  4428. }
  4429. TEST_F(ServerTest, GetWithRange2) {
  4430. auto res = cli_.Get("/with-range", {
  4431. make_range_header({{1, -1}}),
  4432. {"Accept-Encoding", ""},
  4433. });
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4436. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4437. EXPECT_EQ(true, res->has_header("Content-Range"));
  4438. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4439. EXPECT_EQ(std::string("bcdefg"), res->body);
  4440. }
  4441. TEST_F(ServerTest, GetWithRange3) {
  4442. auto res = cli_.Get("/with-range", {
  4443. make_range_header({{0, 0}}),
  4444. {"Accept-Encoding", ""},
  4445. });
  4446. ASSERT_TRUE(res);
  4447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4448. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4449. EXPECT_EQ(true, res->has_header("Content-Range"));
  4450. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4451. EXPECT_EQ(std::string("a"), res->body);
  4452. }
  4453. TEST_F(ServerTest, GetWithRange4) {
  4454. auto res = cli_.Get("/with-range", {
  4455. make_range_header({{-1, 2}}),
  4456. {"Accept-Encoding", ""},
  4457. });
  4458. ASSERT_TRUE(res);
  4459. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4460. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4461. EXPECT_EQ(true, res->has_header("Content-Range"));
  4462. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4463. EXPECT_EQ(std::string("fg"), res->body);
  4464. }
  4465. TEST_F(ServerTest, GetWithRange5) {
  4466. auto res = cli_.Get("/with-range", {
  4467. make_range_header({{0, 5}}),
  4468. {"Accept-Encoding", ""},
  4469. });
  4470. ASSERT_TRUE(res);
  4471. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4472. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4473. EXPECT_EQ(true, res->has_header("Content-Range"));
  4474. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4475. EXPECT_EQ(std::string("abcdef"), res->body);
  4476. }
  4477. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4478. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4481. }
  4482. TEST_F(ServerTest, GetWithRangeMultipart) {
  4483. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4484. ASSERT_TRUE(res);
  4485. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4486. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4487. EXPECT_EQ(false, res->has_header("Content-Range"));
  4488. EXPECT_EQ(267U, res->body.size());
  4489. }
  4490. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4491. auto res =
  4492. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4493. ASSERT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4495. }
  4496. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4497. auto res = cli_.Get("/with-range-customized-response",
  4498. {{make_range_header({{1, 2}})}});
  4499. ASSERT_TRUE(res);
  4500. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4501. EXPECT_EQ(true, res->has_header("Content-Length"));
  4502. EXPECT_EQ(false, res->has_header("Content-Range"));
  4503. EXPECT_EQ(JSON_DATA, res->body);
  4504. }
  4505. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4506. auto res = cli_.Get("/with-range-customized-response",
  4507. {{make_range_header({{1, 2}, {4, 5}})}});
  4508. ASSERT_TRUE(res);
  4509. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4510. EXPECT_EQ(true, res->has_header("Content-Length"));
  4511. EXPECT_EQ(false, res->has_header("Content-Range"));
  4512. EXPECT_EQ(JSON_DATA, res->body);
  4513. }
  4514. TEST_F(ServerTest, Issue1772) {
  4515. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4516. ASSERT_TRUE(res);
  4517. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4518. }
  4519. TEST_F(ServerTest, Issue609) {
  4520. auto res = cli_.Delete("/issue609");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ(std::string("ok"), res->body);
  4524. }
  4525. TEST_F(ServerTest, GetStreamedChunked) {
  4526. auto res = cli_.Get("/streamed-chunked");
  4527. ASSERT_TRUE(res);
  4528. EXPECT_EQ(StatusCode::OK_200, res->status);
  4529. EXPECT_EQ(std::string("123456789"), res->body);
  4530. }
  4531. TEST_F(ServerTest, GetStreamedChunked2) {
  4532. auto res = cli_.Get("/streamed-chunked2");
  4533. ASSERT_TRUE(res);
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. EXPECT_EQ(std::string("123456789"), res->body);
  4536. }
  4537. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4538. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4539. ASSERT_TRUE(res);
  4540. EXPECT_EQ(StatusCode::OK_200, res->status);
  4541. EXPECT_EQ(std::string("123456789"), res->body);
  4542. EXPECT_TRUE(res->has_header("Trailer"));
  4543. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4544. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4545. // Trailers are now stored separately from headers (security fix)
  4546. EXPECT_EQ(2U, res->trailers.size());
  4547. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4548. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4549. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4550. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4551. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4552. // Verify trailers are NOT in headers (security verification)
  4553. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4554. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4555. }
  4556. TEST_F(ServerTest, LargeChunkedPost) {
  4557. Request req;
  4558. req.method = "POST";
  4559. req.path = "/large-chunked";
  4560. std::string host_and_port;
  4561. host_and_port += HOST;
  4562. host_and_port += ":";
  4563. host_and_port += std::to_string(PORT);
  4564. req.headers.emplace("Host", host_and_port.c_str());
  4565. req.headers.emplace("Accept", "*/*");
  4566. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4567. req.headers.emplace("Content-Type", "text/plain");
  4568. req.headers.emplace("Content-Length", "0");
  4569. req.headers.emplace("Transfer-Encoding", "chunked");
  4570. std::string long_string(30 * 1024u, 'a');
  4571. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4572. // Attempt to make a large enough post to exceed OS buffers, to test that
  4573. // the server handles short reads if the full chunk data isn't available.
  4574. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4575. auto res = std::make_shared<Response>();
  4576. auto error = Error::Success;
  4577. auto ret = cli_.send(req, *res, error);
  4578. ASSERT_TRUE(ret);
  4579. EXPECT_EQ(StatusCode::OK_200, res->status);
  4580. }
  4581. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4582. auto res = cli_.Get("/remote_addr");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4586. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4587. }
  4588. TEST_F(ServerTest, GetMethodLocalAddr) {
  4589. auto res = cli_.Get("/local_addr");
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4593. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4594. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4595. }
  4596. TEST_F(ServerTest, HTTPResponseSplitting) {
  4597. auto res = cli_.Get("/http_response_splitting");
  4598. ASSERT_TRUE(res);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. }
  4601. TEST_F(ServerTest, SlowRequest) {
  4602. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4603. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4604. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4605. }
  4606. #if 0
  4607. TEST_F(ServerTest, SlowPost) {
  4608. char buffer[64 * 1024];
  4609. memset(buffer, 0x42, sizeof(buffer));
  4610. auto res = cli_.Post(
  4611. "/slowpost", 64 * 1024 * 1024,
  4612. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4613. auto ret = sink.write(buffer, sizeof(buffer));
  4614. EXPECT_TRUE(ret);
  4615. return true;
  4616. },
  4617. "text/plain");
  4618. ASSERT_TRUE(res);
  4619. EXPECT_EQ(StatusCode::OK_200, res->status);
  4620. }
  4621. TEST_F(ServerTest, SlowPostFail) {
  4622. char buffer[64 * 1024];
  4623. memset(buffer, 0x42, sizeof(buffer));
  4624. cli_.set_write_timeout(std::chrono::seconds(0));
  4625. auto res = cli_.Post(
  4626. "/slowpost", 64 * 1024 * 1024,
  4627. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4628. sink.write(buffer, sizeof(buffer));
  4629. return true;
  4630. },
  4631. "text/plain");
  4632. ASSERT_TRUE(!res);
  4633. EXPECT_EQ(Error::Write, res.error());
  4634. }
  4635. #endif
  4636. TEST_F(ServerTest, Put) {
  4637. auto res = cli_.Put("/put", "PUT", "text/plain");
  4638. ASSERT_TRUE(res);
  4639. EXPECT_EQ(StatusCode::OK_200, res->status);
  4640. EXPECT_EQ("PUT", res->body);
  4641. }
  4642. TEST_F(ServerTest, PutWithContentProvider) {
  4643. auto res = cli_.Put(
  4644. "/put", 3,
  4645. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4646. sink.os << "PUT";
  4647. return true;
  4648. },
  4649. "text/plain");
  4650. ASSERT_TRUE(res);
  4651. EXPECT_EQ(StatusCode::OK_200, res->status);
  4652. EXPECT_EQ("PUT", res->body);
  4653. }
  4654. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4655. auto res = cli_.Post(
  4656. "/post", 42,
  4657. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4658. return false;
  4659. },
  4660. "text/plain");
  4661. ASSERT_TRUE(!res);
  4662. EXPECT_EQ(Error::Canceled, res.error());
  4663. }
  4664. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4665. auto res = cli_.Put(
  4666. "/put",
  4667. [](size_t /*offset*/, DataSink &sink) {
  4668. sink.os << "PUT";
  4669. sink.done();
  4670. return true;
  4671. },
  4672. "text/plain");
  4673. ASSERT_TRUE(res);
  4674. EXPECT_EQ(StatusCode::OK_200, res->status);
  4675. EXPECT_EQ("PUT", res->body);
  4676. }
  4677. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4678. auto res = cli_.Post(
  4679. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4680. "text/plain");
  4681. ASSERT_TRUE(!res);
  4682. EXPECT_EQ(Error::Canceled, res.error());
  4683. }
  4684. TEST_F(ServerTest, PostLoopBack) {
  4685. std::string body;
  4686. auto res = cli_.Post(
  4687. "/post-loopback", 9,
  4688. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4689. EXPECT_EQ(9u, length);
  4690. sink.write("123", 3);
  4691. sink.write("456", 3);
  4692. sink.write("789", 3);
  4693. return true;
  4694. },
  4695. "text/plain",
  4696. [&body](const char *data, size_t data_length) {
  4697. body.append(data, data_length);
  4698. return true;
  4699. });
  4700. ASSERT_TRUE(res);
  4701. EXPECT_EQ(StatusCode::OK_200, res->status);
  4702. EXPECT_EQ("123456789", body);
  4703. }
  4704. TEST_F(ServerTest, PutLoopBack) {
  4705. std::string body;
  4706. auto res = cli_.Put(
  4707. "/put-loopback", 9,
  4708. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4709. EXPECT_EQ(9u, length);
  4710. sink.write("123", 3);
  4711. sink.write("456", 3);
  4712. sink.write("789", 3);
  4713. return true;
  4714. },
  4715. "text/plain",
  4716. [&body](const char *data, size_t data_length) {
  4717. body.append(data, data_length);
  4718. return true;
  4719. });
  4720. ASSERT_TRUE(res);
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ("123456789", body);
  4723. }
  4724. TEST_F(ServerTest, PatchLoopBack) {
  4725. std::string body;
  4726. auto res = cli_.Patch(
  4727. "/patch-loopback", 9,
  4728. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4729. EXPECT_EQ(9u, length);
  4730. sink.write("123", 3);
  4731. sink.write("456", 3);
  4732. sink.write("789", 3);
  4733. return true;
  4734. },
  4735. "text/plain",
  4736. [&body](const char *data, size_t data_length) {
  4737. body.append(data, data_length);
  4738. return true;
  4739. });
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ(StatusCode::OK_200, res->status);
  4742. EXPECT_EQ("123456789", body);
  4743. }
  4744. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4745. std::string body;
  4746. auto res = cli_.Post(
  4747. "/post-loopback",
  4748. [](size_t /*offset*/, DataSink &sink) {
  4749. sink.write("123", 3);
  4750. sink.write("456", 3);
  4751. sink.write("789", 3);
  4752. sink.done();
  4753. return true;
  4754. },
  4755. "text/plain",
  4756. [&body](const char *data, size_t data_length) {
  4757. body.append(data, data_length);
  4758. return true;
  4759. });
  4760. ASSERT_TRUE(res);
  4761. EXPECT_EQ(StatusCode::OK_200, res->status);
  4762. EXPECT_EQ("123456789", body);
  4763. }
  4764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4765. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4766. cli_.set_compress(true);
  4767. auto res = cli_.Put(
  4768. "/put", 3,
  4769. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4770. sink.os << "PUT";
  4771. return true;
  4772. },
  4773. "text/plain");
  4774. ASSERT_TRUE(res);
  4775. EXPECT_EQ(StatusCode::OK_200, res->status);
  4776. EXPECT_EQ("PUT", res->body);
  4777. }
  4778. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4779. cli_.set_compress(true);
  4780. auto res = cli_.Post(
  4781. "/post", 42,
  4782. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4783. return false;
  4784. },
  4785. "text/plain");
  4786. ASSERT_TRUE(!res);
  4787. EXPECT_EQ(Error::Canceled, res.error());
  4788. }
  4789. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4790. cli_.set_compress(true);
  4791. auto res = cli_.Put(
  4792. "/put",
  4793. [](size_t /*offset*/, DataSink &sink) {
  4794. sink.os << "PUT";
  4795. sink.done();
  4796. return true;
  4797. },
  4798. "text/plain");
  4799. ASSERT_TRUE(res);
  4800. EXPECT_EQ(StatusCode::OK_200, res->status);
  4801. EXPECT_EQ("PUT", res->body);
  4802. }
  4803. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4804. cli_.set_compress(true);
  4805. auto res = cli_.Post(
  4806. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4807. "text/plain");
  4808. ASSERT_TRUE(!res);
  4809. EXPECT_EQ(Error::Canceled, res.error());
  4810. }
  4811. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4812. cli_.set_compress(true);
  4813. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4814. ASSERT_TRUE(res);
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. EXPECT_EQ(LARGE_DATA, res->body);
  4817. }
  4818. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4819. #ifdef CPPHTTPLIB_SSL_ENABLED
  4820. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4821. Client cli(s.c_str());
  4822. cli.enable_server_certificate_verification(false);
  4823. #else
  4824. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4825. Client cli(s.c_str());
  4826. #endif
  4827. cli.set_compress(true);
  4828. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4829. ASSERT_TRUE(res);
  4830. EXPECT_EQ(StatusCode::OK_200, res->status);
  4831. EXPECT_EQ(LARGE_DATA, res->body);
  4832. // The compressed size should be less than a 10th of the original. May vary
  4833. // depending on the zlib library.
  4834. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4835. static_cast<uint64_t>(10 * 1024 * 1024));
  4836. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4837. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  4838. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  4839. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4840. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  4841. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  4842. #endif
  4843. }
  4844. TEST_F(ServerTest, PutContentWithDeflate) {
  4845. cli_.set_compress(false);
  4846. Headers headers;
  4847. headers.emplace("Content-Encoding", "deflate");
  4848. // PUT in deflate format:
  4849. auto res = cli_.Put("/put", headers,
  4850. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4851. ASSERT_TRUE(res);
  4852. EXPECT_EQ(StatusCode::OK_200, res->status);
  4853. EXPECT_EQ("PUT", res->body);
  4854. }
  4855. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4856. Headers headers;
  4857. headers.emplace("Accept-Encoding", "gzip, deflate");
  4858. auto res = cli_.Get("/streamed-chunked", headers);
  4859. ASSERT_TRUE(res);
  4860. EXPECT_EQ(StatusCode::OK_200, res->status);
  4861. EXPECT_EQ(std::string("123456789"), res->body);
  4862. }
  4863. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4864. Headers headers;
  4865. headers.emplace("Accept-Encoding", "gzip, deflate");
  4866. auto res = cli_.Get("/streamed-chunked2", headers);
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. EXPECT_EQ(std::string("123456789"), res->body);
  4870. }
  4871. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4872. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::OK_200, res->status);
  4875. }
  4876. TEST(GzipDecompressor, ChunkedDecompression) {
  4877. std::string data;
  4878. for (size_t i = 0; i < 32 * 1024; ++i) {
  4879. data.push_back(static_cast<char>('a' + i % 26));
  4880. }
  4881. std::string compressed_data;
  4882. {
  4883. httplib::detail::gzip_compressor compressor;
  4884. bool result = compressor.compress(
  4885. data.data(), data.size(),
  4886. /*last=*/true,
  4887. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4888. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4889. compressed_data_size);
  4890. return true;
  4891. });
  4892. ASSERT_TRUE(result);
  4893. }
  4894. std::string decompressed_data;
  4895. {
  4896. httplib::detail::gzip_decompressor decompressor;
  4897. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4898. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4899. size_t chunk_size = 130;
  4900. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4901. chunk_begin += chunk_size) {
  4902. size_t current_chunk_size =
  4903. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4904. bool result = decompressor.decompress(
  4905. compressed_data.data() + chunk_begin, current_chunk_size,
  4906. [&](const char *decompressed_data_chunk,
  4907. size_t decompressed_data_chunk_size) {
  4908. decompressed_data.insert(decompressed_data.size(),
  4909. decompressed_data_chunk,
  4910. decompressed_data_chunk_size);
  4911. return true;
  4912. });
  4913. ASSERT_TRUE(result);
  4914. }
  4915. }
  4916. ASSERT_EQ(data, decompressed_data);
  4917. }
  4918. TEST(GzipDecompressor, DeflateDecompression) {
  4919. std::string original_text = "Raw deflate without gzip";
  4920. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4921. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4922. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4923. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4924. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4925. std::string decompressed_data;
  4926. {
  4927. httplib::detail::gzip_decompressor decompressor;
  4928. bool result = decompressor.decompress(
  4929. compressed_data.data(), compressed_data.size(),
  4930. [&](const char *decompressed_data_chunk,
  4931. size_t decompressed_data_chunk_size) {
  4932. decompressed_data.insert(decompressed_data.size(),
  4933. decompressed_data_chunk,
  4934. decompressed_data_chunk_size);
  4935. return true;
  4936. });
  4937. ASSERT_TRUE(result);
  4938. }
  4939. ASSERT_EQ(original_text, decompressed_data);
  4940. }
  4941. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4942. std::string original_text = "Raw deflate without gzip";
  4943. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4944. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4945. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4946. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4947. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4948. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4949. std::string decompressed_data;
  4950. {
  4951. httplib::detail::gzip_decompressor decompressor;
  4952. bool result = decompressor.decompress(
  4953. compressed_data.data(), compressed_data.size(),
  4954. [&](const char *decompressed_data_chunk,
  4955. size_t decompressed_data_chunk_size) {
  4956. decompressed_data.insert(decompressed_data.size(),
  4957. decompressed_data_chunk,
  4958. decompressed_data_chunk_size);
  4959. return true;
  4960. });
  4961. ASSERT_TRUE(result);
  4962. }
  4963. ASSERT_EQ(original_text, decompressed_data);
  4964. }
  4965. #endif
  4966. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4967. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4968. Headers headers;
  4969. headers.emplace("Accept-Encoding", "br");
  4970. auto res = cli_.Get("/streamed-chunked", headers);
  4971. ASSERT_TRUE(res);
  4972. EXPECT_EQ(StatusCode::OK_200, res->status);
  4973. EXPECT_EQ(std::string("123456789"), res->body);
  4974. }
  4975. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4976. Headers headers;
  4977. headers.emplace("Accept-Encoding", "br");
  4978. auto res = cli_.Get("/streamed-chunked2", headers);
  4979. ASSERT_TRUE(res);
  4980. EXPECT_EQ(StatusCode::OK_200, res->status);
  4981. EXPECT_EQ(std::string("123456789"), res->body);
  4982. }
  4983. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  4984. cli_.set_compress(true);
  4985. auto res = cli_.Put(
  4986. "/put", 3,
  4987. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4988. sink.os << "PUT";
  4989. return true;
  4990. },
  4991. "text/plain");
  4992. ASSERT_TRUE(res);
  4993. EXPECT_EQ(StatusCode::OK_200, res->status);
  4994. EXPECT_EQ("PUT", res->body);
  4995. }
  4996. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  4997. cli_.set_compress(true);
  4998. auto res = cli_.Put(
  4999. "/put",
  5000. [](size_t /*offset*/, DataSink &sink) {
  5001. sink.os << "PUT";
  5002. sink.done();
  5003. return true;
  5004. },
  5005. "text/plain");
  5006. ASSERT_TRUE(res);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. EXPECT_EQ("PUT", res->body);
  5009. }
  5010. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  5011. cli_.set_compress(true);
  5012. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  5013. ASSERT_TRUE(res);
  5014. EXPECT_EQ(StatusCode::OK_200, res->status);
  5015. EXPECT_EQ(LARGE_DATA, res->body);
  5016. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  5017. }
  5018. #endif
  5019. TEST_F(ServerTest, Patch) {
  5020. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  5021. ASSERT_TRUE(res);
  5022. EXPECT_EQ(StatusCode::OK_200, res->status);
  5023. EXPECT_EQ("PATCH", res->body);
  5024. }
  5025. TEST_F(ServerTest, Delete) {
  5026. auto res = cli_.Delete("/delete");
  5027. ASSERT_TRUE(res);
  5028. EXPECT_EQ(StatusCode::OK_200, res->status);
  5029. EXPECT_EQ("DELETE", res->body);
  5030. }
  5031. TEST_F(ServerTest, DeleteContentReceiver) {
  5032. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("content", res->body);
  5036. }
  5037. TEST_F(ServerTest, Options) {
  5038. auto res = cli_.Options("*");
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  5042. EXPECT_TRUE(res->body.empty());
  5043. }
  5044. TEST_F(ServerTest, URL) {
  5045. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  5046. ASSERT_TRUE(res);
  5047. EXPECT_EQ(StatusCode::OK_200, res->status);
  5048. }
  5049. TEST_F(ServerTest, ArrayParam) {
  5050. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  5051. ASSERT_TRUE(res);
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. }
  5054. TEST_F(ServerTest, ArrayParamValues) {
  5055. auto res =
  5056. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  5057. ASSERT_TRUE(res);
  5058. EXPECT_EQ(StatusCode::OK_200, res->status);
  5059. }
  5060. TEST_F(ServerTest, NoMultipleHeaders) {
  5061. Headers headers = {{"Content-Length", "5"}};
  5062. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  5063. "text/plain");
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ(StatusCode::OK_200, res->status);
  5066. }
  5067. TEST_F(ServerTest, PostContentReceiver) {
  5068. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5069. ASSERT_TRUE(res);
  5070. ASSERT_EQ(StatusCode::OK_200, res->status);
  5071. ASSERT_EQ("content", res->body);
  5072. }
  5073. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  5074. UploadFormDataItems items = {
  5075. {"text1", "text default", "", ""},
  5076. {"text2", "aωb", "", ""},
  5077. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5078. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5079. {"file3", "", "", "application/octet-stream"},
  5080. };
  5081. auto res = cli_.Post("/content_receiver", items);
  5082. ASSERT_TRUE(res);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. }
  5085. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  5086. UploadFormDataItems items = {
  5087. {"text1", "text default", "", ""},
  5088. {"text2", "aωb", "", ""},
  5089. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5090. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  5091. {"file3", "", "", "application/octet-stream"},
  5092. };
  5093. auto boundary = std::string("+++++");
  5094. std::string body;
  5095. for (const auto &item : items) {
  5096. body += "--" + boundary + "\r\n";
  5097. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  5098. if (!item.filename.empty()) {
  5099. body += "; filename=\"" + item.filename + "\"";
  5100. }
  5101. body += "\r\n";
  5102. if (!item.content_type.empty()) {
  5103. body += "Content-Type: " + item.content_type + "\r\n";
  5104. }
  5105. body += "\r\n";
  5106. body += item.content + "\r\n";
  5107. }
  5108. body += "--" + boundary + "--\r\n";
  5109. std::string content_type = "multipart/form-data; boundary=" + boundary;
  5110. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  5111. ASSERT_TRUE(res);
  5112. EXPECT_EQ(StatusCode::OK_200, res->status);
  5113. }
  5114. TEST_F(ServerTest, PostContentReceiverGzip) {
  5115. cli_.set_compress(true);
  5116. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  5117. ASSERT_TRUE(res);
  5118. ASSERT_EQ(StatusCode::OK_200, res->status);
  5119. ASSERT_EQ("content", res->body);
  5120. }
  5121. TEST_F(ServerTest, PutContentReceiver) {
  5122. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  5123. ASSERT_TRUE(res);
  5124. ASSERT_EQ(StatusCode::OK_200, res->status);
  5125. ASSERT_EQ("content", res->body);
  5126. }
  5127. TEST_F(ServerTest, PatchContentReceiver) {
  5128. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  5129. ASSERT_TRUE(res);
  5130. ASSERT_EQ(StatusCode::OK_200, res->status);
  5131. ASSERT_EQ("content", res->body);
  5132. }
  5133. template <typename ClientType>
  5134. void TestWithHeadersAndContentReceiver(
  5135. ClientType &cli,
  5136. std::function<Result(ClientType &, const std::string &, const Headers &,
  5137. const std::string &, const std::string &,
  5138. ContentReceiver, DownloadProgress)>
  5139. request_func) {
  5140. Headers headers;
  5141. headers.emplace("X-Custom-Header", "test-value");
  5142. std::string received_body;
  5143. auto res = request_func(
  5144. cli, "/content_receiver", headers, "content", "application/json",
  5145. [&](const char *data, size_t data_length) {
  5146. received_body.append(data, data_length);
  5147. return true;
  5148. },
  5149. nullptr);
  5150. ASSERT_TRUE(res);
  5151. EXPECT_EQ(StatusCode::OK_200, res->status);
  5152. EXPECT_EQ("content", received_body);
  5153. }
  5154. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  5155. #ifdef CPPHTTPLIB_SSL_ENABLED
  5156. using ClientT = SSLClient;
  5157. #else
  5158. using ClientT = Client;
  5159. #endif
  5160. TestWithHeadersAndContentReceiver<ClientT>(
  5161. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5162. const std::string &body, const std::string &content_type,
  5163. ContentReceiver receiver, DownloadProgress progress) {
  5164. return cli.Post(path, headers, body, content_type, receiver, progress);
  5165. });
  5166. }
  5167. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  5168. #ifdef CPPHTTPLIB_SSL_ENABLED
  5169. using ClientT = SSLClient;
  5170. #else
  5171. using ClientT = Client;
  5172. #endif
  5173. TestWithHeadersAndContentReceiver<ClientT>(
  5174. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5175. const std::string &body, const std::string &content_type,
  5176. ContentReceiver receiver, DownloadProgress progress) {
  5177. return cli.Put(path, headers, body, content_type, receiver, progress);
  5178. });
  5179. }
  5180. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5181. #ifdef CPPHTTPLIB_SSL_ENABLED
  5182. using ClientT = SSLClient;
  5183. #else
  5184. using ClientT = Client;
  5185. #endif
  5186. TestWithHeadersAndContentReceiver<ClientT>(
  5187. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5188. const std::string &body, const std::string &content_type,
  5189. ContentReceiver receiver, DownloadProgress progress) {
  5190. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5191. });
  5192. }
  5193. template <typename ClientType>
  5194. void TestWithHeadersAndContentReceiverWithProgress(
  5195. ClientType &cli,
  5196. std::function<Result(ClientType &, const std::string &, const Headers &,
  5197. const std::string &, const std::string &,
  5198. ContentReceiver, DownloadProgress)>
  5199. request_func) {
  5200. Headers headers;
  5201. headers.emplace("X-Test-Header", "progress-test");
  5202. std::string received_body;
  5203. auto progress_called = false;
  5204. auto res = request_func(
  5205. cli, "/content_receiver", headers, "content", "text/plain",
  5206. [&](const char *data, size_t data_length) {
  5207. received_body.append(data, data_length);
  5208. return true;
  5209. },
  5210. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5211. progress_called = true;
  5212. return true;
  5213. });
  5214. ASSERT_TRUE(res);
  5215. EXPECT_EQ(StatusCode::OK_200, res->status);
  5216. EXPECT_EQ("content", received_body);
  5217. EXPECT_TRUE(progress_called);
  5218. }
  5219. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5220. #ifdef CPPHTTPLIB_SSL_ENABLED
  5221. using ClientT = SSLClient;
  5222. #else
  5223. using ClientT = Client;
  5224. #endif
  5225. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5226. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5227. const std::string &body, const std::string &content_type,
  5228. ContentReceiver receiver, DownloadProgress progress) {
  5229. return cli.Post(path, headers, body, content_type, receiver, progress);
  5230. });
  5231. }
  5232. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5233. #ifdef CPPHTTPLIB_SSL_ENABLED
  5234. using ClientT = SSLClient;
  5235. #else
  5236. using ClientT = Client;
  5237. #endif
  5238. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5239. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5240. const std::string &body, const std::string &content_type,
  5241. ContentReceiver receiver, DownloadProgress progress) {
  5242. return cli.Put(path, headers, body, content_type, receiver, progress);
  5243. });
  5244. }
  5245. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5246. #ifdef CPPHTTPLIB_SSL_ENABLED
  5247. using ClientT = SSLClient;
  5248. #else
  5249. using ClientT = Client;
  5250. #endif
  5251. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5252. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5253. const std::string &body, const std::string &content_type,
  5254. ContentReceiver receiver, DownloadProgress progress) {
  5255. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5256. });
  5257. }
  5258. template <typename ClientType>
  5259. void TestWithHeadersAndContentReceiverError(
  5260. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5261. const Headers &, const std::string &,
  5262. const std::string &, ContentReceiver)>
  5263. request_func) {
  5264. Headers headers;
  5265. headers.emplace("X-Error-Test", "true");
  5266. std::string received_body;
  5267. auto receiver_failed = false;
  5268. auto res =
  5269. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5270. [&](const char *data, size_t data_length) {
  5271. received_body.append(data, data_length);
  5272. receiver_failed = true;
  5273. return false;
  5274. });
  5275. ASSERT_FALSE(res);
  5276. EXPECT_TRUE(receiver_failed);
  5277. }
  5278. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5279. #ifdef CPPHTTPLIB_SSL_ENABLED
  5280. using ClientT = SSLClient;
  5281. #else
  5282. using ClientT = Client;
  5283. #endif
  5284. TestWithHeadersAndContentReceiverError<ClientT>(
  5285. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5286. const std::string &body, const std::string &content_type,
  5287. ContentReceiver receiver) {
  5288. return cli.Post(path, headers, body, content_type, receiver);
  5289. });
  5290. }
  5291. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5292. #ifdef CPPHTTPLIB_SSL_ENABLED
  5293. using ClientT = SSLClient;
  5294. #else
  5295. using ClientT = Client;
  5296. #endif
  5297. TestWithHeadersAndContentReceiverError<ClientT>(
  5298. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5299. const std::string &body, const std::string &content_type,
  5300. ContentReceiver receiver) {
  5301. return cli.Put(path, headers, body, content_type, receiver);
  5302. });
  5303. }
  5304. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5305. #ifdef CPPHTTPLIB_SSL_ENABLED
  5306. using ClientT = SSLClient;
  5307. #else
  5308. using ClientT = Client;
  5309. #endif
  5310. TestWithHeadersAndContentReceiverError<ClientT>(
  5311. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5312. const std::string &body, const std::string &content_type,
  5313. ContentReceiver receiver) {
  5314. return cli.Patch(path, headers, body, content_type, receiver);
  5315. });
  5316. }
  5317. TEST_F(ServerTest, PostQueryStringAndBody) {
  5318. auto res =
  5319. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5320. ASSERT_TRUE(res);
  5321. ASSERT_EQ(StatusCode::OK_200, res->status);
  5322. }
  5323. TEST_F(ServerTest, HTTP2Magic) {
  5324. Request req;
  5325. req.method = "PRI";
  5326. req.path = "*";
  5327. req.body = "SM";
  5328. auto res = std::make_shared<Response>();
  5329. auto error = Error::Success;
  5330. auto ret = cli_.send(req, *res, error);
  5331. ASSERT_TRUE(ret);
  5332. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5333. }
  5334. TEST_F(ServerTest, KeepAlive) {
  5335. auto res = cli_.Get("/hi");
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ(StatusCode::OK_200, res->status);
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("Hello World!", res->body);
  5340. res = cli_.Get("/hi");
  5341. ASSERT_TRUE(res);
  5342. EXPECT_EQ(StatusCode::OK_200, res->status);
  5343. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5344. EXPECT_EQ("Hello World!", res->body);
  5345. res = cli_.Get("/hi");
  5346. ASSERT_TRUE(res);
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5349. EXPECT_EQ("Hello World!", res->body);
  5350. res = cli_.Get("/not-exist");
  5351. ASSERT_TRUE(res);
  5352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5353. res = cli_.Post("/empty", "", "text/plain");
  5354. ASSERT_TRUE(res);
  5355. EXPECT_EQ(StatusCode::OK_200, res->status);
  5356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5357. EXPECT_EQ("empty", res->body);
  5358. EXPECT_EQ("close", res->get_header_value("Connection"));
  5359. res = cli_.Post(
  5360. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5361. "text/plain");
  5362. ASSERT_TRUE(res);
  5363. EXPECT_EQ(StatusCode::OK_200, res->status);
  5364. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ("empty", res->body);
  5366. cli_.set_keep_alive(false);
  5367. res = cli_.Get("/last-request");
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(StatusCode::OK_200, res->status);
  5370. EXPECT_EQ("close", res->get_header_value("Connection"));
  5371. }
  5372. TEST_F(ServerTest, TooManyRedirect) {
  5373. cli_.set_follow_location(true);
  5374. auto res = cli_.Get("/redirect/0");
  5375. ASSERT_TRUE(!res);
  5376. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5377. }
  5378. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5379. Request req;
  5380. req.method = "FOOBAR";
  5381. req.path = "/hi";
  5382. cli_.set_keep_alive(true);
  5383. auto res = cli_.send(req);
  5384. ASSERT_TRUE(res);
  5385. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5386. EXPECT_EQ("close", res->get_header_value("Connection"));
  5387. EXPECT_FALSE(cli_.is_socket_open());
  5388. }
  5389. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5391. TEST_F(ServerTest, Gzip) {
  5392. Headers headers;
  5393. headers.emplace("Accept-Encoding", "gzip, deflate");
  5394. auto res = cli_.Get("/compress", headers);
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5400. "7890123456789012345678901234567890",
  5401. res->body);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  5405. Headers headers;
  5406. headers.emplace("Accept-Encoding", "gzip, deflate");
  5407. auto res = cli_.Get("/compress-with-charset", headers);
  5408. ASSERT_TRUE(res);
  5409. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5410. EXPECT_EQ("application/json; charset=utf-8",
  5411. res->get_header_value("Content-Type"));
  5412. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5413. "7890123456789012345678901234567890",
  5414. res->body);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "");
  5420. auto res = cli_.Get("/compress", headers);
  5421. ASSERT_TRUE(res);
  5422. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5423. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5424. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5425. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5426. "7890123456789012345678901234567890",
  5427. res->body);
  5428. EXPECT_EQ(StatusCode::OK_200, res->status);
  5429. }
  5430. TEST_F(ServerTest, GzipWithContentReceiver) {
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "gzip, deflate");
  5433. std::string body;
  5434. auto res = cli_.Get("/compress", headers,
  5435. [&](const char *data, uint64_t data_length) {
  5436. EXPECT_EQ(100U, data_length);
  5437. body.append(data, data_length);
  5438. return true;
  5439. });
  5440. ASSERT_TRUE(res);
  5441. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5442. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5443. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5445. "7890123456789012345678901234567890",
  5446. body);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. }
  5449. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5450. Headers headers;
  5451. headers.emplace("Accept-Encoding", "gzip, deflate");
  5452. cli_.set_decompress(false);
  5453. auto res = cli_.Get("/compress", headers);
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5457. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5458. EXPECT_EQ(33U, res->body.size());
  5459. EXPECT_EQ(StatusCode::OK_200, res->status);
  5460. }
  5461. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5462. Headers headers;
  5463. headers.emplace("Accept-Encoding", "");
  5464. std::string body;
  5465. auto res = cli_.Get("/compress", headers,
  5466. [&](const char *data, uint64_t data_length) {
  5467. EXPECT_EQ(100U, data_length);
  5468. body.append(data, data_length);
  5469. return true;
  5470. });
  5471. ASSERT_TRUE(res);
  5472. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5473. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5474. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5475. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5476. "7890123456789012345678901234567890",
  5477. body);
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. }
  5480. TEST_F(ServerTest, NoGzip) {
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "gzip, deflate");
  5483. auto res = cli_.Get("/nocompress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5486. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5488. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5489. "7890123456789012345678901234567890",
  5490. res->body);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. }
  5493. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5494. Headers headers;
  5495. headers.emplace("Accept-Encoding", "gzip, deflate");
  5496. std::string body;
  5497. auto res = cli_.Get("/nocompress", headers,
  5498. [&](const char *data, uint64_t data_length) {
  5499. EXPECT_EQ(100U, data_length);
  5500. body.append(data, data_length);
  5501. return true;
  5502. });
  5503. ASSERT_TRUE(res);
  5504. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5505. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5506. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5507. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5508. "7890123456789012345678901234567890",
  5509. body);
  5510. EXPECT_EQ(StatusCode::OK_200, res->status);
  5511. }
  5512. TEST_F(ServerTest, MultipartFormDataGzip) {
  5513. UploadFormDataItems items = {
  5514. {"key1", "test", "", ""},
  5515. {"key2", "--abcdefg123", "", ""},
  5516. };
  5517. cli_.set_compress(true);
  5518. auto res = cli_.Post("/compress-multipart", items);
  5519. ASSERT_TRUE(res);
  5520. EXPECT_EQ(StatusCode::OK_200, res->status);
  5521. }
  5522. #endif
  5523. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5524. TEST_F(ServerTest, Brotli) {
  5525. Headers headers;
  5526. headers.emplace("Accept-Encoding", "br");
  5527. auto res = cli_.Get("/compress", headers);
  5528. ASSERT_TRUE(res);
  5529. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5531. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5532. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5533. "7890123456789012345678901234567890",
  5534. res->body);
  5535. EXPECT_EQ(StatusCode::OK_200, res->status);
  5536. }
  5537. #endif
  5538. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5539. TEST_F(ServerTest, Zstd) {
  5540. Headers headers;
  5541. headers.emplace("Accept-Encoding", "zstd");
  5542. auto res = cli_.Get("/compress", headers);
  5543. ASSERT_TRUE(res);
  5544. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5545. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5546. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5547. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5548. "7890123456789012345678901234567890",
  5549. res->body);
  5550. EXPECT_EQ(StatusCode::OK_200, res->status);
  5551. }
  5552. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5553. Headers headers;
  5554. headers.emplace("Accept-Encoding", "");
  5555. auto res = cli_.Get("/compress", headers);
  5556. ASSERT_TRUE(res);
  5557. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5558. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5559. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5560. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5561. "7890123456789012345678901234567890",
  5562. res->body);
  5563. EXPECT_EQ(StatusCode::OK_200, res->status);
  5564. }
  5565. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5566. Headers headers;
  5567. headers.emplace("Accept-Encoding", "zstd");
  5568. std::string body;
  5569. auto res = cli_.Get("/compress", headers,
  5570. [&](const char *data, uint64_t data_length) {
  5571. EXPECT_EQ(100U, data_length);
  5572. body.append(data, data_length);
  5573. return true;
  5574. });
  5575. ASSERT_TRUE(res);
  5576. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5577. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5578. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5579. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5580. "7890123456789012345678901234567890",
  5581. body);
  5582. EXPECT_EQ(StatusCode::OK_200, res->status);
  5583. }
  5584. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5585. Headers headers;
  5586. headers.emplace("Accept-Encoding", "zstd");
  5587. cli_.set_decompress(false);
  5588. auto res = cli_.Get("/compress", headers);
  5589. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5590. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5591. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5592. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5593. ASSERT_TRUE(res);
  5594. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5596. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. ASSERT_EQ(26U, res->body.size());
  5599. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5600. 0);
  5601. }
  5602. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5603. Headers headers;
  5604. headers.emplace("Accept-Encoding", "");
  5605. std::string body;
  5606. auto res = cli_.Get("/compress", headers,
  5607. [&](const char *data, uint64_t data_length) {
  5608. EXPECT_EQ(100U, data_length);
  5609. body.append(data, data_length);
  5610. return true;
  5611. });
  5612. ASSERT_TRUE(res);
  5613. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5615. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5616. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5617. "7890123456789012345678901234567890",
  5618. body);
  5619. EXPECT_EQ(StatusCode::OK_200, res->status);
  5620. }
  5621. TEST_F(ServerTest, NoZstd) {
  5622. Headers headers;
  5623. headers.emplace("Accept-Encoding", "zstd");
  5624. auto res = cli_.Get("/nocompress", headers);
  5625. ASSERT_TRUE(res);
  5626. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5627. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5628. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5629. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5630. "7890123456789012345678901234567890",
  5631. res->body);
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. }
  5634. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5635. Headers headers;
  5636. headers.emplace("Accept-Encoding", "zstd");
  5637. std::string body;
  5638. auto res = cli_.Get("/nocompress", headers,
  5639. [&](const char *data, uint64_t data_length) {
  5640. EXPECT_EQ(100U, data_length);
  5641. body.append(data, data_length);
  5642. return true;
  5643. });
  5644. ASSERT_TRUE(res);
  5645. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5646. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5647. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5648. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5649. "7890123456789012345678901234567890",
  5650. body);
  5651. EXPECT_EQ(StatusCode::OK_200, res->status);
  5652. }
  5653. // TODO: How to enable zstd ??
  5654. TEST_F(ServerTest, MultipartFormDataZstd) {
  5655. UploadFormDataItems items = {
  5656. {"key1", "test", "", ""},
  5657. {"key2", "--abcdefg123", "", ""},
  5658. };
  5659. Headers headers;
  5660. headers.emplace("Accept-Encoding", "zstd");
  5661. cli_.set_compress(true);
  5662. auto res = cli_.Post("/compress-multipart", headers, items);
  5663. ASSERT_TRUE(res);
  5664. EXPECT_EQ(StatusCode::OK_200, res->status);
  5665. }
  5666. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5667. Headers headers;
  5668. headers.emplace("Accept-Encoding", "zstd");
  5669. cli_.set_compress(true);
  5670. auto res = cli_.Put(
  5671. "/put", headers, 3,
  5672. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5673. sink.os << "PUT";
  5674. return true;
  5675. },
  5676. "text/plain");
  5677. ASSERT_TRUE(res);
  5678. EXPECT_EQ(StatusCode::OK_200, res->status);
  5679. EXPECT_EQ("PUT", res->body);
  5680. }
  5681. // Pre-compression logging tests
  5682. TEST_F(ServerTest, PreCompressionLogging) {
  5683. // Test data for compression (matches the actual /compress endpoint content)
  5684. const std::string test_content =
  5685. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5686. "3456789012345678901234567890";
  5687. // Variables to capture logging data
  5688. std::string pre_compression_body;
  5689. std::string pre_compression_content_type;
  5690. std::string pre_compression_content_encoding;
  5691. std::string post_compression_body;
  5692. std::string post_compression_content_type;
  5693. std::string post_compression_content_encoding;
  5694. // Set up pre-compression logger
  5695. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5696. const Response &res) {
  5697. pre_compression_body = res.body;
  5698. pre_compression_content_type = res.get_header_value("Content-Type");
  5699. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5700. });
  5701. // Set up post-compression logger
  5702. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5703. post_compression_body = res.body;
  5704. post_compression_content_type = res.get_header_value("Content-Type");
  5705. post_compression_content_encoding =
  5706. res.get_header_value("Content-Encoding");
  5707. });
  5708. // Test with gzip compression
  5709. Headers headers;
  5710. headers.emplace("Accept-Encoding", "gzip");
  5711. auto res = cli_.Get("/compress", headers);
  5712. // Verify response was compressed
  5713. ASSERT_TRUE(res);
  5714. EXPECT_EQ(StatusCode::OK_200, res->status);
  5715. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5716. // Verify pre-compression logger captured uncompressed content
  5717. EXPECT_EQ(test_content, pre_compression_body);
  5718. EXPECT_EQ("text/plain", pre_compression_content_type);
  5719. EXPECT_TRUE(pre_compression_content_encoding
  5720. .empty()); // No encoding header before compression
  5721. // Verify post-compression logger captured compressed content
  5722. EXPECT_NE(test_content,
  5723. post_compression_body); // Should be different after compression
  5724. EXPECT_EQ("text/plain", post_compression_content_type);
  5725. EXPECT_EQ("gzip", post_compression_content_encoding);
  5726. // Verify compressed content is smaller
  5727. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5728. }
  5729. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5730. const std::string test_content =
  5731. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5732. "3456789012345678901234567890";
  5733. std::string pre_compression_body;
  5734. std::string post_compression_body;
  5735. svr_.set_pre_compression_logger(
  5736. [&](const Request & /*req*/, const Response &res) {
  5737. pre_compression_body = res.body;
  5738. });
  5739. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5740. post_compression_body = res.body;
  5741. });
  5742. Headers headers;
  5743. headers.emplace("Accept-Encoding", "br");
  5744. auto res = cli_.Get("/compress", headers);
  5745. ASSERT_TRUE(res);
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5748. // Verify pre-compression content is uncompressed
  5749. EXPECT_EQ(test_content, pre_compression_body);
  5750. // Verify post-compression content is compressed
  5751. EXPECT_NE(test_content, post_compression_body);
  5752. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5753. }
  5754. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5755. const std::string test_content =
  5756. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5757. "3456789012345678901234567890";
  5758. std::string pre_compression_body;
  5759. std::string post_compression_body;
  5760. svr_.set_pre_compression_logger(
  5761. [&](const Request & /*req*/, const Response &res) {
  5762. pre_compression_body = res.body;
  5763. });
  5764. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5765. post_compression_body = res.body;
  5766. });
  5767. // Request without compression (use /nocompress endpoint)
  5768. Headers headers;
  5769. auto res = cli_.Get("/nocompress", headers);
  5770. ASSERT_TRUE(res);
  5771. EXPECT_EQ(StatusCode::OK_200, res->status);
  5772. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5773. // Pre-compression logger should not be called when no compression is applied
  5774. EXPECT_TRUE(
  5775. pre_compression_body.empty()); // Pre-compression logger not called
  5776. EXPECT_EQ(
  5777. test_content,
  5778. post_compression_body); // Post-compression logger captures final content
  5779. }
  5780. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5781. const std::string test_content =
  5782. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5783. "3456789012345678901234567890";
  5784. std::string pre_compression_body;
  5785. bool pre_logger_called = false;
  5786. // Set only pre-compression logger
  5787. svr_.set_pre_compression_logger(
  5788. [&](const Request & /*req*/, const Response &res) {
  5789. pre_compression_body = res.body;
  5790. pre_logger_called = true;
  5791. });
  5792. Headers headers;
  5793. headers.emplace("Accept-Encoding", "gzip");
  5794. auto res = cli_.Get("/compress", headers);
  5795. ASSERT_TRUE(res);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5798. // Verify pre-compression logger was called
  5799. EXPECT_TRUE(pre_logger_called);
  5800. EXPECT_EQ(test_content, pre_compression_body);
  5801. }
  5802. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5803. {
  5804. // Test with Expect: 100-continue header - success case
  5805. // Server returns 100 Continue, client sends body, server returns 200 OK
  5806. Request req;
  5807. req.method = "POST";
  5808. req.path = "/post-large";
  5809. req.set_header("Expect", "100-continue");
  5810. req.body = LARGE_DATA;
  5811. Response res;
  5812. auto error = Error::Success;
  5813. cli_.set_keep_alive(true);
  5814. auto ret = cli_.send(req, res, error);
  5815. EXPECT_TRUE(ret);
  5816. EXPECT_EQ(StatusCode::OK_200, res.status);
  5817. EXPECT_EQ(LARGE_DATA, res.body);
  5818. }
  5819. {
  5820. // Test with Expect: 100-continue header - error case
  5821. // Client should not send the body when server returns an error
  5822. Request req;
  5823. req.method = "POST";
  5824. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5825. req.set_header("Expect", "100-continue");
  5826. req.body = LARGE_DATA;
  5827. Response res;
  5828. auto error = Error::Success;
  5829. auto start = std::chrono::high_resolution_clock::now();
  5830. cli_.set_keep_alive(true);
  5831. auto ret = cli_.send(req, res, error);
  5832. auto end = std::chrono::high_resolution_clock::now();
  5833. auto elapsed =
  5834. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5835. .count();
  5836. // With Expect: 100-continue, request completes successfully but with error
  5837. EXPECT_TRUE(ret);
  5838. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5839. EXPECT_EQ("close", res.get_header_value("Connection"));
  5840. EXPECT_FALSE(cli_.is_socket_open());
  5841. EXPECT_LE(elapsed, 200);
  5842. }
  5843. {
  5844. // Send an extra GET request to ensure error recovery without hanging
  5845. Request req;
  5846. req.method = "GET";
  5847. req.path = "/hi";
  5848. auto start = std::chrono::high_resolution_clock::now();
  5849. auto res = cli_.send(req);
  5850. auto end = std::chrono::high_resolution_clock::now();
  5851. auto elapsed =
  5852. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5853. .count();
  5854. ASSERT_TRUE(res);
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("Hello World!", res->body);
  5857. EXPECT_LE(elapsed, 500);
  5858. }
  5859. }
  5860. TEST(ZstdDecompressor, ChunkedDecompression) {
  5861. std::string data;
  5862. for (size_t i = 0; i < 32 * 1024; ++i) {
  5863. data.push_back(static_cast<char>('a' + i % 26));
  5864. }
  5865. std::string compressed_data;
  5866. {
  5867. httplib::detail::zstd_compressor compressor;
  5868. bool result = compressor.compress(
  5869. data.data(), data.size(),
  5870. /*last=*/true,
  5871. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5872. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5873. compressed_data_size);
  5874. return true;
  5875. });
  5876. ASSERT_TRUE(result);
  5877. }
  5878. std::string decompressed_data;
  5879. {
  5880. httplib::detail::zstd_decompressor decompressor;
  5881. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5882. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5883. size_t chunk_size = 130;
  5884. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5885. chunk_begin += chunk_size) {
  5886. size_t current_chunk_size =
  5887. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5888. bool result = decompressor.decompress(
  5889. compressed_data.data() + chunk_begin, current_chunk_size,
  5890. [&](const char *decompressed_data_chunk,
  5891. size_t decompressed_data_chunk_size) {
  5892. decompressed_data.insert(decompressed_data.size(),
  5893. decompressed_data_chunk,
  5894. decompressed_data_chunk_size);
  5895. return true;
  5896. });
  5897. ASSERT_TRUE(result);
  5898. }
  5899. }
  5900. ASSERT_EQ(data, decompressed_data);
  5901. }
  5902. TEST(ZstdDecompressor, Decompress) {
  5903. std::string original_text = "Compressed with ZSTD";
  5904. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5905. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5906. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5907. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5908. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5909. std::string decompressed_data;
  5910. {
  5911. httplib::detail::zstd_decompressor decompressor;
  5912. bool result = decompressor.decompress(
  5913. compressed_data.data(), compressed_data.size(),
  5914. [&](const char *decompressed_data_chunk,
  5915. size_t decompressed_data_chunk_size) {
  5916. decompressed_data.insert(decompressed_data.size(),
  5917. decompressed_data_chunk,
  5918. decompressed_data_chunk_size);
  5919. return true;
  5920. });
  5921. ASSERT_TRUE(result);
  5922. }
  5923. ASSERT_EQ(original_text, decompressed_data);
  5924. }
  5925. #endif
  5926. // Sends a raw request to a server listening at HOST:PORT.
  5927. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5928. std::string *resp = nullptr) {
  5929. auto error = Error::Success;
  5930. auto client_sock = detail::create_client_socket(
  5931. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5932. /*connection_timeout_sec=*/5, 0,
  5933. /*read_timeout_sec=*/5, 0,
  5934. /*write_timeout_sec=*/5, 0, std::string(), error);
  5935. if (client_sock == INVALID_SOCKET) { return false; }
  5936. auto ret = detail::process_client_socket(
  5937. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5938. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5939. if (req.size() !=
  5940. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5941. return false;
  5942. }
  5943. char buf[512];
  5944. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5945. while (line_reader.getline()) {
  5946. if (resp) { *resp += line_reader.ptr(); }
  5947. }
  5948. return true;
  5949. });
  5950. detail::close_socket(client_sock);
  5951. return ret;
  5952. }
  5953. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5954. Server svr;
  5955. std::string header_value;
  5956. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5957. header_value = req.get_header_value("foo");
  5958. res.set_content("ok", "text/plain");
  5959. });
  5960. thread t = thread([&] { svr.listen(HOST, PORT); });
  5961. auto se = detail::scope_exit([&] {
  5962. svr.stop();
  5963. t.join();
  5964. ASSERT_FALSE(svr.is_running());
  5965. });
  5966. svr.wait_until_ready();
  5967. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5968. // like characters are not treated the same - use vertical tab and escape.
  5969. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5970. "foo: \t \v bar \x1B\t \r\n"
  5971. "Connection: close\r\n"
  5972. "\r\n";
  5973. std::string res;
  5974. ASSERT_TRUE(send_request(5, req, &res));
  5975. EXPECT_EQ(header_value, "");
  5976. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5977. }
  5978. // Sends a raw request and verifies that there isn't a crash or exception.
  5979. static void test_raw_request(const std::string &req,
  5980. std::string *out = nullptr) {
  5981. Server svr;
  5982. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5983. res.set_content("ok", "text/plain");
  5984. });
  5985. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5986. res.set_content("ok", "text/plain");
  5987. });
  5988. svr.Get("/header_field_value_check",
  5989. [&](const Request & /*req*/, Response &res) {
  5990. res.set_content("ok", "text/plain");
  5991. });
  5992. // Server read timeout must be longer than the client read timeout for the
  5993. // bug to reproduce, probably to force the server to process a request
  5994. // without a trailing blank line.
  5995. const time_t client_read_timeout_sec = 1;
  5996. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5997. bool listen_thread_ok = false;
  5998. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5999. auto se = detail::scope_exit([&] {
  6000. svr.stop();
  6001. t.join();
  6002. ASSERT_FALSE(svr.is_running());
  6003. EXPECT_TRUE(listen_thread_ok);
  6004. });
  6005. svr.wait_until_ready();
  6006. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  6007. }
  6008. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  6009. // A certain header line causes an exception if the header property is parsed
  6010. // naively with a single regex. This occurs with libc++ but not libstdc++.
  6011. test_raw_request(
  6012. "GET /hi HTTP/1.1\r\n"
  6013. " : "
  6014. " "
  6015. " ");
  6016. }
  6017. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  6018. // A certain header line causes an exception if the header property *name* is
  6019. // parsed with a regular expression starting with "(.+?):" - this is a non-
  6020. // greedy matcher and requires backtracking when there are a lot of ":"
  6021. // characters.
  6022. // This occurs with libc++ but not libstdc++.
  6023. test_raw_request(
  6024. "GET /hi HTTP/1.1\r\n"
  6025. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  6026. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6027. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  6028. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  6029. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  6030. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  6031. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  6032. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  6033. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6034. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6035. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  6036. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6037. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  6038. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  6039. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  6040. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  6041. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  6042. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  6043. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  6044. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  6045. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  6046. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  6047. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  6048. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  6049. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  6050. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  6051. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  6052. "&&&%%%");
  6053. }
  6054. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  6055. // Make sure this doesn't crash the server.
  6056. // In a previous version of the header line regex, the "\r" rendered the line
  6057. // unparsable and the regex engine repeatedly backtracked, trying to look for
  6058. // a new position where the leading white space ended and the field value
  6059. // began.
  6060. // The crash occurs with libc++ but not libstdc++.
  6061. test_raw_request("GET /hi HTTP/1.1\r\n"
  6062. "a:" +
  6063. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  6064. "\r\n"
  6065. "\r\n");
  6066. }
  6067. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  6068. std::string out;
  6069. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6070. "Content-Type: text/plain\r\n"
  6071. "Transfer-Encoding: chunked\r\n"
  6072. "\r\n"
  6073. "nothex\r\n",
  6074. &out);
  6075. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6076. }
  6077. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  6078. std::string out;
  6079. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6080. "Content-Type: text/plain\r\n"
  6081. "Transfer-Encoding: chunked\r\n"
  6082. "\r\n"
  6083. "3\r\n"
  6084. "xyz\r\n"
  6085. "NaN\r\n",
  6086. &out);
  6087. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6088. }
  6089. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  6090. std::string out;
  6091. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  6092. "Content-Type: text/plain\r\n"
  6093. "Transfer-Encoding: chunked\r\n"
  6094. "\r\n"
  6095. // Length is too large for 64 bits.
  6096. "1ffffffffffffffff\r\n"
  6097. "xyz\r\n",
  6098. &out);
  6099. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6100. }
  6101. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  6102. test_raw_request("GET /hi HTTP/1.1\r\n"
  6103. "Content-Type: text/plain\r\n\r");
  6104. }
  6105. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  6106. std::string out;
  6107. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  6108. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6109. }
  6110. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  6111. Server svr;
  6112. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  6113. EXPECT_TRUE(!req.remote_addr.empty());
  6114. });
  6115. thread t = thread([&] { svr.listen(HOST, PORT); });
  6116. auto se = detail::scope_exit([&] {
  6117. svr.stop();
  6118. t.join();
  6119. ASSERT_FALSE(svr.is_running());
  6120. });
  6121. svr.wait_until_ready();
  6122. // Send an invalid request line to trigger Bad Request
  6123. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  6124. std::string out;
  6125. ASSERT_TRUE(send_request(5, bad_req, &out));
  6126. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6127. }
  6128. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  6129. std::string out;
  6130. std::string request(
  6131. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  6132. test_raw_request(request, &out);
  6133. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6134. }
  6135. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  6136. std::string out;
  6137. std::string request(
  6138. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  6139. test_raw_request(request, &out);
  6140. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6141. }
  6142. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  6143. std::string out;
  6144. std::string request(
  6145. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  6146. test_raw_request(request, &out);
  6147. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  6148. }
  6149. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  6150. std::string out;
  6151. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  6152. "Test: \r\n\r\n",
  6153. &out);
  6154. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  6155. }
  6156. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  6157. Server svr;
  6158. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  6159. res.set_header("Cache-Control", "no-cache");
  6160. res.set_chunked_content_provider(
  6161. "text/event-stream", [](size_t offset, DataSink &sink) {
  6162. std::string s = "data:";
  6163. s += std::to_string(offset);
  6164. s += "\n\n";
  6165. auto ret = sink.write(s.data(), s.size());
  6166. EXPECT_TRUE(ret);
  6167. std::this_thread::sleep_for(std::chrono::seconds(1));
  6168. return true;
  6169. });
  6170. });
  6171. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6172. svr.wait_until_ready();
  6173. Client client(HOST, PORT);
  6174. const Headers headers = {{"Accept", "text/event-stream"}};
  6175. auto get_thread = std::thread([&client, &headers]() {
  6176. auto res = client.Get(
  6177. "/events", headers,
  6178. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  6179. });
  6180. auto se = detail::scope_exit([&] {
  6181. svr.stop();
  6182. get_thread.join();
  6183. listen_thread.join();
  6184. ASSERT_FALSE(svr.is_running());
  6185. });
  6186. // Give GET time to get a few messages.
  6187. std::this_thread::sleep_for(std::chrono::seconds(2));
  6188. }
  6189. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6190. httplib::Server svr;
  6191. svr.Post("/hi",
  6192. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6193. res.status = StatusCode::OK_200;
  6194. });
  6195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6196. svr.wait_until_ready();
  6197. Client cli(HOST, PORT);
  6198. auto res = cli.Post("/hi", "data", "text/plain");
  6199. ASSERT_TRUE(res);
  6200. EXPECT_EQ(StatusCode::OK_200, res->status);
  6201. svr.stop();
  6202. thread.join();
  6203. ASSERT_FALSE(svr.is_running());
  6204. res = cli.Post("/hi", "data", "text/plain");
  6205. ASSERT_FALSE(res);
  6206. }
  6207. TEST(ServerStopTest, ListenFailure) {
  6208. Server svr;
  6209. auto t = thread([&]() {
  6210. auto ret = svr.listen("????", PORT);
  6211. EXPECT_FALSE(ret);
  6212. });
  6213. svr.wait_until_ready();
  6214. svr.stop();
  6215. t.join();
  6216. }
  6217. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6218. TEST(ServerStopTest, Decommision) {
  6219. Server svr;
  6220. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6221. for (int i = 0; i < 4; i++) {
  6222. auto is_even = !(i % 2);
  6223. std::thread t{[&] {
  6224. try {
  6225. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6226. if (is_even) {
  6227. throw std::runtime_error("Some thing that happens to go wrong.");
  6228. }
  6229. svr.listen(HOST, PORT);
  6230. } catch (...) { svr.decommission(); }
  6231. }};
  6232. svr.wait_until_ready();
  6233. // Server is up
  6234. {
  6235. Client cli(HOST, PORT);
  6236. auto res = cli.Get("/hi");
  6237. if (is_even) {
  6238. EXPECT_FALSE(res);
  6239. } else {
  6240. EXPECT_TRUE(res);
  6241. EXPECT_EQ("hi...", res->body);
  6242. }
  6243. }
  6244. svr.stop();
  6245. t.join();
  6246. // Server is down...
  6247. {
  6248. Client cli(HOST, PORT);
  6249. auto res = cli.Get("/hi");
  6250. EXPECT_FALSE(res);
  6251. }
  6252. }
  6253. }
  6254. #endif
  6255. // Helper function for string body upload progress tests
  6256. template <typename SetupHandler, typename ClientCall>
  6257. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6258. ClientCall &&client_call,
  6259. const string &body) {
  6260. Server svr;
  6261. setup_handler(svr);
  6262. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6263. auto se = detail::scope_exit([&] {
  6264. svr.stop();
  6265. t.join();
  6266. });
  6267. svr.wait_until_ready();
  6268. Client cli(HOST, PORT);
  6269. vector<uint64_t> progress_values;
  6270. bool progress_called = false;
  6271. auto res =
  6272. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6273. progress_values.push_back(current);
  6274. progress_called = true;
  6275. return true;
  6276. });
  6277. ASSERT_TRUE(res);
  6278. EXPECT_EQ(200, res->status);
  6279. EXPECT_TRUE(progress_called);
  6280. }
  6281. TEST(UploadProgressTest, PostStringBodyBasic) {
  6282. TestStringBodyUploadProgress(
  6283. [](Server &svr) {
  6284. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6285. res.set_content("received", "text/plain");
  6286. });
  6287. },
  6288. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6289. return cli.Post("/test", body, "text/plain", progress_callback);
  6290. },
  6291. "test data for upload progress");
  6292. }
  6293. TEST(UploadProgressTest, PutStringBodyBasic) {
  6294. TestStringBodyUploadProgress(
  6295. [](Server &svr) {
  6296. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6297. res.set_content("put received", "text/plain");
  6298. });
  6299. },
  6300. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6301. return cli.Put("/test", body, "text/plain", progress_callback);
  6302. },
  6303. "put test data for upload progress");
  6304. }
  6305. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6306. TestStringBodyUploadProgress(
  6307. [](Server &svr) {
  6308. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6309. res.set_content("patch received", "text/plain");
  6310. });
  6311. },
  6312. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6313. return cli.Patch("/test", body, "text/plain", progress_callback);
  6314. },
  6315. "patch test data for upload progress");
  6316. }
  6317. // Helper function for content provider upload progress tests
  6318. template <typename SetupHandler, typename ClientCall>
  6319. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6320. ClientCall &&client_call) {
  6321. Server svr;
  6322. setup_handler(svr);
  6323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6324. auto se = detail::scope_exit([&] {
  6325. svr.stop();
  6326. t.join();
  6327. });
  6328. svr.wait_until_ready();
  6329. Client cli(HOST, PORT);
  6330. vector<uint64_t> progress_values;
  6331. auto res =
  6332. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6333. progress_values.push_back(current);
  6334. return true;
  6335. });
  6336. ASSERT_TRUE(res);
  6337. EXPECT_EQ(200, res->status);
  6338. EXPECT_FALSE(progress_values.empty());
  6339. }
  6340. TEST(UploadProgressTest, PostContentProviderProgress) {
  6341. TestContentProviderUploadProgress(
  6342. [](Server &svr) {
  6343. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6344. res.set_content("provider received", "text/plain");
  6345. });
  6346. },
  6347. [](Client &cli, UploadProgress progress_callback) {
  6348. return cli.Post(
  6349. "/test", 10,
  6350. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6351. sink.os << "test data";
  6352. return true;
  6353. },
  6354. "text/plain", progress_callback);
  6355. });
  6356. }
  6357. // Helper function for multipart upload progress tests
  6358. template <typename SetupHandler, typename ClientCall>
  6359. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6360. ClientCall &&client_call,
  6361. const string &endpoint) {
  6362. Server svr;
  6363. setup_handler(svr);
  6364. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6365. auto se = detail::scope_exit([&] {
  6366. svr.stop();
  6367. t.join();
  6368. });
  6369. svr.wait_until_ready();
  6370. Client cli(HOST, PORT);
  6371. vector<uint64_t> progress_values;
  6372. UploadFormDataItems items = {
  6373. {"field1", "value1", "", ""},
  6374. {"field2", "longer value for progress tracking test", "", ""},
  6375. {"file1", "file content data for upload progress", "test.txt",
  6376. "text/plain"}};
  6377. auto res = client_call(cli, endpoint, items,
  6378. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6379. progress_values.push_back(current);
  6380. return true;
  6381. });
  6382. ASSERT_TRUE(res);
  6383. EXPECT_EQ(200, res->status);
  6384. EXPECT_FALSE(progress_values.empty());
  6385. }
  6386. TEST(UploadProgressTest, PostMultipartProgress) {
  6387. TestMultipartUploadProgress(
  6388. [](Server &svr) {
  6389. svr.Post("/multipart", [](const Request &req, Response &res) {
  6390. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6391. res.set_content("multipart received", "text/plain");
  6392. });
  6393. },
  6394. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6395. UploadProgress progress_callback) {
  6396. return cli.Post(endpoint, items, progress_callback);
  6397. },
  6398. "/multipart");
  6399. }
  6400. // Helper function for basic download progress tests
  6401. template <typename SetupHandler, typename ClientCall>
  6402. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6403. ClientCall &&client_call, const string &endpoint,
  6404. size_t expected_content_size) {
  6405. Server svr;
  6406. setup_handler(svr);
  6407. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6408. auto se = detail::scope_exit([&] {
  6409. svr.stop();
  6410. t.join();
  6411. });
  6412. svr.wait_until_ready();
  6413. Client cli(HOST, PORT);
  6414. vector<uint64_t> progress_values;
  6415. auto res = client_call(cli, endpoint,
  6416. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6417. progress_values.push_back(current);
  6418. return true;
  6419. });
  6420. ASSERT_TRUE(res);
  6421. EXPECT_EQ(200, res->status);
  6422. EXPECT_FALSE(progress_values.empty());
  6423. EXPECT_EQ(expected_content_size, res->body.size());
  6424. }
  6425. TEST(DownloadProgressTest, GetBasic) {
  6426. TestBasicDownloadProgress(
  6427. [](Server &svr) {
  6428. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6429. string content(1000, 'D');
  6430. res.set_content(content, "text/plain");
  6431. });
  6432. },
  6433. [](Client &cli, const string &endpoint,
  6434. DownloadProgress progress_callback) {
  6435. return cli.Get(endpoint, progress_callback);
  6436. },
  6437. "/download", 1000u);
  6438. }
  6439. // Helper function for content receiver download progress tests
  6440. template <typename SetupHandler, typename ClientCall>
  6441. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6442. ClientCall &&client_call,
  6443. const string &endpoint,
  6444. size_t expected_content_size) {
  6445. Server svr;
  6446. setup_handler(svr);
  6447. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6448. auto se = detail::scope_exit([&] {
  6449. svr.stop();
  6450. t.join();
  6451. });
  6452. svr.wait_until_ready();
  6453. Client cli(HOST, PORT);
  6454. vector<uint64_t> progress_values;
  6455. string received_body;
  6456. auto res = client_call(
  6457. cli, endpoint,
  6458. [&](const char *data, size_t data_length) -> bool {
  6459. received_body.append(data, data_length);
  6460. return true;
  6461. },
  6462. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6463. progress_values.push_back(current);
  6464. return true;
  6465. });
  6466. ASSERT_TRUE(res);
  6467. EXPECT_EQ(200, res->status);
  6468. EXPECT_FALSE(progress_values.empty());
  6469. EXPECT_EQ(expected_content_size, received_body.size());
  6470. EXPECT_TRUE(res->body.empty());
  6471. }
  6472. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6473. TestContentReceiverDownloadProgress(
  6474. [](Server &svr) {
  6475. svr.Get("/download-receiver",
  6476. [](const Request & /*req*/, Response &res) {
  6477. string content(2000, 'R');
  6478. res.set_content(content, "text/plain");
  6479. });
  6480. },
  6481. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6482. DownloadProgress progress_callback) {
  6483. return cli.Get(endpoint, content_receiver, progress_callback);
  6484. },
  6485. "/download-receiver", 2000u);
  6486. }
  6487. TEST(StreamingTest, NoContentLengthStreaming) {
  6488. Server svr;
  6489. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6490. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6491. if (offset < 6) {
  6492. sink.os << (offset < 3 ? "a" : "b");
  6493. } else {
  6494. sink.done();
  6495. }
  6496. return true;
  6497. });
  6498. });
  6499. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6500. auto listen_se = detail::scope_exit([&] {
  6501. svr.stop();
  6502. listen_thread.join();
  6503. ASSERT_FALSE(svr.is_running());
  6504. });
  6505. svr.wait_until_ready();
  6506. Client client(HOST, PORT);
  6507. auto get_thread = std::thread([&client]() {
  6508. std::string s;
  6509. auto res =
  6510. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6511. s += std::string(data, len);
  6512. return true;
  6513. });
  6514. ASSERT_TRUE(res);
  6515. EXPECT_EQ(StatusCode::OK_200, res->status);
  6516. EXPECT_EQ("aaabbb", s);
  6517. });
  6518. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6519. // Give GET time to get a few messages.
  6520. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6521. }
  6522. TEST(MountTest, Unmount) {
  6523. Server svr;
  6524. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6525. auto se = detail::scope_exit([&] {
  6526. svr.stop();
  6527. listen_thread.join();
  6528. ASSERT_FALSE(svr.is_running());
  6529. });
  6530. svr.wait_until_ready();
  6531. Client cli("localhost", PORT);
  6532. svr.set_mount_point("/mount2", "./www2");
  6533. auto res = cli.Get("/");
  6534. ASSERT_TRUE(res);
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. res = cli.Get("/mount2/dir/test.html");
  6537. ASSERT_TRUE(res);
  6538. EXPECT_EQ(StatusCode::OK_200, res->status);
  6539. svr.set_mount_point("/", "./www");
  6540. res = cli.Get("/dir/");
  6541. ASSERT_TRUE(res);
  6542. EXPECT_EQ(StatusCode::OK_200, res->status);
  6543. svr.remove_mount_point("/");
  6544. res = cli.Get("/dir/");
  6545. ASSERT_TRUE(res);
  6546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6547. svr.remove_mount_point("/mount2");
  6548. res = cli.Get("/mount2/dir/test.html");
  6549. ASSERT_TRUE(res);
  6550. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6551. }
  6552. TEST(MountTest, Redicect) {
  6553. Server svr;
  6554. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6555. auto se = detail::scope_exit([&] {
  6556. svr.stop();
  6557. listen_thread.join();
  6558. ASSERT_FALSE(svr.is_running());
  6559. });
  6560. svr.set_mount_point("/", "./www");
  6561. svr.wait_until_ready();
  6562. Client cli("localhost", PORT);
  6563. auto res = cli.Get("/dir/");
  6564. ASSERT_TRUE(res);
  6565. EXPECT_EQ(StatusCode::OK_200, res->status);
  6566. res = cli.Get("/dir");
  6567. ASSERT_TRUE(res);
  6568. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6569. res = cli.Get("/file");
  6570. ASSERT_TRUE(res);
  6571. EXPECT_EQ(StatusCode::OK_200, res->status);
  6572. res = cli.Get("/file/");
  6573. ASSERT_TRUE(res);
  6574. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6575. cli.set_follow_location(true);
  6576. res = cli.Get("/dir");
  6577. ASSERT_TRUE(res);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. }
  6580. TEST(MountTest, MultibytesPathName) {
  6581. Server svr;
  6582. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6583. auto se = detail::scope_exit([&] {
  6584. svr.stop();
  6585. listen_thread.join();
  6586. ASSERT_FALSE(svr.is_running());
  6587. });
  6588. svr.set_mount_point("/", "./www");
  6589. svr.wait_until_ready();
  6590. Client cli("localhost", PORT);
  6591. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6592. ASSERT_TRUE(res);
  6593. EXPECT_EQ(StatusCode::OK_200, res->status);
  6594. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6595. }
  6596. TEST(KeepAliveTest, ReadTimeout) {
  6597. Server svr;
  6598. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6599. std::this_thread::sleep_for(std::chrono::seconds(2));
  6600. res.set_content("a", "text/plain");
  6601. });
  6602. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6603. res.set_content("b", "text/plain");
  6604. });
  6605. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6606. auto se = detail::scope_exit([&] {
  6607. svr.stop();
  6608. listen_thread.join();
  6609. ASSERT_FALSE(svr.is_running());
  6610. });
  6611. svr.wait_until_ready();
  6612. Client cli("localhost", PORT);
  6613. cli.set_keep_alive(true);
  6614. cli.set_read_timeout(std::chrono::seconds(1));
  6615. auto resa = cli.Get("/a");
  6616. ASSERT_FALSE(resa);
  6617. EXPECT_EQ(Error::Read, resa.error());
  6618. auto resb = cli.Get("/b");
  6619. ASSERT_TRUE(resb);
  6620. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6621. EXPECT_EQ("b", resb->body);
  6622. }
  6623. TEST(KeepAliveTest, MaxCount) {
  6624. size_t keep_alive_max_count = 3;
  6625. Server svr;
  6626. svr.set_keep_alive_max_count(keep_alive_max_count);
  6627. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6628. res.set_content("Hello World!", "text/plain");
  6629. });
  6630. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6631. auto se = detail::scope_exit([&] {
  6632. svr.stop();
  6633. listen_thread.join();
  6634. ASSERT_FALSE(svr.is_running());
  6635. });
  6636. svr.wait_until_ready();
  6637. Client cli(HOST, PORT);
  6638. cli.set_keep_alive(true);
  6639. for (size_t i = 0; i < 5; i++) {
  6640. auto result = cli.Get("/hi");
  6641. ASSERT_TRUE(result);
  6642. EXPECT_EQ(StatusCode::OK_200, result->status);
  6643. if (i == keep_alive_max_count - 1) {
  6644. EXPECT_EQ("close", result->get_header_value("Connection"));
  6645. } else {
  6646. EXPECT_FALSE(result->has_header("Connection"));
  6647. }
  6648. }
  6649. }
  6650. TEST(KeepAliveTest, Issue1041) {
  6651. Server svr;
  6652. svr.set_keep_alive_timeout(3);
  6653. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6654. res.set_content("Hello World!", "text/plain");
  6655. });
  6656. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6657. auto se = detail::scope_exit([&] {
  6658. svr.stop();
  6659. listen_thread.join();
  6660. ASSERT_FALSE(svr.is_running());
  6661. });
  6662. svr.wait_until_ready();
  6663. Client cli(HOST, PORT);
  6664. cli.set_keep_alive(true);
  6665. auto result = cli.Get("/hi");
  6666. ASSERT_TRUE(result);
  6667. EXPECT_EQ(StatusCode::OK_200, result->status);
  6668. std::this_thread::sleep_for(std::chrono::seconds(5));
  6669. result = cli.Get("/hi");
  6670. ASSERT_TRUE(result);
  6671. EXPECT_EQ(StatusCode::OK_200, result->status);
  6672. }
  6673. TEST(KeepAliveTest, Issue1959) {
  6674. Server svr;
  6675. svr.set_keep_alive_timeout(5);
  6676. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6677. res.set_content("a", "text/plain");
  6678. });
  6679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6680. auto se = detail::scope_exit([&] {
  6681. if (!svr.is_running()) return;
  6682. svr.stop();
  6683. listen_thread.join();
  6684. ASSERT_FALSE(svr.is_running());
  6685. });
  6686. svr.wait_until_ready();
  6687. Client cli("localhost", PORT);
  6688. cli.set_keep_alive(true);
  6689. using namespace std::chrono;
  6690. auto start = steady_clock::now();
  6691. cli.Get("/a");
  6692. svr.stop();
  6693. listen_thread.join();
  6694. auto end = steady_clock::now();
  6695. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6696. EXPECT_LT(elapsed, 5000);
  6697. }
  6698. #ifdef CPPHTTPLIB_SSL_ENABLED
  6699. TEST(KeepAliveTest, SSLClientReconnection) {
  6700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6701. ASSERT_TRUE(svr.is_valid());
  6702. svr.set_keep_alive_timeout(1);
  6703. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6704. res.set_content("Hello World!", "text/plain");
  6705. });
  6706. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6707. auto se = detail::scope_exit([&] {
  6708. svr.stop();
  6709. listen_thread.join();
  6710. ASSERT_FALSE(svr.is_running());
  6711. });
  6712. svr.wait_until_ready();
  6713. SSLClient cli(HOST, PORT);
  6714. cli.enable_server_certificate_verification(false);
  6715. cli.set_keep_alive(true);
  6716. auto result = cli.Get("/hi");
  6717. ASSERT_TRUE(result);
  6718. EXPECT_EQ(StatusCode::OK_200, result->status);
  6719. result = cli.Get("/hi");
  6720. ASSERT_TRUE(result);
  6721. EXPECT_EQ(StatusCode::OK_200, result->status);
  6722. std::this_thread::sleep_for(std::chrono::seconds(2));
  6723. // Recoonect
  6724. result = cli.Get("/hi");
  6725. ASSERT_TRUE(result);
  6726. EXPECT_EQ(StatusCode::OK_200, result->status);
  6727. result = cli.Get("/hi");
  6728. ASSERT_TRUE(result);
  6729. EXPECT_EQ(StatusCode::OK_200, result->status);
  6730. }
  6731. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6733. ASSERT_TRUE(svr.is_valid());
  6734. svr.set_keep_alive_timeout(1);
  6735. std::string content = "reconnect";
  6736. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6737. res.set_content("Hello World!", "text/plain");
  6738. });
  6739. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6740. auto se = detail::scope_exit([&] {
  6741. svr.stop();
  6742. listen_thread.join();
  6743. ASSERT_FALSE(svr.is_running());
  6744. });
  6745. svr.wait_until_ready();
  6746. SSLClient cli(HOST, PORT);
  6747. cli.enable_server_certificate_verification(false);
  6748. cli.set_keep_alive(true);
  6749. auto result = cli.Post(
  6750. "/hi", content.size(),
  6751. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6752. sink.write(content.c_str(), content.size());
  6753. return true;
  6754. },
  6755. "text/plain");
  6756. ASSERT_TRUE(result);
  6757. EXPECT_EQ(200, result->status);
  6758. std::this_thread::sleep_for(std::chrono::seconds(2));
  6759. // Recoonect
  6760. result = cli.Post(
  6761. "/hi", content.size(),
  6762. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6763. sink.write(content.c_str(), content.size());
  6764. return true;
  6765. },
  6766. "text/plain");
  6767. ASSERT_TRUE(result);
  6768. EXPECT_EQ(200, result->status);
  6769. result = cli.Post(
  6770. "/hi", content.size(),
  6771. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6772. sink.write(content.c_str(), content.size());
  6773. return true;
  6774. },
  6775. "text/plain");
  6776. ASSERT_TRUE(result);
  6777. EXPECT_EQ(200, result->status);
  6778. }
  6779. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6780. using namespace httplib::tls;
  6781. {
  6782. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6783. ASSERT_TRUE(svr.is_valid());
  6784. svr.Get("/sni", [&](const Request &req, Response &res) {
  6785. std::string expected = req.sni();
  6786. EXPECT_EQ(expected, req.get_param_value("expected"));
  6787. res.set_content("ok", "text/plain");
  6788. });
  6789. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6790. auto se = detail::scope_exit([&] {
  6791. svr.stop();
  6792. listen_thread.join();
  6793. ASSERT_FALSE(svr.is_running());
  6794. });
  6795. svr.wait_until_ready();
  6796. {
  6797. SSLClient cli("localhost", PORT);
  6798. cli.enable_server_certificate_verification(false);
  6799. auto res = cli.Get("/sni?expected=localhost");
  6800. ASSERT_TRUE(res);
  6801. }
  6802. {
  6803. SSLClient cli("::1", PORT);
  6804. cli.enable_server_certificate_verification(false);
  6805. auto res = cli.Get("/sni?expected=");
  6806. // NOTE: This may fail if the server is listening on IPv4 only
  6807. // (e.g., when localhost resolves to 127.0.0.1 only)
  6808. if (res) {
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. } else {
  6811. EXPECT_EQ(Error::Connection, res.error());
  6812. }
  6813. }
  6814. }
  6815. }
  6816. #endif
  6817. TEST(ClientProblemDetectionTest, ContentProvider) {
  6818. Server svr;
  6819. size_t content_length = 1024 * 1024;
  6820. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6821. res.set_content_provider(
  6822. content_length, "text/plain",
  6823. [&](size_t offset, size_t length, DataSink &sink) {
  6824. auto out_len = std::min(length, static_cast<size_t>(1024));
  6825. std::string out(out_len, '@');
  6826. sink.write(out.data(), out_len);
  6827. return offset < 4096;
  6828. },
  6829. [](bool success) { ASSERT_FALSE(success); });
  6830. });
  6831. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6832. res.set_content_provider(
  6833. 0, "text/plain",
  6834. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6835. EXPECT_TRUE(false);
  6836. return true;
  6837. },
  6838. [](bool success) { ASSERT_FALSE(success); });
  6839. });
  6840. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6841. auto se = detail::scope_exit([&] {
  6842. svr.stop();
  6843. listen_thread.join();
  6844. ASSERT_FALSE(svr.is_running());
  6845. });
  6846. svr.wait_until_ready();
  6847. Client cli("localhost", PORT);
  6848. {
  6849. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6850. size_t /*data_length*/) { return false; });
  6851. ASSERT_FALSE(res);
  6852. }
  6853. {
  6854. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6855. size_t /*data_length*/) { return false; });
  6856. ASSERT_TRUE(res);
  6857. }
  6858. }
  6859. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6860. Server svr;
  6861. svr.set_error_handler([](Request const &, Response &res) -> void {
  6862. res.set_chunked_content_provider(
  6863. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6864. sink.os << "hello";
  6865. sink.os << "world";
  6866. sink.done();
  6867. return true;
  6868. });
  6869. });
  6870. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6871. auto se = detail::scope_exit([&] {
  6872. svr.stop();
  6873. listen_thread.join();
  6874. ASSERT_FALSE(svr.is_running());
  6875. });
  6876. svr.wait_until_ready();
  6877. Client cli("localhost", PORT);
  6878. auto res = cli.Get("/");
  6879. ASSERT_TRUE(res);
  6880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6881. EXPECT_EQ("helloworld", res->body);
  6882. }
  6883. TEST(LongPollingTest, ClientCloseDetection) {
  6884. Server svr;
  6885. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6886. res.set_chunked_content_provider(
  6887. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6888. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6889. sink.os << "hello";
  6890. auto count = 10;
  6891. while (count > 0 && sink.is_writable()) {
  6892. this_thread::sleep_for(chrono::milliseconds(10));
  6893. count--;
  6894. }
  6895. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6896. return true;
  6897. });
  6898. });
  6899. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6900. auto se = detail::scope_exit([&] {
  6901. svr.stop();
  6902. listen_thread.join();
  6903. ASSERT_FALSE(svr.is_running());
  6904. });
  6905. svr.wait_until_ready();
  6906. Client cli("localhost", PORT);
  6907. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6908. EXPECT_EQ("hello", string(data, data_length));
  6909. return false; // close the socket immediately.
  6910. });
  6911. ASSERT_FALSE(res);
  6912. }
  6913. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  6914. Server svr;
  6915. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6916. res.set_chunked_content_provider(
  6917. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6918. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6919. sink.os << "hello";
  6920. EXPECT_TRUE(sink.os.good());
  6921. // Wait for the client to close the connection
  6922. auto count = 10;
  6923. while (count > 0 && sink.is_writable()) {
  6924. this_thread::sleep_for(chrono::milliseconds(10));
  6925. count--;
  6926. }
  6927. // After client disconnect, write repeatedly until the socket
  6928. // write actually fails (small writes may be absorbed by the
  6929. // kernel buffer)
  6930. std::string chunk(1024, 'x');
  6931. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  6932. sink.os << chunk;
  6933. }
  6934. EXPECT_TRUE(sink.os.fail());
  6935. return true;
  6936. });
  6937. });
  6938. auto port = svr.bind_to_any_port("localhost");
  6939. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  6940. auto se = detail::scope_exit([&] {
  6941. svr.stop();
  6942. listen_thread.join();
  6943. ASSERT_FALSE(svr.is_running());
  6944. });
  6945. svr.wait_until_ready();
  6946. Client cli("localhost", port);
  6947. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6948. EXPECT_EQ("hello", string(data, data_length));
  6949. return false; // close the socket immediately.
  6950. });
  6951. ASSERT_FALSE(res);
  6952. }
  6953. TEST(GetWithParametersTest, GetWithParameters) {
  6954. Server svr;
  6955. svr.Get("/", [&](const Request &req, Response &) {
  6956. EXPECT_EQ("world", req.get_param_value("hello"));
  6957. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6958. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6959. });
  6960. svr.Get("/params", [&](const Request &req, Response &) {
  6961. EXPECT_EQ("world", req.get_param_value("hello"));
  6962. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6963. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6964. });
  6965. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6966. EXPECT_EQ("resource-id", req.matches[1]);
  6967. EXPECT_EQ("foo", req.get_param_value("param1"));
  6968. EXPECT_EQ("bar", req.get_param_value("param2"));
  6969. });
  6970. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6971. EXPECT_EQ("user-id", req.path_params.at("id"));
  6972. EXPECT_EQ("foo", req.get_param_value("param1"));
  6973. EXPECT_EQ("bar", req.get_param_value("param2"));
  6974. });
  6975. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6976. auto se = detail::scope_exit([&] {
  6977. svr.stop();
  6978. listen_thread.join();
  6979. ASSERT_FALSE(svr.is_running());
  6980. });
  6981. svr.wait_until_ready();
  6982. {
  6983. Client cli(HOST, PORT);
  6984. Params params;
  6985. params.emplace("hello", "world");
  6986. params.emplace("hello2", "world2");
  6987. params.emplace("hello3", "world3");
  6988. auto res = cli.Get("/", params, Headers{});
  6989. ASSERT_TRUE(res);
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. }
  6992. {
  6993. Client cli(HOST, PORT);
  6994. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6995. ASSERT_TRUE(res);
  6996. EXPECT_EQ(StatusCode::OK_200, res->status);
  6997. }
  6998. {
  6999. Client cli(HOST, PORT);
  7000. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  7001. ASSERT_TRUE(res);
  7002. EXPECT_EQ(StatusCode::OK_200, res->status);
  7003. }
  7004. {
  7005. Client cli(HOST, PORT);
  7006. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  7007. ASSERT_TRUE(res);
  7008. EXPECT_EQ(StatusCode::OK_200, res->status);
  7009. }
  7010. }
  7011. TEST(GetWithParametersTest, GetWithParameters2) {
  7012. Server svr;
  7013. svr.Get("/", [&](const Request &req, Response &res) {
  7014. auto text = req.get_param_value("hello");
  7015. res.set_content(text, "text/plain");
  7016. });
  7017. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7018. auto se = detail::scope_exit([&] {
  7019. svr.stop();
  7020. listen_thread.join();
  7021. ASSERT_FALSE(svr.is_running());
  7022. });
  7023. svr.wait_until_ready();
  7024. Client cli("localhost", PORT);
  7025. Params params;
  7026. params.emplace("hello", "world");
  7027. std::string body;
  7028. auto res = cli.Get("/", params, Headers{},
  7029. [&](const char *data, size_t data_length) {
  7030. body.append(data, data_length);
  7031. return true;
  7032. });
  7033. ASSERT_TRUE(res);
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. EXPECT_EQ("world", body);
  7036. }
  7037. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  7038. auto host = "httpbingo.org";
  7039. auto path = std::string{"/range/32"};
  7040. #ifdef CPPHTTPLIB_SSL_ENABLED
  7041. SSLClient cli(host);
  7042. #else
  7043. Client cli(host);
  7044. #endif
  7045. cli.set_default_headers({make_range_header({{1, 10}})});
  7046. cli.set_connection_timeout(5);
  7047. {
  7048. auto res = cli.Get(path);
  7049. ASSERT_TRUE(res);
  7050. EXPECT_EQ("bcdefghijk", res->body);
  7051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7052. }
  7053. {
  7054. auto res = cli.Get(path);
  7055. ASSERT_TRUE(res);
  7056. EXPECT_EQ("bcdefghijk", res->body);
  7057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7058. }
  7059. }
  7060. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  7061. Server svr;
  7062. svr.set_default_headers({{"Hello", "World"}});
  7063. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  7064. res.set_content("ok", "text/plain");
  7065. });
  7066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7067. auto se = detail::scope_exit([&] {
  7068. svr.stop();
  7069. listen_thread.join();
  7070. ASSERT_FALSE(svr.is_running());
  7071. });
  7072. svr.wait_until_ready();
  7073. Client cli("localhost", PORT);
  7074. auto res = cli.Get("/");
  7075. ASSERT_TRUE(res);
  7076. EXPECT_EQ(StatusCode::OK_200, res->status);
  7077. EXPECT_EQ("ok", res->body);
  7078. EXPECT_EQ("World", res->get_header_value("Hello"));
  7079. }
  7080. #ifdef CPPHTTPLIB_SSL_ENABLED
  7081. TEST(KeepAliveTest, ReadTimeoutSSL) {
  7082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7083. ASSERT_TRUE(svr.is_valid());
  7084. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  7085. std::this_thread::sleep_for(std::chrono::seconds(2));
  7086. res.set_content("a", "text/plain");
  7087. });
  7088. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  7089. res.set_content("b", "text/plain");
  7090. });
  7091. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7092. auto se = detail::scope_exit([&] {
  7093. svr.stop();
  7094. listen_thread.join();
  7095. ASSERT_FALSE(svr.is_running());
  7096. });
  7097. svr.wait_until_ready();
  7098. SSLClient cli("localhost", PORT);
  7099. cli.enable_server_certificate_verification(false);
  7100. cli.set_keep_alive(true);
  7101. cli.set_read_timeout(std::chrono::seconds(1));
  7102. auto resa = cli.Get("/a");
  7103. ASSERT_TRUE(!resa);
  7104. EXPECT_EQ(Error::Read, resa.error());
  7105. auto resb = cli.Get("/b");
  7106. ASSERT_TRUE(resb);
  7107. EXPECT_EQ(StatusCode::OK_200, resb->status);
  7108. EXPECT_EQ("b", resb->body);
  7109. }
  7110. #endif
  7111. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  7112. protected:
  7113. ServerTestWithAI_PASSIVE()
  7114. : cli_(HOST, PORT)
  7115. #ifdef CPPHTTPLIB_SSL_ENABLED
  7116. ,
  7117. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7118. #endif
  7119. {
  7120. #ifdef CPPHTTPLIB_SSL_ENABLED
  7121. cli_.enable_server_certificate_verification(false);
  7122. #endif
  7123. }
  7124. virtual void SetUp() {
  7125. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  7126. res.set_content("Hello World!", "text/plain");
  7127. });
  7128. t_ = thread(
  7129. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  7130. svr_.wait_until_ready();
  7131. }
  7132. virtual void TearDown() {
  7133. svr_.stop();
  7134. t_.join();
  7135. }
  7136. #ifdef CPPHTTPLIB_SSL_ENABLED
  7137. SSLClient cli_;
  7138. SSLServer svr_;
  7139. #else
  7140. Client cli_;
  7141. Server svr_;
  7142. #endif
  7143. thread t_;
  7144. };
  7145. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  7146. auto res = cli_.Get("/hi");
  7147. ASSERT_TRUE(res);
  7148. EXPECT_EQ(StatusCode::OK_200, res->status);
  7149. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7150. EXPECT_EQ("Hello World!", res->body);
  7151. }
  7152. class ServerUpDownTest : public ::testing::Test {
  7153. protected:
  7154. ServerUpDownTest() : cli_(HOST, PORT) {}
  7155. virtual void SetUp() {
  7156. t_ = thread([&]() {
  7157. svr_.bind_to_any_port(HOST);
  7158. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  7159. ASSERT_TRUE(svr_.listen_after_bind());
  7160. });
  7161. svr_.wait_until_ready();
  7162. }
  7163. virtual void TearDown() {
  7164. svr_.stop();
  7165. t_.join();
  7166. }
  7167. Client cli_;
  7168. Server svr_;
  7169. thread t_;
  7170. };
  7171. TEST_F(ServerUpDownTest, QuickStartStop) {
  7172. // Should not crash, especially when run with
  7173. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  7174. }
  7175. class PayloadMaxLengthTest : public ::testing::Test {
  7176. protected:
  7177. PayloadMaxLengthTest()
  7178. : cli_(HOST, PORT)
  7179. #ifdef CPPHTTPLIB_SSL_ENABLED
  7180. ,
  7181. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7182. #endif
  7183. {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. cli_.enable_server_certificate_verification(false);
  7186. #endif
  7187. }
  7188. virtual void SetUp() {
  7189. svr_.set_payload_max_length(8);
  7190. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7191. res.set_content("test", "text/plain");
  7192. });
  7193. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7194. svr_.wait_until_ready();
  7195. }
  7196. virtual void TearDown() {
  7197. svr_.stop();
  7198. t_.join();
  7199. }
  7200. #ifdef CPPHTTPLIB_SSL_ENABLED
  7201. SSLClient cli_;
  7202. SSLServer svr_;
  7203. #else
  7204. Client cli_;
  7205. Server svr_;
  7206. #endif
  7207. thread t_;
  7208. };
  7209. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  7210. auto res = cli_.Post("/test", "123456789", "text/plain");
  7211. ASSERT_TRUE(res);
  7212. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7213. res = cli_.Post("/test", "12345678", "text/plain");
  7214. ASSERT_TRUE(res);
  7215. EXPECT_EQ(StatusCode::OK_200, res->status);
  7216. }
  7217. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7218. // Test chunked encoding with payload exceeding the 8-byte limit
  7219. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7220. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7221. ASSERT_TRUE(res);
  7222. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7223. }
  7224. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7225. // Test chunked encoding with payload within the 8-byte limit
  7226. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7227. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7228. ASSERT_TRUE(res);
  7229. EXPECT_EQ(StatusCode::OK_200, res->status);
  7230. }
  7231. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7232. // Test using send_request to send chunked data exceeding payload limit
  7233. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7234. "Host: " +
  7235. std::string(HOST) + ":" + std::to_string(PORT) +
  7236. "\r\n"
  7237. "Transfer-Encoding: chunked\r\n"
  7238. "Connection: close\r\n"
  7239. "\r\n"
  7240. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7241. "0123456789\r\n"
  7242. "0\r\n" // End chunk
  7243. "\r\n";
  7244. std::string response;
  7245. bool result = send_request(1, chunked_request, &response);
  7246. if (!result) {
  7247. // If send_request fails, it might be because the server closed the
  7248. // connection due to payload limit enforcement, which is acceptable
  7249. SUCCEED()
  7250. << "Server rejected oversized chunked request (connection closed)";
  7251. } else {
  7252. // If we got a response, check if it's an error response or connection was
  7253. // closed early Short response length indicates connection was closed due to
  7254. // payload limit
  7255. if (response.length() <= 10) {
  7256. SUCCEED() << "Server closed connection for oversized chunked request";
  7257. } else {
  7258. // Check for error status codes
  7259. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7260. response.find("Payload Too Large") != std::string::npos ||
  7261. response.find("400") != std::string::npos);
  7262. }
  7263. }
  7264. }
  7265. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7266. // Test request without Content-Length header exceeding payload limit
  7267. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7268. "Host: " +
  7269. std::string(HOST) + ":" +
  7270. std::to_string(PORT) +
  7271. "\r\n"
  7272. "Connection: close\r\n"
  7273. "\r\n";
  7274. // Add payload exceeding the 8-byte limit
  7275. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7276. request_without_content_length += large_payload;
  7277. std::string response;
  7278. bool result = send_request(1, request_without_content_length, &response);
  7279. if (!result) {
  7280. // If send_request fails, server likely closed connection due to payload
  7281. // limit
  7282. SUCCEED() << "Server rejected oversized request without Content-Length "
  7283. "(connection closed)";
  7284. } else {
  7285. // Check if server responded with error or closed connection early
  7286. if (response.length() <= 10) {
  7287. SUCCEED() << "Server closed connection for oversized request without "
  7288. "Content-Length";
  7289. } else {
  7290. // Check for error status codes
  7291. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7292. response.find("Payload Too Large") != std::string::npos ||
  7293. response.find("400") != std::string::npos);
  7294. }
  7295. }
  7296. }
  7297. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7298. // Test request without Content-Length header within payload limit
  7299. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7300. "Host: " +
  7301. std::string(HOST) + ":" +
  7302. std::to_string(PORT) +
  7303. "\r\n"
  7304. "Connection: close\r\n"
  7305. "\r\n";
  7306. // Add payload within the 8-byte limit
  7307. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7308. request_without_content_length += small_payload;
  7309. std::string response;
  7310. bool result = send_request(1, request_without_content_length, &response);
  7311. // For requests without Content-Length, the server may have different behavior
  7312. // The key is that it should not reject due to payload limit for small
  7313. // payloads
  7314. if (result) {
  7315. // Check for any HTTP response (success or error, but not connection closed)
  7316. if (response.length() > 10) {
  7317. SUCCEED()
  7318. << "Server processed request without Content-Length within limit";
  7319. } else {
  7320. // Short response might indicate connection closed, which is acceptable
  7321. SUCCEED() << "Server closed connection for request without "
  7322. "Content-Length (acceptable behavior)";
  7323. }
  7324. } else {
  7325. // Connection failure might be due to protocol requirements
  7326. SUCCEED() << "Connection issue with request without Content-Length "
  7327. "(environment-specific)";
  7328. }
  7329. }
  7330. class LargePayloadMaxLengthTest : public ::testing::Test {
  7331. protected:
  7332. LargePayloadMaxLengthTest()
  7333. : cli_(HOST, PORT)
  7334. #ifdef CPPHTTPLIB_SSL_ENABLED
  7335. ,
  7336. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7337. #endif
  7338. {
  7339. #ifdef CPPHTTPLIB_SSL_ENABLED
  7340. cli_.enable_server_certificate_verification(false);
  7341. #endif
  7342. }
  7343. virtual void SetUp() {
  7344. // Set 10MB payload limit
  7345. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7346. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7347. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7348. res.set_content("Large payload test", "text/plain");
  7349. });
  7350. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7351. svr_.wait_until_ready();
  7352. }
  7353. virtual void TearDown() {
  7354. svr_.stop();
  7355. t_.join();
  7356. }
  7357. #ifdef CPPHTTPLIB_SSL_ENABLED
  7358. SSLClient cli_;
  7359. SSLServer svr_;
  7360. #else
  7361. Client cli_;
  7362. Server svr_;
  7363. #endif
  7364. thread t_;
  7365. };
  7366. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7367. // Test chunked encoding with payload within 10MB limit
  7368. std::string medium_payload(5 * 1024 * 1024,
  7369. 'A'); // 5MB payload, within 10MB limit
  7370. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7371. ASSERT_TRUE(res);
  7372. EXPECT_EQ(StatusCode::OK_200, res->status);
  7373. }
  7374. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7375. // Test chunked encoding with payload exceeding 10MB limit
  7376. std::string large_payload(12 * 1024 * 1024,
  7377. 'B'); // 12MB payload, exceeds 10MB limit
  7378. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7379. // Server may either return 413 or close the connection
  7380. if (res) {
  7381. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7382. } else {
  7383. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  7384. }
  7385. }
  7386. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7387. // Test request without Content-Length header within 10MB limit
  7388. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7389. "Host: " +
  7390. std::string(HOST) + ":" +
  7391. std::to_string(PORT) +
  7392. "\r\n"
  7393. "Connection: close\r\n"
  7394. "\r\n";
  7395. // Add 1MB payload (within 10MB limit)
  7396. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7397. request_without_content_length += medium_payload;
  7398. std::string response;
  7399. bool result = send_request(5, request_without_content_length, &response);
  7400. if (result) {
  7401. // Should get a proper HTTP response for payloads within limit
  7402. if (response.length() > 10) {
  7403. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7404. "10MB limit";
  7405. } else {
  7406. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7407. "Content-Length)";
  7408. }
  7409. } else {
  7410. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7411. }
  7412. }
  7413. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7414. // Test request without Content-Length header exceeding 10MB limit
  7415. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7416. "Host: " +
  7417. std::string(HOST) + ":" +
  7418. std::to_string(PORT) +
  7419. "\r\n"
  7420. "Connection: close\r\n"
  7421. "\r\n";
  7422. // Add 12MB payload (exceeds 10MB limit)
  7423. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7424. request_without_content_length += large_payload;
  7425. std::string response;
  7426. bool result = send_request(10, request_without_content_length, &response);
  7427. if (!result) {
  7428. // Server should close connection due to payload limit
  7429. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7430. "(connection closed)";
  7431. } else {
  7432. // Check for error response
  7433. if (response.length() <= 10) {
  7434. SUCCEED()
  7435. << "Server closed connection for 12MB request exceeding 10MB limit";
  7436. } else {
  7437. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7438. response.find("Payload Too Large") != std::string::npos ||
  7439. response.find("400") != std::string::npos);
  7440. }
  7441. }
  7442. }
  7443. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7444. // `payload_max_length` is not enforced on decompressed body in ContentReader
  7445. // path.
  7446. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  7447. Server svr;
  7448. const size_t LIMIT = 64 * 1024; // 64KB
  7449. svr.set_payload_max_length(LIMIT);
  7450. size_t total = 0;
  7451. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  7452. const ContentReader &content_reader) {
  7453. content_reader([&](const char * /*data*/, size_t len) {
  7454. total += len;
  7455. return true;
  7456. });
  7457. res.status = 200;
  7458. res.set_content("stream_ok", "text/plain");
  7459. });
  7460. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7461. auto se = detail::scope_exit([&] {
  7462. svr.stop();
  7463. thread.join();
  7464. ASSERT_FALSE(svr.is_running());
  7465. });
  7466. svr.wait_until_ready();
  7467. // Prepare 256KB raw data and gzip-compress it
  7468. std::string raw(256 * 1024, 'A');
  7469. std::string gz;
  7470. {
  7471. z_stream zs{};
  7472. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  7473. Z_DEFAULT_STRATEGY);
  7474. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  7475. zs.avail_in = static_cast<uInt>(raw.size());
  7476. char outbuf[4096];
  7477. int ret;
  7478. do {
  7479. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  7480. zs.avail_out = sizeof(outbuf);
  7481. ret = deflate(&zs, Z_FINISH);
  7482. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  7483. } while (ret != Z_STREAM_END);
  7484. deflateEnd(&zs);
  7485. }
  7486. Client cli(HOST, PORT);
  7487. cli.set_connection_timeout(std::chrono::seconds(5));
  7488. Headers headers = {{"Content-Encoding", "gzip"}};
  7489. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  7490. "application/octet-stream");
  7491. ASSERT_TRUE(res);
  7492. // Server must reject oversized decompressed payloads with 413.
  7493. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7494. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  7495. EXPECT_LE(total, LIMIT);
  7496. }
  7497. #endif
  7498. // Regression test for DoS vulnerability: a malicious server sending a response
  7499. // without Content-Length header must not cause unbounded memory consumption on
  7500. // the client side. The client should stop reading after a reasonable limit,
  7501. // similar to the server-side set_payload_max_length protection.
  7502. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  7503. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7504. #ifndef _WIN32
  7505. signal(SIGPIPE, SIG_IGN);
  7506. #endif
  7507. auto server_thread = std::thread([] {
  7508. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  7509. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7510. default_socket_options(srv);
  7511. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7512. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7513. sockaddr_in addr{};
  7514. addr.sin_family = AF_INET;
  7515. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7516. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7517. int opt = 1;
  7518. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7519. #ifdef _WIN32
  7520. reinterpret_cast<const char *>(&opt),
  7521. #else
  7522. &opt,
  7523. #endif
  7524. sizeof(opt));
  7525. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7526. ::listen(srv, 1);
  7527. sockaddr_in cli_addr{};
  7528. socklen_t cli_len = sizeof(cli_addr);
  7529. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7530. if (cli != INVALID_SOCKET) {
  7531. char buf[4096];
  7532. ::recv(cli, buf, sizeof(buf), 0);
  7533. // Malicious response: no Content-Length, no chunked encoding
  7534. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7535. "Connection: close\r\n"
  7536. "\r\n";
  7537. ::send(cli,
  7538. #ifdef _WIN32
  7539. static_cast<const char *>(response_header.c_str()),
  7540. static_cast<int>(response_header.size()),
  7541. #else
  7542. response_header.c_str(), response_header.size(),
  7543. #endif
  7544. 0);
  7545. // Send 10MB of data
  7546. std::string chunk(64 * 1024, 'A');
  7547. size_t total_sent = 0;
  7548. while (total_sent < MALICIOUS_DATA_SIZE) {
  7549. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  7550. auto sent = ::send(cli,
  7551. #ifdef _WIN32
  7552. static_cast<const char *>(chunk.c_str()),
  7553. static_cast<int>(to_send),
  7554. #else
  7555. chunk.c_str(), to_send,
  7556. #endif
  7557. 0);
  7558. if (sent <= 0) break;
  7559. total_sent += static_cast<size_t>(sent);
  7560. }
  7561. detail::close_socket(cli);
  7562. }
  7563. detail::close_socket(srv);
  7564. });
  7565. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7566. size_t total_read = 0;
  7567. {
  7568. Client cli("127.0.0.1", PORT + 2);
  7569. cli.set_read_timeout(5, 0);
  7570. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  7571. auto stream = cli.open_stream("GET", "/malicious");
  7572. ASSERT_TRUE(stream.is_valid());
  7573. char buffer[64 * 1024];
  7574. ssize_t n;
  7575. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7576. total_read += static_cast<size_t>(n);
  7577. }
  7578. } // StreamHandle and Client destroyed here, closing the socket
  7579. server_thread.join();
  7580. // With set_payload_max_length, the client must stop reading before consuming
  7581. // all 10MB. The read loop should be cut off at or near the configured limit.
  7582. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  7583. << "Client read " << total_read << " bytes, exceeding the configured "
  7584. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  7585. }
  7586. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  7587. // the entire response body without truncation.
  7588. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  7589. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  7590. #ifndef _WIN32
  7591. signal(SIGPIPE, SIG_IGN);
  7592. #endif
  7593. auto server_thread = std::thread([] {
  7594. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7595. default_socket_options(srv);
  7596. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7597. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7598. sockaddr_in addr{};
  7599. addr.sin_family = AF_INET;
  7600. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7601. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7602. int opt = 1;
  7603. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7604. #ifdef _WIN32
  7605. reinterpret_cast<const char *>(&opt),
  7606. #else
  7607. &opt,
  7608. #endif
  7609. sizeof(opt));
  7610. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7611. ::listen(srv, 1);
  7612. sockaddr_in cli_addr{};
  7613. socklen_t cli_len = sizeof(cli_addr);
  7614. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7615. if (cli != INVALID_SOCKET) {
  7616. char buf[4096];
  7617. ::recv(cli, buf, sizeof(buf), 0);
  7618. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7619. "Connection: close\r\n"
  7620. "\r\n";
  7621. ::send(cli,
  7622. #ifdef _WIN32
  7623. static_cast<const char *>(response_header.c_str()),
  7624. static_cast<int>(response_header.size()),
  7625. #else
  7626. response_header.c_str(), response_header.size(),
  7627. #endif
  7628. 0);
  7629. std::string chunk(64 * 1024, 'A');
  7630. size_t total_sent = 0;
  7631. while (total_sent < DATA_SIZE) {
  7632. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7633. auto sent = ::send(cli,
  7634. #ifdef _WIN32
  7635. static_cast<const char *>(chunk.c_str()),
  7636. static_cast<int>(to_send),
  7637. #else
  7638. chunk.c_str(), to_send,
  7639. #endif
  7640. 0);
  7641. if (sent <= 0) break;
  7642. total_sent += static_cast<size_t>(sent);
  7643. }
  7644. #ifdef _WIN32
  7645. ::shutdown(cli, SD_SEND);
  7646. #else
  7647. ::shutdown(cli, SHUT_WR);
  7648. #endif
  7649. // Drain until the client closes its end, ensuring all data is delivered
  7650. char drain[1024];
  7651. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7652. detail::close_socket(cli);
  7653. }
  7654. detail::close_socket(srv);
  7655. });
  7656. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7657. size_t total_read = 0;
  7658. {
  7659. Client cli("127.0.0.1", PORT + 2);
  7660. cli.set_read_timeout(5, 0);
  7661. cli.set_payload_max_length(0); // 0 means no limit
  7662. auto stream = cli.open_stream("GET", "/data");
  7663. ASSERT_TRUE(stream.is_valid());
  7664. char buffer[64 * 1024];
  7665. ssize_t n;
  7666. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  7667. total_read += static_cast<size_t>(n);
  7668. }
  7669. }
  7670. server_thread.join();
  7671. EXPECT_EQ(total_read, DATA_SIZE)
  7672. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  7673. << " bytes without truncation, but only read " << total_read << " bytes.";
  7674. }
  7675. // Verify that content_receiver bypasses the default payload_max_length,
  7676. // allowing streaming downloads larger than 100MB without requiring an explicit
  7677. // set_payload_max_length call.
  7678. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  7679. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7680. #ifndef _WIN32
  7681. signal(SIGPIPE, SIG_IGN);
  7682. #endif
  7683. auto server_thread = std::thread([] {
  7684. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7685. default_socket_options(srv);
  7686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7687. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7688. sockaddr_in addr{};
  7689. addr.sin_family = AF_INET;
  7690. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7691. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7692. int opt = 1;
  7693. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7694. #ifdef _WIN32
  7695. reinterpret_cast<const char *>(&opt),
  7696. #else
  7697. &opt,
  7698. #endif
  7699. sizeof(opt));
  7700. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7701. ::listen(srv, 1);
  7702. sockaddr_in cli_addr{};
  7703. socklen_t cli_len = sizeof(cli_addr);
  7704. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7705. if (cli != INVALID_SOCKET) {
  7706. char buf[4096];
  7707. ::recv(cli, buf, sizeof(buf), 0);
  7708. // Response with Content-Length larger than default 100MB limit
  7709. auto content_length = std::to_string(DATA_SIZE);
  7710. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7711. "Content-Length: " +
  7712. content_length +
  7713. "\r\n"
  7714. "Connection: close\r\n"
  7715. "\r\n";
  7716. ::send(cli,
  7717. #ifdef _WIN32
  7718. static_cast<const char *>(response_header.c_str()),
  7719. static_cast<int>(response_header.size()),
  7720. #else
  7721. response_header.c_str(), response_header.size(),
  7722. #endif
  7723. 0);
  7724. std::string chunk(64 * 1024, 'A');
  7725. size_t total_sent = 0;
  7726. while (total_sent < DATA_SIZE) {
  7727. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7728. auto sent = ::send(cli,
  7729. #ifdef _WIN32
  7730. static_cast<const char *>(chunk.c_str()),
  7731. static_cast<int>(to_send),
  7732. #else
  7733. chunk.c_str(), to_send,
  7734. #endif
  7735. 0);
  7736. if (sent <= 0) break;
  7737. total_sent += static_cast<size_t>(sent);
  7738. }
  7739. detail::close_socket(cli);
  7740. }
  7741. detail::close_socket(srv);
  7742. });
  7743. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7744. size_t total_received = 0;
  7745. {
  7746. Client cli("127.0.0.1", PORT + 2);
  7747. cli.set_read_timeout(10, 0);
  7748. // Do NOT call set_payload_max_length — use the default 100MB limit
  7749. auto res =
  7750. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7751. total_received += data_length;
  7752. return true;
  7753. });
  7754. ASSERT_TRUE(res);
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. }
  7757. server_thread.join();
  7758. EXPECT_EQ(total_received, DATA_SIZE)
  7759. << "With content_receiver, the client should read all " << DATA_SIZE
  7760. << " bytes despite the default 100MB payload_max_length, but only read "
  7761. << total_received << " bytes.";
  7762. }
  7763. // Verify that an explicit set_payload_max_length smaller than the response is
  7764. // enforced even when a content_receiver is used.
  7765. TEST(ClientVulnerabilityTest,
  7766. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  7767. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7768. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  7769. #ifndef _WIN32
  7770. signal(SIGPIPE, SIG_IGN);
  7771. #endif
  7772. auto server_thread = std::thread([] {
  7773. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7774. default_socket_options(srv);
  7775. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7776. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7777. sockaddr_in addr{};
  7778. addr.sin_family = AF_INET;
  7779. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7780. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7781. int opt = 1;
  7782. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7783. #ifdef _WIN32
  7784. reinterpret_cast<const char *>(&opt),
  7785. #else
  7786. &opt,
  7787. #endif
  7788. sizeof(opt));
  7789. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7790. ::listen(srv, 1);
  7791. sockaddr_in cli_addr{};
  7792. socklen_t cli_len = sizeof(cli_addr);
  7793. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7794. if (cli != INVALID_SOCKET) {
  7795. char buf[4096];
  7796. ::recv(cli, buf, sizeof(buf), 0);
  7797. auto content_length = std::to_string(DATA_SIZE);
  7798. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7799. "Content-Length: " +
  7800. content_length +
  7801. "\r\n"
  7802. "Connection: close\r\n"
  7803. "\r\n";
  7804. ::send(cli,
  7805. #ifdef _WIN32
  7806. static_cast<const char *>(response_header.c_str()),
  7807. static_cast<int>(response_header.size()),
  7808. #else
  7809. response_header.c_str(), response_header.size(),
  7810. #endif
  7811. 0);
  7812. std::string chunk(64 * 1024, 'A');
  7813. size_t total_sent = 0;
  7814. while (total_sent < DATA_SIZE) {
  7815. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7816. auto sent = ::send(cli,
  7817. #ifdef _WIN32
  7818. static_cast<const char *>(chunk.c_str()),
  7819. static_cast<int>(to_send),
  7820. #else
  7821. chunk.c_str(), to_send,
  7822. #endif
  7823. 0);
  7824. if (sent <= 0) break;
  7825. total_sent += static_cast<size_t>(sent);
  7826. }
  7827. detail::close_socket(cli);
  7828. }
  7829. detail::close_socket(srv);
  7830. });
  7831. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7832. size_t total_received = 0;
  7833. {
  7834. Client cli("127.0.0.1", PORT + 2);
  7835. cli.set_read_timeout(10, 0);
  7836. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  7837. auto res =
  7838. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7839. total_received += data_length;
  7840. return true;
  7841. });
  7842. // Should fail because 200MB exceeds the explicit 150MB limit
  7843. EXPECT_FALSE(res);
  7844. }
  7845. server_thread.join();
  7846. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  7847. << "Client with content_receiver should respect the explicit "
  7848. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  7849. << total_received << " bytes.";
  7850. }
  7851. // Verify that an explicit set_payload_max_length larger than the response
  7852. // allows the content_receiver to read all data successfully.
  7853. TEST(ClientVulnerabilityTest,
  7854. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  7855. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  7856. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  7857. #ifndef _WIN32
  7858. signal(SIGPIPE, SIG_IGN);
  7859. #endif
  7860. auto server_thread = std::thread([] {
  7861. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7862. default_socket_options(srv);
  7863. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7864. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7865. sockaddr_in addr{};
  7866. addr.sin_family = AF_INET;
  7867. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  7868. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7869. int opt = 1;
  7870. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7871. #ifdef _WIN32
  7872. reinterpret_cast<const char *>(&opt),
  7873. #else
  7874. &opt,
  7875. #endif
  7876. sizeof(opt));
  7877. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  7878. ::listen(srv, 1);
  7879. sockaddr_in cli_addr{};
  7880. socklen_t cli_len = sizeof(cli_addr);
  7881. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7882. if (cli != INVALID_SOCKET) {
  7883. char buf[4096];
  7884. ::recv(cli, buf, sizeof(buf), 0);
  7885. auto content_length = std::to_string(DATA_SIZE);
  7886. std::string response_header = "HTTP/1.1 200 OK\r\n"
  7887. "Content-Length: " +
  7888. content_length +
  7889. "\r\n"
  7890. "Connection: close\r\n"
  7891. "\r\n";
  7892. ::send(cli,
  7893. #ifdef _WIN32
  7894. static_cast<const char *>(response_header.c_str()),
  7895. static_cast<int>(response_header.size()),
  7896. #else
  7897. response_header.c_str(), response_header.size(),
  7898. #endif
  7899. 0);
  7900. std::string chunk(64 * 1024, 'A');
  7901. size_t total_sent = 0;
  7902. while (total_sent < DATA_SIZE) {
  7903. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  7904. auto sent = ::send(cli,
  7905. #ifdef _WIN32
  7906. static_cast<const char *>(chunk.c_str()),
  7907. static_cast<int>(to_send),
  7908. #else
  7909. chunk.c_str(), to_send,
  7910. #endif
  7911. 0);
  7912. if (sent <= 0) break;
  7913. total_sent += static_cast<size_t>(sent);
  7914. }
  7915. #ifdef _WIN32
  7916. ::shutdown(cli, SD_SEND);
  7917. #else
  7918. ::shutdown(cli, SHUT_WR);
  7919. #endif
  7920. char drain[1024];
  7921. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  7922. detail::close_socket(cli);
  7923. }
  7924. detail::close_socket(srv);
  7925. });
  7926. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  7927. size_t total_received = 0;
  7928. {
  7929. Client cli("127.0.0.1", PORT + 2);
  7930. cli.set_read_timeout(10, 0);
  7931. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  7932. auto res =
  7933. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  7934. total_received += data_length;
  7935. return true;
  7936. });
  7937. ASSERT_TRUE(res);
  7938. EXPECT_EQ(StatusCode::OK_200, res->status);
  7939. }
  7940. server_thread.join();
  7941. EXPECT_EQ(total_received, DATA_SIZE)
  7942. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  7943. << " bytes (larger than " << DATA_SIZE
  7944. << " bytes response), content_receiver should read all data, but only "
  7945. "read "
  7946. << total_received << " bytes.";
  7947. }
  7948. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  7949. // Regression test for "zip bomb" attack on the client side: a malicious server
  7950. // sends a small gzip-compressed response that decompresses to a huge payload.
  7951. // The client must enforce payload_max_length on the decompressed size.
  7952. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  7953. constexpr size_t DECOMPRESSED_SIZE =
  7954. 10 * 1024 * 1024; // 10MB after decompression
  7955. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  7956. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  7957. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  7958. std::string compressed;
  7959. {
  7960. httplib::detail::gzip_compressor compressor;
  7961. bool ok =
  7962. compressor.compress(uncompressed.data(), uncompressed.size(),
  7963. /*last=*/true, [&](const char *buf, size_t len) {
  7964. compressed.append(buf, len);
  7965. return true;
  7966. });
  7967. ASSERT_TRUE(ok);
  7968. }
  7969. // Sanity: compressed data should be much smaller than the decompressed size
  7970. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  7971. #ifndef _WIN32
  7972. signal(SIGPIPE, SIG_IGN);
  7973. #endif
  7974. // Set up the listening socket in the main thread so the server is guaranteed
  7975. // to be ready before the client connects (eliminates race condition).
  7976. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  7977. default_socket_options(srv);
  7978. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  7979. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  7980. sockaddr_in addr{};
  7981. addr.sin_family = AF_INET;
  7982. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  7983. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  7984. int opt = 1;
  7985. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  7986. #ifdef _WIN32
  7987. reinterpret_cast<const char *>(&opt),
  7988. #else
  7989. &opt,
  7990. #endif
  7991. sizeof(opt));
  7992. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  7993. ASSERT_EQ(0, ::listen(srv, 1));
  7994. auto server_thread = std::thread([&compressed, srv] {
  7995. sockaddr_in cli_addr{};
  7996. socklen_t cli_len = sizeof(cli_addr);
  7997. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  7998. if (cli != INVALID_SOCKET) {
  7999. // Read the full HTTP request (until \r\n\r\n)
  8000. char buf[4096];
  8001. size_t total = 0;
  8002. while (total < sizeof(buf)) {
  8003. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  8004. if (n <= 0) break;
  8005. total += static_cast<size_t>(n);
  8006. // Check for end of headers
  8007. if (total >= 4) {
  8008. std::string req(buf, total);
  8009. if (req.find("\r\n\r\n") != std::string::npos) break;
  8010. }
  8011. }
  8012. // Malicious response: gzip-compressed body, no Content-Length
  8013. std::string response_header = "HTTP/1.1 200 OK\r\n"
  8014. "Content-Encoding: gzip\r\n"
  8015. "Connection: close\r\n"
  8016. "\r\n";
  8017. ::send(cli,
  8018. #ifdef _WIN32
  8019. static_cast<const char *>(response_header.c_str()),
  8020. static_cast<int>(response_header.size()),
  8021. #else
  8022. response_header.c_str(), response_header.size(),
  8023. #endif
  8024. 0);
  8025. // Send the compressed payload (small on the wire, huge when decompressed)
  8026. size_t total_sent = 0;
  8027. while (total_sent < compressed.size()) {
  8028. auto to_send = std::min(compressed.size() - total_sent,
  8029. static_cast<size_t>(64 * 1024));
  8030. auto sent =
  8031. ::send(cli,
  8032. #ifdef _WIN32
  8033. static_cast<const char *>(compressed.c_str() + total_sent),
  8034. static_cast<int>(to_send),
  8035. #else
  8036. compressed.c_str() + total_sent, to_send,
  8037. #endif
  8038. 0);
  8039. if (sent <= 0) break;
  8040. total_sent += static_cast<size_t>(sent);
  8041. }
  8042. detail::close_socket(cli);
  8043. }
  8044. });
  8045. auto se = detail::scope_exit([&] {
  8046. detail::close_socket(srv);
  8047. server_thread.join();
  8048. });
  8049. size_t total_decompressed = 0;
  8050. {
  8051. Client cli("127.0.0.1", PORT + 3);
  8052. cli.set_read_timeout(5, 0);
  8053. cli.set_decompress(true);
  8054. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  8055. auto stream = cli.open_stream("GET", "/zipbomb");
  8056. ASSERT_TRUE(stream.is_valid());
  8057. char buffer[64 * 1024];
  8058. ssize_t n;
  8059. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  8060. total_decompressed += static_cast<size_t>(n);
  8061. }
  8062. }
  8063. // The decompressed size must be capped by payload_max_length. Without
  8064. // protection, the client would decompress the full 10MB from a tiny
  8065. // compressed payload, enabling a zip bomb DoS attack.
  8066. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  8067. << "Client decompressed " << total_decompressed
  8068. << " bytes from a gzip response. The decompressed size should be "
  8069. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  8070. }
  8071. #endif
  8072. TEST(HostAndPortPropertiesTest, NoSSL) {
  8073. httplib::Client cli("www.google.com", 1234);
  8074. ASSERT_EQ("www.google.com", cli.host());
  8075. ASSERT_EQ(1234, cli.port());
  8076. }
  8077. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  8078. httplib::Client cli("www.google.com:1234");
  8079. ASSERT_EQ("www.google.com", cli.host());
  8080. ASSERT_EQ(1234, cli.port());
  8081. }
  8082. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  8083. // Port number that overflows int — should not crash, client becomes invalid
  8084. httplib::Client cli("http://www.google.com:99999999999999999999");
  8085. ASSERT_FALSE(cli.is_valid());
  8086. }
  8087. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  8088. // Port 99999 exceeds valid range (1-65535) — should not crash
  8089. httplib::Client cli("http://www.google.com:99999");
  8090. ASSERT_FALSE(cli.is_valid());
  8091. }
  8092. #ifdef CPPHTTPLIB_SSL_ENABLED
  8093. TEST(HostAndPortPropertiesTest, SSL) {
  8094. httplib::SSLClient cli("www.google.com");
  8095. ASSERT_EQ("www.google.com", cli.host());
  8096. ASSERT_EQ(443, cli.port());
  8097. }
  8098. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  8099. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  8100. std::string cert;
  8101. read_file(CA_CERT_FILE, cert);
  8102. httplib::SSLClient httplib_client("www.google.com");
  8103. // Load CA store first time
  8104. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8105. // Load CA store second time (update)
  8106. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  8107. // Verify client is still valid and can make connections
  8108. httplib_client.enable_server_certificate_verification(true);
  8109. auto res = httplib_client.Get("/");
  8110. ASSERT_TRUE(res);
  8111. // Google may return 200 or 301 depending on various factors
  8112. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  8113. res->status == StatusCode::MovedPermanently_301);
  8114. }
  8115. TEST(SSLClientTest, ServerNameIndication_Online) {
  8116. auto host = "httpbingo.org";
  8117. auto path = std::string{"/get"};
  8118. SSLClient cli(host, 443);
  8119. auto res = cli.Get(path);
  8120. ASSERT_TRUE(res);
  8121. ASSERT_EQ(StatusCode::OK_200, res->status);
  8122. }
  8123. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  8124. // Use a site that will cause SSL verification failure due to self-signed cert
  8125. SSLClient cli("self-signed.badssl.com", 443);
  8126. cli.enable_server_certificate_verification(true);
  8127. auto res = cli.Get("/");
  8128. ASSERT_TRUE(!res);
  8129. EXPECT_EQ(Error::SSLServerVerification, res.error());
  8130. // Verify backend error is captured for SSLServerVerification
  8131. // This occurs when certificate verification fails
  8132. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  8133. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  8134. EXPECT_NE(0UL, res.ssl_backend_error());
  8135. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8136. // For OpenSSL, ssl_error is 0 for verification errors
  8137. EXPECT_EQ(0, res.ssl_error());
  8138. #if !defined(_WIN32) || \
  8139. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8140. // On non-Windows or when Windows Schannel is disabled, the error comes
  8141. // from OpenSSL's verification
  8142. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  8143. res.ssl_backend_error());
  8144. #endif
  8145. #endif
  8146. }
  8147. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  8148. // Use a site where hostname doesn't match the certificate
  8149. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  8150. SSLClient cli("wrong.host.badssl.com", 443);
  8151. cli.enable_server_certificate_verification(true);
  8152. cli.enable_server_hostname_verification(true);
  8153. auto res = cli.Get("/");
  8154. ASSERT_TRUE(!res);
  8155. // The error type depends on when hostname verification occurs:
  8156. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  8157. // - Mbed TLS: SSLServerVerification (during handshake)
  8158. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  8159. res.error() == Error::SSLServerVerification);
  8160. // Verify backend error is captured for hostname verification failure
  8161. EXPECT_NE(0UL, res.ssl_backend_error());
  8162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8163. // For OpenSSL, ssl_error is 0 for verification errors
  8164. EXPECT_EQ(0, res.ssl_error());
  8165. #if !defined(_WIN32) || \
  8166. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8167. // On non-Windows or when Windows Schannel is disabled, the error comes
  8168. // from OpenSSL's hostname verification
  8169. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  8170. res.ssl_backend_error());
  8171. #endif
  8172. #endif
  8173. }
  8174. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  8175. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  8176. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  8177. SSLClient cli("www.google.com", 443);
  8178. cli.enable_server_certificate_verification(true);
  8179. auto res = cli.Get("/");
  8180. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8181. }
  8182. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  8183. SSLClient cli("www.google.com", 443);
  8184. cli.enable_server_certificate_verification(true);
  8185. cli.enable_windows_certificate_verification(false);
  8186. auto res = cli.Get("/");
  8187. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  8188. }
  8189. #endif
  8190. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  8191. Client cli("https://google.com");
  8192. auto res = cli.Get("/");
  8193. ASSERT_TRUE(res);
  8194. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8195. }
  8196. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  8197. SSLClient cli("google.com");
  8198. cli.set_ca_cert_path(CA_CERT_FILE);
  8199. auto res = cli.Get("/");
  8200. ASSERT_TRUE(res);
  8201. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8202. }
  8203. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  8204. SSLClient cli("google.com");
  8205. cli.enable_server_certificate_verification(true);
  8206. cli.set_ca_cert_path("hello");
  8207. auto res = cli.Get("/");
  8208. ASSERT_TRUE(!res);
  8209. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  8210. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  8211. // should be set
  8212. EXPECT_EQ(0, res.ssl_error());
  8213. // Verify backend error is captured for SSLLoadingCerts
  8214. // This error occurs when loading CA certificates fails
  8215. EXPECT_NE(0UL, res.ssl_backend_error());
  8216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8217. // OpenSSL specific error codes:
  8218. // > openssl errstr 0x80000002
  8219. // error:80000002:system library::No such file or directory
  8220. // > openssl errstr 0xA000126
  8221. // error:0A000126:SSL routines::unexpected eof while reading
  8222. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  8223. res.ssl_backend_error() == 0xA000126);
  8224. #endif
  8225. }
  8226. TEST(SSLClientTest, ServerCertificateVerification4) {
  8227. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8228. ASSERT_TRUE(svr.is_valid());
  8229. svr.Get("/test", [&](const Request &, Response &res) {
  8230. res.set_content("test", "text/plain");
  8231. svr.stop();
  8232. ASSERT_TRUE(true);
  8233. });
  8234. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8235. auto se = detail::scope_exit([&] {
  8236. t.join();
  8237. ASSERT_FALSE(svr.is_running());
  8238. });
  8239. svr.wait_until_ready();
  8240. SSLClient cli("127.0.0.1", PORT);
  8241. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8242. cli.enable_server_certificate_verification(true);
  8243. cli.set_connection_timeout(30);
  8244. auto res = cli.Get("/test");
  8245. ASSERT_TRUE(res);
  8246. ASSERT_EQ(StatusCode::OK_200, res->status);
  8247. }
  8248. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  8249. std::string cert;
  8250. read_file(CA_CERT_FILE, cert);
  8251. SSLClient cli("google.com");
  8252. cli.load_ca_cert_store(cert.data(), cert.size());
  8253. const auto res = cli.Get("/");
  8254. ASSERT_TRUE(res);
  8255. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8256. }
  8257. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  8258. // clang-format off
  8259. static constexpr char cert[] =
  8260. "GlobalSign Root CA\n"
  8261. "==================\n"
  8262. "-----BEGIN CERTIFICATE-----\n"
  8263. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  8264. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  8265. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  8266. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  8267. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  8268. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  8269. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  8270. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  8271. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  8272. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  8273. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  8274. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  8275. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  8276. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  8277. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  8278. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  8279. "-----END CERTIFICATE-----\n";
  8280. // clang-format on
  8281. SSLClient cli("google.com");
  8282. cli.load_ca_cert_store(cert, sizeof(cert));
  8283. const auto res = cli.Get("/");
  8284. ASSERT_TRUE(res);
  8285. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  8286. }
  8287. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  8288. SSLClient cli("www.youtube.com");
  8289. cli.set_ca_cert_path(CA_CERT_FILE);
  8290. cli.enable_server_certificate_verification(true);
  8291. cli.set_follow_location(true);
  8292. auto res = cli.Get("/");
  8293. ASSERT_TRUE(res);
  8294. ASSERT_EQ(StatusCode::OK_200, res->status);
  8295. }
  8296. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  8297. SSLClient cli("wWw.YouTube.Com");
  8298. cli.set_ca_cert_path(CA_CERT_FILE);
  8299. cli.enable_server_certificate_verification(true);
  8300. cli.enable_server_hostname_verification(true);
  8301. cli.set_follow_location(true);
  8302. auto res = cli.Get("/");
  8303. ASSERT_TRUE(res);
  8304. ASSERT_EQ(StatusCode::OK_200, res->status);
  8305. }
  8306. TEST(SSLClientTest, HostNameMatchCase_Online) {
  8307. SSLClient cli("gOoGlE.COm");
  8308. cli.enable_server_certificate_verification(true);
  8309. cli.enable_server_hostname_verification(true);
  8310. cli.set_follow_location(true);
  8311. auto res = cli.Get("/");
  8312. ASSERT_TRUE(res);
  8313. ASSERT_EQ(StatusCode::OK_200, res->status);
  8314. }
  8315. TEST(SSLClientTest, Issue2004_Online) {
  8316. Client client("https://google.com");
  8317. client.set_follow_location(true);
  8318. auto res = client.Get("/");
  8319. ASSERT_TRUE(res);
  8320. ASSERT_EQ(StatusCode::OK_200, res->status);
  8321. auto body = res->body;
  8322. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  8323. }
  8324. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  8325. // Create SSLClient with invalid cert/key to make is_valid() return false
  8326. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  8327. "nonexistent_key.pem");
  8328. // is_valid() should be false due to cert loading failure
  8329. ASSERT_FALSE(cli.is_valid());
  8330. auto res = cli.Get("/");
  8331. ASSERT_FALSE(res);
  8332. EXPECT_EQ(Error::SSLConnection, res.error());
  8333. }
  8334. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  8335. // Test for Issue #2251: SSL error not properly reported when client cert
  8336. // and key paths are swapped or mismatched
  8337. // This simulates the scenario where user accidentally swaps the cert and key
  8338. // files
  8339. // Using client cert file as private key and vice versa (completely wrong)
  8340. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  8341. // Should fail validation due to cert/key mismatch
  8342. ASSERT_FALSE(cli.is_valid());
  8343. // Attempt to make a request should fail with proper error
  8344. auto res = cli.Get("/");
  8345. ASSERT_FALSE(res);
  8346. EXPECT_EQ(Error::SSLConnection, res.error());
  8347. // SSL error should be recorded in the Result object (this is the key fix for
  8348. // Issue #2251)
  8349. auto backend_error = res.ssl_backend_error();
  8350. EXPECT_NE(0u, backend_error);
  8351. }
  8352. // Tests cert/key mismatch detection at the TLS context level
  8353. TEST(TlsApiTest, ClientCertKeyMismatch) {
  8354. // Test that using mismatched cert/key causes connection failure.
  8355. // We verify this at the SSLClient level rather than through internal
  8356. // TLS API functions.
  8357. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  8358. cli.enable_server_certificate_verification(false);
  8359. cli.set_connection_timeout(2);
  8360. // The mismatch should cause a connection or handshake error
  8361. auto res = cli.Get("/test");
  8362. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  8363. // Either way, the request should fail
  8364. EXPECT_FALSE(res);
  8365. }
  8366. #endif
  8367. #if 0
  8368. TEST(SSLClientTest, SetInterfaceWithINET6) {
  8369. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  8370. ASSERT_TRUE(cli != nullptr);
  8371. cli->set_address_family(AF_INET6);
  8372. cli->set_interface("en0");
  8373. auto res = cli->Get("/get");
  8374. ASSERT_TRUE(res);
  8375. ASSERT_EQ(StatusCode::OK_200, res->status);
  8376. }
  8377. #endif
  8378. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  8379. #ifdef CPPHTTPLIB_SSL_ENABLED
  8380. void ClientCertPresent(
  8381. const std::string &client_cert_file,
  8382. const std::string &client_private_key_file,
  8383. const std::string &client_encrypted_private_key_pass = std::string()) {
  8384. using namespace httplib::tls;
  8385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8386. CLIENT_CA_CERT_DIR);
  8387. ASSERT_TRUE(svr.is_valid());
  8388. svr.Get("/test", [&](const Request &req, Response &res) {
  8389. res.set_content("test", "text/plain");
  8390. auto cert = req.peer_cert();
  8391. ASSERT_TRUE(static_cast<bool>(cert));
  8392. std::string common_name = cert.subject_cn();
  8393. EXPECT_EQ("Common Name", common_name);
  8394. });
  8395. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8396. auto se = detail::scope_exit([&] {
  8397. svr.stop();
  8398. t.join();
  8399. ASSERT_FALSE(svr.is_running());
  8400. });
  8401. svr.wait_until_ready();
  8402. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  8403. client_encrypted_private_key_pass);
  8404. cli.enable_server_certificate_verification(false);
  8405. cli.set_connection_timeout(30);
  8406. auto res = cli.Get("/test");
  8407. ASSERT_TRUE(res);
  8408. ASSERT_EQ(StatusCode::OK_200, res->status);
  8409. }
  8410. TEST(SSLClientServerTest, ClientCertPresent) {
  8411. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8412. }
  8413. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  8414. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8415. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8416. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8417. }
  8418. // PEM memory-based constructor tests (works with all TLS backends)
  8419. void PemMemoryClientCertPresent(
  8420. const std::string &client_cert_file,
  8421. const std::string &client_private_key_file,
  8422. const std::string &client_encrypted_private_key_pass = std::string()) {
  8423. // Read PEM files into memory
  8424. std::string server_cert_pem, server_key_pem;
  8425. std::string client_ca_pem;
  8426. std::string client_cert_pem, client_key_pem;
  8427. read_file(SERVER_CERT_FILE, server_cert_pem);
  8428. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8429. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8430. read_file(client_cert_file, client_cert_pem);
  8431. read_file(client_private_key_file, client_key_pem);
  8432. // Create server with PEM memory
  8433. SSLServer::PemMemory server_pem = {
  8434. server_cert_pem.c_str(),
  8435. server_cert_pem.size(),
  8436. server_key_pem.c_str(),
  8437. server_key_pem.size(),
  8438. client_ca_pem.c_str(),
  8439. client_ca_pem.size(),
  8440. nullptr // no password for server key
  8441. };
  8442. SSLServer svr(server_pem);
  8443. ASSERT_TRUE(svr.is_valid());
  8444. svr.Get("/test", [&](const Request &, Response &res) {
  8445. res.set_content("test", "text/plain");
  8446. });
  8447. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8448. auto se = detail::scope_exit([&] {
  8449. svr.stop();
  8450. t.join();
  8451. ASSERT_FALSE(svr.is_running());
  8452. });
  8453. svr.wait_until_ready();
  8454. // Create client with PEM memory
  8455. const char *password = client_encrypted_private_key_pass.empty()
  8456. ? nullptr
  8457. : client_encrypted_private_key_pass.c_str();
  8458. SSLClient::PemMemory client_pem = {
  8459. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  8460. client_key_pem.size(), password};
  8461. SSLClient cli(HOST, PORT, client_pem);
  8462. cli.enable_server_certificate_verification(false);
  8463. cli.set_connection_timeout(30);
  8464. auto res = cli.Get("/test");
  8465. ASSERT_TRUE(res);
  8466. ASSERT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  8469. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8470. }
  8471. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  8472. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  8473. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  8474. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  8475. }
  8476. TEST(SSLClientServerTest, ClientCertMissing) {
  8477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8478. CLIENT_CA_CERT_DIR);
  8479. ASSERT_TRUE(svr.is_valid());
  8480. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  8481. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8482. auto se = detail::scope_exit([&] {
  8483. svr.stop();
  8484. t.join();
  8485. ASSERT_FALSE(svr.is_running());
  8486. });
  8487. svr.wait_until_ready();
  8488. SSLClient cli(HOST, PORT);
  8489. cli.set_connection_timeout(30);
  8490. auto res = cli.Get("/test");
  8491. ASSERT_TRUE(!res);
  8492. // When client cert is missing and server requires it, connection fails
  8493. // Error type depends on backend implementation
  8494. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  8495. res.error() == Error::SSLConnection);
  8496. // Verify backend error is captured
  8497. // Note: This test may have different error codes depending on the exact
  8498. // verification failure
  8499. EXPECT_NE(0UL, res.ssl_backend_error());
  8500. }
  8501. TEST(SSLClientServerTest, TrustDirOptional) {
  8502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8503. ASSERT_TRUE(svr.is_valid());
  8504. svr.Get("/test", [&](const Request &, Response &res) {
  8505. res.set_content("test", "text/plain");
  8506. });
  8507. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8508. auto se = detail::scope_exit([&] {
  8509. svr.stop();
  8510. t.join();
  8511. ASSERT_FALSE(svr.is_running());
  8512. });
  8513. svr.wait_until_ready();
  8514. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8515. cli.enable_server_certificate_verification(false);
  8516. cli.set_connection_timeout(30);
  8517. auto res = cli.Get("/test");
  8518. ASSERT_TRUE(res);
  8519. ASSERT_EQ(StatusCode::OK_200, res->status);
  8520. }
  8521. TEST(SSLClientServerTest, SSLConnectTimeout) {
  8522. class NoListenSSLServer : public SSLServer {
  8523. public:
  8524. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  8525. const char *client_ca_cert_file_path,
  8526. const char *client_ca_cert_dir_path = nullptr)
  8527. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  8528. client_ca_cert_dir_path),
  8529. stop_(false) {}
  8530. std::atomic_bool stop_;
  8531. private:
  8532. bool process_and_close_socket(socket_t /*sock*/) override {
  8533. // Don't create SSL context
  8534. while (!stop_.load()) {
  8535. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8536. }
  8537. return true;
  8538. }
  8539. };
  8540. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8541. CLIENT_CA_CERT_FILE);
  8542. ASSERT_TRUE(svr.is_valid());
  8543. svr.Get("/test", [&](const Request &, Response &res) {
  8544. res.set_content("test", "text/plain");
  8545. });
  8546. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8547. auto se = detail::scope_exit([&] {
  8548. svr.stop_ = true;
  8549. svr.stop();
  8550. t.join();
  8551. ASSERT_FALSE(svr.is_running());
  8552. });
  8553. svr.wait_until_ready();
  8554. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8555. cli.enable_server_certificate_verification(false);
  8556. cli.set_connection_timeout(1);
  8557. auto res = cli.Get("/test");
  8558. ASSERT_TRUE(!res);
  8559. EXPECT_EQ(Error::SSLConnection, res.error());
  8560. // Timeout results in WantRead error code (maps to backend-specific value)
  8561. EXPECT_NE(0, res.ssl_error());
  8562. }
  8563. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  8564. // Test SSLServer with client certificate verification using the standard
  8565. // constructor (ContextSetupCallback is tested by backend-specific tests)
  8566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  8567. CLIENT_CA_CERT_DIR);
  8568. ASSERT_TRUE(svr.is_valid());
  8569. svr.Get("/test", [&](const Request &req, Response &res) {
  8570. res.set_content("test", "text/plain");
  8571. auto cert = req.peer_cert();
  8572. ASSERT_TRUE(static_cast<bool>(cert));
  8573. auto common_name = cert.subject_cn();
  8574. EXPECT_EQ("Common Name", common_name);
  8575. });
  8576. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8577. auto se = detail::scope_exit([&] {
  8578. svr.stop();
  8579. t.join();
  8580. ASSERT_FALSE(svr.is_running());
  8581. });
  8582. svr.wait_until_ready();
  8583. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8584. cli.enable_server_certificate_verification(false);
  8585. cli.set_connection_timeout(30);
  8586. auto res = cli.Get("/test");
  8587. ASSERT_TRUE(res);
  8588. ASSERT_EQ(StatusCode::OK_200, res->status);
  8589. }
  8590. // Test verify_hostname for both OpenSSL and MbedTLS backends
  8591. // Verifies that wildcard matching and exact matching work consistently
  8592. TEST(SSLClientServerTest, TlsVerifyHostname) {
  8593. using namespace httplib::tls;
  8594. // We need a running server to test against
  8595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8596. ASSERT_TRUE(svr.is_valid());
  8597. svr.Get("/test", [](const Request &, Response &res) {
  8598. res.set_content("ok", "text/plain");
  8599. });
  8600. thread t([&]() { svr.listen(HOST, PORT); });
  8601. auto se = detail::scope_exit([&] {
  8602. svr.stop();
  8603. t.join();
  8604. });
  8605. svr.wait_until_ready();
  8606. bool verify_callback_called = false;
  8607. bool verify_result_wrong = false;
  8608. SSLClient cli(HOST, PORT);
  8609. cli.enable_server_certificate_verification(true);
  8610. cli.set_ca_cert_path(CA_CERT_FILE);
  8611. cli.set_connection_timeout(5);
  8612. // Note: Test certificate has CN="Common Name", not "localhost"
  8613. bool verify_result_cn = false;
  8614. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8615. verify_callback_called = true;
  8616. if (!ctx.cert) return false;
  8617. // Test 1: "Common Name" should match (our test server cert CN)
  8618. verify_result_cn = ctx.check_hostname("Common Name");
  8619. // Test 2: wrong hostname should not match
  8620. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  8621. return true; // Accept for the purpose of this test
  8622. });
  8623. auto res = cli.Get("/test");
  8624. // The request may succeed or fail depending on cert configuration
  8625. // but the callback should have been called
  8626. ASSERT_TRUE(verify_callback_called)
  8627. << "Verify callback should have been called";
  8628. // CN="Common Name" should match our test certificate
  8629. EXPECT_TRUE(verify_result_cn)
  8630. << "verify_hostname should match 'Common Name' (certificate CN)";
  8631. // Wrong hostname should not match
  8632. EXPECT_FALSE(verify_result_wrong)
  8633. << "verify_hostname should not match 'wronghost.example.com'";
  8634. }
  8635. #endif
  8636. // mbedTLS-specific callback constructor test
  8637. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  8638. #ifdef CPPHTTPLIB_SSL_ENABLED
  8639. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  8640. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8641. ASSERT_TRUE(svr.is_valid());
  8642. // Set up a handler to verify client certificate is present
  8643. bool client_cert_verified = false;
  8644. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8645. // Verify that client certificate was provided
  8646. client_cert_verified = true;
  8647. res.set_content("success", "text/plain");
  8648. });
  8649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8650. auto se = detail::scope_exit([&] {
  8651. svr.stop();
  8652. t.join();
  8653. ASSERT_FALSE(svr.is_running());
  8654. });
  8655. svr.wait_until_ready();
  8656. // Client with certificate
  8657. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8658. cli.enable_server_certificate_verification(false);
  8659. cli.set_connection_timeout(30);
  8660. auto res = cli.Get("/test");
  8661. ASSERT_TRUE(res);
  8662. ASSERT_EQ(StatusCode::OK_200, res->status);
  8663. ASSERT_TRUE(client_cert_verified);
  8664. EXPECT_EQ("success", res->body);
  8665. }
  8666. #endif
  8667. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  8668. // backends
  8669. #ifdef CPPHTTPLIB_SSL_ENABLED
  8670. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  8671. using namespace httplib::tls;
  8672. // Test that when client CA cert file is provided,
  8673. // the server properly requests and validates client certificates
  8674. // Create a server with client authentication
  8675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  8676. ASSERT_TRUE(svr.is_valid());
  8677. bool handler_called = false;
  8678. svr.Get("/test", [&](const Request &req, Response &res) {
  8679. handler_called = true;
  8680. // Verify that a client certificate was provided
  8681. auto cert = req.peer_cert();
  8682. ASSERT_TRUE(static_cast<bool>(cert));
  8683. // Get the issuer name
  8684. std::string issuer_str = cert.issuer_name();
  8685. ASSERT_FALSE(issuer_str.empty());
  8686. // The client certificate should be issued by our test CA
  8687. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  8688. res.set_content("authenticated", "text/plain");
  8689. });
  8690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8691. auto se = detail::scope_exit([&] {
  8692. svr.stop();
  8693. t.join();
  8694. ASSERT_FALSE(svr.is_running());
  8695. });
  8696. svr.wait_until_ready();
  8697. // Connect with a client certificate issued by the CA
  8698. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8699. cli.enable_server_certificate_verification(false);
  8700. cli.set_connection_timeout(30);
  8701. auto res = cli.Get("/test");
  8702. ASSERT_TRUE(res);
  8703. ASSERT_EQ(StatusCode::OK_200, res->status);
  8704. ASSERT_TRUE(handler_called);
  8705. EXPECT_EQ("authenticated", res->body);
  8706. }
  8707. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  8708. using namespace httplib::tls;
  8709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8710. ASSERT_TRUE(svr.is_valid());
  8711. svr.Get("/test", [](const Request &, Response &res) {
  8712. res.set_content("ok", "text/plain");
  8713. });
  8714. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8715. auto se = detail::scope_exit([&] {
  8716. svr.stop();
  8717. t.join();
  8718. });
  8719. svr.wait_until_ready();
  8720. SSLClient cli(HOST, PORT);
  8721. cli.enable_server_certificate_verification(false);
  8722. cli.set_connection_timeout(30);
  8723. bool cert_checked = false;
  8724. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8725. if (ctx.cert) {
  8726. auto sans = ctx.sans();
  8727. // Test certificate may or may not have SANs - just verify the API
  8728. // works If SANs exist, verify the types are valid
  8729. for (const auto &san : sans) {
  8730. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  8731. san.type == SanType::EMAIL || san.type == SanType::URI ||
  8732. san.type == SanType::OTHER);
  8733. EXPECT_FALSE(san.value.empty());
  8734. }
  8735. cert_checked = true;
  8736. }
  8737. return true;
  8738. });
  8739. auto res = cli.Get("/test");
  8740. ASSERT_TRUE(res);
  8741. EXPECT_TRUE(cert_checked);
  8742. }
  8743. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  8744. using namespace httplib::tls;
  8745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8746. ASSERT_TRUE(svr.is_valid());
  8747. svr.Get("/test", [](const Request &, Response &res) {
  8748. res.set_content("ok", "text/plain");
  8749. });
  8750. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8751. auto se = detail::scope_exit([&] {
  8752. svr.stop();
  8753. t.join();
  8754. });
  8755. svr.wait_until_ready();
  8756. SSLClient cli(HOST, PORT);
  8757. cli.enable_server_certificate_verification(false);
  8758. cli.set_connection_timeout(30);
  8759. bool validity_checked = false;
  8760. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8761. if (ctx.cert) {
  8762. time_t not_before = 0, not_after = 0;
  8763. bool result = ctx.validity(not_before, not_after);
  8764. EXPECT_TRUE(result);
  8765. // Verify that not_before < now < not_after for a valid cert
  8766. time_t now = time(nullptr);
  8767. EXPECT_LT(not_before, now);
  8768. EXPECT_GT(not_after, now);
  8769. validity_checked = true;
  8770. }
  8771. return true;
  8772. });
  8773. auto res = cli.Get("/test");
  8774. ASSERT_TRUE(res);
  8775. EXPECT_TRUE(validity_checked);
  8776. }
  8777. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  8778. using namespace httplib::tls;
  8779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8780. ASSERT_TRUE(svr.is_valid());
  8781. svr.Get("/test", [](const Request &, Response &res) {
  8782. res.set_content("ok", "text/plain");
  8783. });
  8784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8785. auto se = detail::scope_exit([&] {
  8786. svr.stop();
  8787. t.join();
  8788. });
  8789. svr.wait_until_ready();
  8790. SSLClient cli(HOST, PORT);
  8791. cli.enable_server_certificate_verification(false);
  8792. cli.set_connection_timeout(30);
  8793. bool serial_checked = false;
  8794. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8795. if (ctx.cert) {
  8796. std::string serial = ctx.serial();
  8797. EXPECT_FALSE(serial.empty());
  8798. // Serial should be a hex string
  8799. for (char c : serial) {
  8800. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8801. (c >= 'a' && c <= 'f'));
  8802. }
  8803. serial_checked = true;
  8804. }
  8805. return true;
  8806. });
  8807. auto res = cli.Get("/test");
  8808. ASSERT_TRUE(res);
  8809. EXPECT_TRUE(serial_checked);
  8810. }
  8811. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8812. // Test 1: Valid CA file - no error should be recorded
  8813. {
  8814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8815. CLIENT_CA_CERT_FILE);
  8816. ASSERT_TRUE(svr.is_valid());
  8817. // With valid setup, last_ssl_error should be 0
  8818. EXPECT_EQ(0, svr.ssl_last_error());
  8819. }
  8820. // Test 2: Invalid CA file content
  8821. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8822. {
  8823. // Create a temporary file with completely invalid content
  8824. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8825. {
  8826. std::ofstream ofs(temp_invalid_ca);
  8827. ofs << "This is not a certificate file at all\n";
  8828. ofs << "Just plain text content\n";
  8829. }
  8830. // Create server with invalid CA file
  8831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8832. // Clean up temporary file
  8833. std::remove(temp_invalid_ca);
  8834. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8835. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8836. // Note: SSL_CTX_load_verify_locations typically fails first,
  8837. // but our error handling code path is still exercised
  8838. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8839. }
  8840. }
  8841. TEST(VerifyCallbackTest, VerifyContextFields) {
  8842. using namespace httplib::tls;
  8843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8844. ASSERT_TRUE(svr.is_valid());
  8845. svr.Get("/test", [](const Request &, Response &res) {
  8846. res.set_content("ok", "text/plain");
  8847. });
  8848. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8849. auto se = detail::scope_exit([&] {
  8850. svr.stop();
  8851. t.join();
  8852. });
  8853. svr.wait_until_ready();
  8854. SSLClient cli(HOST, PORT);
  8855. cli.enable_server_certificate_verification(false);
  8856. cli.set_connection_timeout(30);
  8857. int callback_count = 0;
  8858. bool saw_leaf_cert = false;
  8859. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  8860. if (ctx.cert) {
  8861. callback_count++;
  8862. // We should see at least one certificate (the leaf)
  8863. std::string cn = ctx.subject_cn();
  8864. if (!cn.empty()) { saw_leaf_cert = true; }
  8865. // Verify context fields are populated
  8866. EXPECT_NE(ctx.session, nullptr);
  8867. EXPECT_GE(ctx.depth, 0);
  8868. }
  8869. return true;
  8870. });
  8871. auto res = cli.Get("/test");
  8872. ASSERT_TRUE(res);
  8873. EXPECT_GT(callback_count, 0);
  8874. EXPECT_TRUE(saw_leaf_cert);
  8875. }
  8876. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8877. using httplib::tls::TlsError;
  8878. // Test that verify_error_to_string returns empty for success
  8879. std::string success_str = TlsError::verify_error_to_string(0);
  8880. EXPECT_TRUE(success_str.empty());
  8881. // Test that verify_error_to_string returns non-empty for error codes
  8882. // Using a common error code (certificate expired)
  8883. std::string error_str =
  8884. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8885. EXPECT_FALSE(error_str.empty());
  8886. }
  8887. TEST(SessionVerifierTest, CertificateAccepted) {
  8888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8889. ASSERT_TRUE(svr.is_valid());
  8890. svr.Get("/test", [](const Request &, Response &res) {
  8891. res.set_content("ok", "text/plain");
  8892. });
  8893. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8894. auto se = detail::scope_exit([&] {
  8895. svr.stop();
  8896. t.join();
  8897. });
  8898. svr.wait_until_ready();
  8899. SSLClient cli(HOST, PORT);
  8900. cli.enable_server_certificate_verification(false);
  8901. cli.set_connection_timeout(30);
  8902. bool callback_called = false;
  8903. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8904. EXPECT_NE(session, nullptr);
  8905. callback_called = true;
  8906. return SSLVerifierResponse::CertificateAccepted;
  8907. });
  8908. auto res = cli.Get("/test");
  8909. ASSERT_TRUE(res);
  8910. EXPECT_EQ(200, res->status);
  8911. EXPECT_TRUE(callback_called);
  8912. }
  8913. TEST(SessionVerifierTest, CertificateRejected) {
  8914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8915. ASSERT_TRUE(svr.is_valid());
  8916. svr.Get("/test", [](const Request &, Response &res) {
  8917. res.set_content("ok", "text/plain");
  8918. });
  8919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8920. auto se = detail::scope_exit([&] {
  8921. svr.stop();
  8922. t.join();
  8923. });
  8924. svr.wait_until_ready();
  8925. SSLClient cli(HOST, PORT);
  8926. cli.enable_server_certificate_verification(false);
  8927. cli.set_connection_timeout(30);
  8928. bool callback_called = false;
  8929. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8930. EXPECT_NE(session, nullptr);
  8931. callback_called = true;
  8932. return SSLVerifierResponse::CertificateRejected;
  8933. });
  8934. auto res = cli.Get("/test");
  8935. EXPECT_FALSE(res);
  8936. EXPECT_TRUE(callback_called);
  8937. }
  8938. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  8939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8940. ASSERT_TRUE(svr.is_valid());
  8941. svr.Get("/test", [](const Request &, Response &res) {
  8942. res.set_content("ok", "text/plain");
  8943. });
  8944. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8945. auto se = detail::scope_exit([&] {
  8946. svr.stop();
  8947. t.join();
  8948. });
  8949. svr.wait_until_ready();
  8950. // NoDecisionMade with verification disabled should succeed (no default check)
  8951. SSLClient cli(HOST, PORT);
  8952. cli.enable_server_certificate_verification(false);
  8953. cli.set_connection_timeout(30);
  8954. bool callback_called = false;
  8955. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8956. EXPECT_NE(session, nullptr);
  8957. callback_called = true;
  8958. return SSLVerifierResponse::NoDecisionMade;
  8959. });
  8960. auto res = cli.Get("/test");
  8961. ASSERT_TRUE(res);
  8962. EXPECT_EQ(200, res->status);
  8963. EXPECT_TRUE(callback_called);
  8964. }
  8965. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  8966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8967. ASSERT_TRUE(svr.is_valid());
  8968. svr.Get("/test", [](const Request &, Response &res) {
  8969. res.set_content("ok", "text/plain");
  8970. });
  8971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8972. auto se = detail::scope_exit([&] {
  8973. svr.stop();
  8974. t.join();
  8975. });
  8976. svr.wait_until_ready();
  8977. // NoDecisionMade with verification enabled should fail (self-signed cert).
  8978. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  8979. // so we only check that the request fails, not whether the callback was
  8980. // called.
  8981. SSLClient cli(HOST, PORT);
  8982. cli.enable_server_certificate_verification(true);
  8983. cli.set_connection_timeout(30);
  8984. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  8985. EXPECT_NE(session, nullptr);
  8986. return SSLVerifierResponse::NoDecisionMade;
  8987. });
  8988. auto res = cli.Get("/test");
  8989. EXPECT_FALSE(res);
  8990. }
  8991. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8992. // Test SSL server using PemMemory constructor with client CA certificates
  8993. // Read PEM files
  8994. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8995. read_file(SERVER_CERT_FILE, server_cert_pem);
  8996. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8997. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8998. // Create SSLServer with PemMemory constructor including client CA
  8999. SSLServer::PemMemory server_pem = {
  9000. server_cert_pem.c_str(),
  9001. server_cert_pem.size(),
  9002. server_key_pem.c_str(),
  9003. server_key_pem.size(),
  9004. client_ca_pem.c_str(),
  9005. client_ca_pem.size(),
  9006. nullptr // no password for server key
  9007. };
  9008. SSLServer svr(server_pem);
  9009. ASSERT_TRUE(svr.is_valid());
  9010. // No SSL error should be recorded for valid setup
  9011. EXPECT_EQ(0, svr.ssl_last_error());
  9012. // Set up server endpoints
  9013. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  9014. res.set_content("ok", "text/plain");
  9015. });
  9016. // Start server in a thread
  9017. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  9018. svr.wait_until_ready();
  9019. // Connect with client certificate (using constructor with paths)
  9020. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  9021. cli.enable_server_certificate_verification(false);
  9022. auto res = cli.Get("/test-pem-ca");
  9023. ASSERT_TRUE(res);
  9024. EXPECT_EQ(200, res->status);
  9025. EXPECT_EQ("ok", res->body);
  9026. svr.stop();
  9027. server_thread.join();
  9028. }
  9029. #endif
  9030. #ifdef _WIN32
  9031. TEST(CleanupTest, WSACleanup) {
  9032. int ret = WSACleanup();
  9033. ASSERT_EQ(0, ret);
  9034. }
  9035. #endif
  9036. #ifndef CPPHTTPLIB_SSL_ENABLED
  9037. TEST(NoSSLSupport, SimpleInterface) {
  9038. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  9039. }
  9040. #endif
  9041. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9042. TEST(InvalidScheme, SimpleInterface) {
  9043. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  9044. }
  9045. #endif
  9046. TEST(NoScheme, SimpleInterface) {
  9047. Client cli("yahoo.com:80");
  9048. ASSERT_TRUE(cli.is_valid());
  9049. }
  9050. TEST(SendAPI, SimpleInterface_Online) {
  9051. Client cli("http://yahoo.com");
  9052. Request req;
  9053. req.method = "GET";
  9054. req.path = "/";
  9055. auto res = cli.send(req);
  9056. ASSERT_TRUE(res);
  9057. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9058. }
  9059. TEST(SendAPI, WithParamsInRequest) {
  9060. Server svr;
  9061. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  9062. EXPECT_TRUE(req.has_param("test"));
  9063. EXPECT_EQ("test_value", req.get_param_value("test"));
  9064. });
  9065. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  9066. auto se = detail::scope_exit([&] {
  9067. svr.stop();
  9068. t.join();
  9069. ASSERT_FALSE(svr.is_running());
  9070. });
  9071. svr.wait_until_ready();
  9072. Client cli(HOST, PORT);
  9073. {
  9074. Request req;
  9075. req.method = "GET";
  9076. req.path = "/";
  9077. req.params.emplace("test", "test_value");
  9078. auto res = cli.send(req);
  9079. ASSERT_TRUE(res);
  9080. }
  9081. {
  9082. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  9083. ASSERT_TRUE(res);
  9084. }
  9085. }
  9086. TEST(ClientImplMethods, GetSocketTest) {
  9087. httplib::Server svr;
  9088. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9089. res.status = StatusCode::OK_200;
  9090. });
  9091. auto port = svr.bind_to_any_port("127.0.0.1");
  9092. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9093. auto se = detail::scope_exit([&] {
  9094. svr.stop();
  9095. thread.join();
  9096. ASSERT_FALSE(svr.is_running());
  9097. });
  9098. svr.wait_until_ready();
  9099. {
  9100. httplib::Client cli("127.0.0.1", port);
  9101. cli.set_keep_alive(true);
  9102. // Use the behavior of cpp-httplib of opening the connection
  9103. // only when the first request happens. If that changes,
  9104. // this test would be obsolete.
  9105. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  9106. // This also implicitly tests the server. But other tests would fail much
  9107. // earlier than this one to be considered.
  9108. auto res = cli.Get("/");
  9109. ASSERT_TRUE(res);
  9110. EXPECT_EQ(StatusCode::OK_200, res->status);
  9111. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  9112. }
  9113. }
  9114. #ifdef CPPHTTPLIB_SSL_ENABLED
  9115. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  9116. Client cli("http://yahoo.com");
  9117. auto res = cli.Get("/");
  9118. ASSERT_TRUE(res);
  9119. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9120. cli.set_follow_location(true);
  9121. res = cli.Get("/");
  9122. ASSERT_TRUE(res);
  9123. EXPECT_EQ(StatusCode::OK_200, res->status);
  9124. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9125. }
  9126. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  9127. Client cli("https://yahoo.com");
  9128. auto res = cli.Get("/");
  9129. ASSERT_TRUE(res);
  9130. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9131. cli.set_follow_location(true);
  9132. res = cli.Get("/");
  9133. ASSERT_TRUE(res);
  9134. EXPECT_EQ(StatusCode::OK_200, res->status);
  9135. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9136. }
  9137. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  9138. Client cli("https://yahoo.com");
  9139. auto res = cli.Get("/");
  9140. ASSERT_TRUE(res);
  9141. ASSERT_FALSE(!res);
  9142. ASSERT_TRUE(res);
  9143. ASSERT_FALSE(res == nullptr);
  9144. ASSERT_TRUE(res != nullptr);
  9145. EXPECT_EQ(Error::Success, res.error());
  9146. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  9147. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  9148. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9149. cli.set_follow_location(true);
  9150. res = cli.Get("/");
  9151. ASSERT_TRUE(res);
  9152. EXPECT_EQ(Error::Success, res.error());
  9153. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  9154. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. EXPECT_EQ("https://www.yahoo.com/", res->location);
  9157. }
  9158. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9159. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  9160. Client cli("https://cdnjs.cloudflare.com");
  9161. auto res =
  9162. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  9163. ASSERT_TRUE(res);
  9164. EXPECT_EQ(StatusCode::OK_200, res->status);
  9165. EXPECT_EQ(287630U, res->body.size());
  9166. EXPECT_EQ("application/javascript; charset=utf-8",
  9167. res->get_header_value("Content-Type"));
  9168. }
  9169. #endif
  9170. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  9171. #undef REDIR_HOST // Silence compiler warning
  9172. #define REDIR_HOST "https://httpbingo.org"
  9173. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  9174. Client cli(REDIR_HOST);
  9175. cli.set_follow_location(true);
  9176. auto res =
  9177. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  9178. ASSERT_TRUE(res);
  9179. EXPECT_EQ(StatusCode::OK_200, res->status);
  9180. }
  9181. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  9182. Client cli(REDIR_HOST);
  9183. cli.set_follow_location(true);
  9184. Params params;
  9185. params.emplace("url", "http://example.com");
  9186. params.emplace("status_code", "302");
  9187. auto res = cli.Get(REDIR_PATH, params, Headers{});
  9188. ASSERT_TRUE(res);
  9189. EXPECT_EQ(StatusCode::OK_200, res->status);
  9190. }
  9191. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  9192. Client cli(REDIR_HOST);
  9193. cli.set_follow_location(true);
  9194. Params params;
  9195. params.emplace("url", "http://example.com");
  9196. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  9197. ASSERT_TRUE(res);
  9198. EXPECT_EQ(StatusCode::OK_200, res->status);
  9199. }
  9200. TEST(HttpToHttpsRedirectTest, CertFile) {
  9201. auto ssl_port = PORT + 1;
  9202. Server svr;
  9203. ASSERT_TRUE(svr.is_valid());
  9204. svr.Get("/index", [&](const Request &, Response &res) {
  9205. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9206. "/index");
  9207. svr.stop();
  9208. });
  9209. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9210. ASSERT_TRUE(ssl_svr.is_valid());
  9211. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  9212. res.set_content("test", "text/plain");
  9213. ssl_svr.stop();
  9214. });
  9215. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  9216. thread t2 =
  9217. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  9218. auto se = detail::scope_exit([&] {
  9219. t2.join();
  9220. t.join();
  9221. ASSERT_FALSE(svr.is_running());
  9222. });
  9223. svr.wait_until_ready();
  9224. ssl_svr.wait_until_ready();
  9225. Client cli("127.0.0.1", PORT);
  9226. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  9227. cli.enable_server_certificate_verification(true);
  9228. cli.set_follow_location(true);
  9229. cli.set_connection_timeout(30);
  9230. auto res = cli.Get("/index");
  9231. ASSERT_TRUE(res);
  9232. ASSERT_EQ(StatusCode::OK_200, res->status);
  9233. }
  9234. TEST(SSLClientRedirectTest, CertFile) {
  9235. auto ssl_port = PORT + 1;
  9236. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9237. ASSERT_TRUE(ssl_svr1.is_valid());
  9238. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  9239. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  9240. "/index");
  9241. ssl_svr1.stop();
  9242. });
  9243. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  9244. ASSERT_TRUE(ssl_svr2.is_valid());
  9245. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  9246. res.set_content("test", "text/plain");
  9247. ssl_svr2.stop();
  9248. });
  9249. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  9250. thread t2 =
  9251. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  9252. auto se = detail::scope_exit([&] {
  9253. t2.join();
  9254. t.join();
  9255. ASSERT_FALSE(ssl_svr1.is_running());
  9256. });
  9257. ssl_svr1.wait_until_ready();
  9258. ssl_svr2.wait_until_ready();
  9259. SSLClient cli("127.0.0.1", PORT);
  9260. std::string cert;
  9261. read_file(SERVER_CERT2_FILE, cert);
  9262. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9263. cli.enable_server_certificate_verification(true);
  9264. cli.set_follow_location(true);
  9265. cli.set_connection_timeout(30);
  9266. auto res = cli.Get("/index");
  9267. ASSERT_TRUE(res);
  9268. ASSERT_EQ(StatusCode::OK_200, res->status);
  9269. }
  9270. #endif
  9271. #ifdef CPPHTTPLIB_SSL_ENABLED
  9272. // Test that set_ca_cert_store() skips system certs (consistent with
  9273. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  9274. // should be trusted - system certs should NOT be loaded.
  9275. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  9276. // Load a specific cert that is NOT a system CA cert
  9277. std::string cert;
  9278. read_file(SERVER_CERT2_FILE, cert);
  9279. SSLClient cli("google.com");
  9280. cli.load_ca_cert_store(cert.c_str(), cert.size());
  9281. cli.enable_server_certificate_verification(true);
  9282. // This should FAIL because:
  9283. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  9284. // 2. System certs should NOT be loaded when custom store is set
  9285. // If system certs WERE loaded, this would succeed
  9286. auto res = cli.Get("/");
  9287. ASSERT_FALSE(res);
  9288. EXPECT_EQ(Error::SSLServerVerification, res.error());
  9289. }
  9290. TEST(MultipartFormDataTest, LargeData) {
  9291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9292. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  9293. const ContentReader &content_reader) {
  9294. if (req.is_multipart_form_data()) {
  9295. std::vector<FormData> items;
  9296. content_reader(
  9297. [&](const FormData &file) {
  9298. items.push_back(file);
  9299. return true;
  9300. },
  9301. [&](const char *data, size_t data_length) {
  9302. items.back().content.append(data, data_length);
  9303. return true;
  9304. });
  9305. EXPECT_TRUE(std::string(items[0].name) == "document");
  9306. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9307. EXPECT_TRUE(items[0].filename == "2MB_data");
  9308. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9309. EXPECT_TRUE(items[1].name == "hello");
  9310. EXPECT_TRUE(items[1].content == "world");
  9311. EXPECT_TRUE(items[1].filename == "");
  9312. EXPECT_TRUE(items[1].content_type == "");
  9313. } else {
  9314. std::string body;
  9315. content_reader([&](const char *data, size_t data_length) {
  9316. body.append(data, data_length);
  9317. return true;
  9318. });
  9319. }
  9320. });
  9321. auto port = svr.bind_to_any_port(HOST);
  9322. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9323. auto se = detail::scope_exit([&] {
  9324. svr.stop();
  9325. t.join();
  9326. ASSERT_FALSE(svr.is_running());
  9327. });
  9328. svr.wait_until_ready();
  9329. {
  9330. std::string data(1024 * 1024 * 2, '.');
  9331. std::stringstream buffer;
  9332. buffer << data;
  9333. SSLClient cli(HOST, port);
  9334. cli.enable_server_certificate_verification(false);
  9335. UploadFormDataItems items{
  9336. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9337. {"hello", "world", "", ""},
  9338. };
  9339. auto res = cli.Post("/post", items);
  9340. ASSERT_TRUE(res);
  9341. ASSERT_EQ(StatusCode::OK_200, res->status);
  9342. }
  9343. }
  9344. TEST(MultipartFormDataTest, DataProviderItems) {
  9345. std::random_device seed_gen;
  9346. std::mt19937 random(seed_gen());
  9347. std::string rand1;
  9348. rand1.resize(1000);
  9349. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  9350. std::string rand2;
  9351. rand2.resize(3000);
  9352. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  9353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9354. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  9355. const ContentReader &content_reader) {
  9356. ASSERT_FALSE(req.is_multipart_form_data());
  9357. std::string body;
  9358. content_reader([&](const char *data, size_t data_length) {
  9359. body.append(data, data_length);
  9360. return true;
  9361. });
  9362. EXPECT_EQ(body, "");
  9363. });
  9364. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  9365. const ContentReader &content_reader) {
  9366. ASSERT_TRUE(req.is_multipart_form_data());
  9367. std::vector<FormData> items;
  9368. content_reader(
  9369. [&](const FormData &file) {
  9370. items.push_back(file);
  9371. return true;
  9372. },
  9373. [&](const char *data, size_t data_length) {
  9374. items.back().content.append(data, data_length);
  9375. return true;
  9376. });
  9377. ASSERT_TRUE(items.size() == 2);
  9378. EXPECT_EQ(std::string(items[0].name), "name1");
  9379. EXPECT_EQ(items[0].content, "Testing123");
  9380. EXPECT_EQ(items[0].filename, "filename1");
  9381. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9382. EXPECT_EQ(items[1].name, "name2");
  9383. EXPECT_EQ(items[1].content, "Testing456");
  9384. EXPECT_EQ(items[1].filename, "");
  9385. EXPECT_EQ(items[1].content_type, "");
  9386. });
  9387. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  9388. const ContentReader &content_reader) {
  9389. ASSERT_TRUE(req.is_multipart_form_data());
  9390. std::vector<FormData> items;
  9391. content_reader(
  9392. [&](const FormData &file) {
  9393. items.push_back(file);
  9394. return true;
  9395. },
  9396. [&](const char *data, size_t data_length) {
  9397. items.back().content.append(data, data_length);
  9398. return true;
  9399. });
  9400. ASSERT_TRUE(items.size() == 2);
  9401. EXPECT_EQ(items[0].name, "name3");
  9402. EXPECT_EQ(items[0].content, rand1);
  9403. EXPECT_EQ(items[0].filename, "filename3");
  9404. EXPECT_EQ(items[0].content_type, "");
  9405. EXPECT_EQ(items[1].name, "name4");
  9406. EXPECT_EQ(items[1].content, rand2);
  9407. EXPECT_EQ(items[1].filename, "filename4");
  9408. EXPECT_EQ(items[1].content_type, "");
  9409. });
  9410. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  9411. const ContentReader &content_reader) {
  9412. ASSERT_TRUE(req.is_multipart_form_data());
  9413. std::vector<FormData> items;
  9414. content_reader(
  9415. [&](const FormData &file) {
  9416. items.push_back(file);
  9417. return true;
  9418. },
  9419. [&](const char *data, size_t data_length) {
  9420. items.back().content.append(data, data_length);
  9421. return true;
  9422. });
  9423. ASSERT_TRUE(items.size() == 4);
  9424. EXPECT_EQ(std::string(items[0].name), "name1");
  9425. EXPECT_EQ(items[0].content, "Testing123");
  9426. EXPECT_EQ(items[0].filename, "filename1");
  9427. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  9428. EXPECT_EQ(items[1].name, "name2");
  9429. EXPECT_EQ(items[1].content, "Testing456");
  9430. EXPECT_EQ(items[1].filename, "");
  9431. EXPECT_EQ(items[1].content_type, "");
  9432. EXPECT_EQ(items[2].name, "name3");
  9433. EXPECT_EQ(items[2].content, rand1);
  9434. EXPECT_EQ(items[2].filename, "filename3");
  9435. EXPECT_EQ(items[2].content_type, "");
  9436. EXPECT_EQ(items[3].name, "name4");
  9437. EXPECT_EQ(items[3].content, rand2);
  9438. EXPECT_EQ(items[3].filename, "filename4");
  9439. EXPECT_EQ(items[3].content_type, "");
  9440. });
  9441. auto port = svr.bind_to_any_port("localhost");
  9442. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9443. auto se = detail::scope_exit([&] {
  9444. svr.stop();
  9445. t.join();
  9446. ASSERT_FALSE(svr.is_running());
  9447. });
  9448. svr.wait_until_ready();
  9449. {
  9450. SSLClient cli("localhost", port);
  9451. cli.enable_server_certificate_verification(false);
  9452. UploadFormDataItems items{
  9453. {"name1", "Testing123", "filename1", "application/octet-stream"},
  9454. {"name2", "Testing456", "", ""}, // not a file
  9455. };
  9456. {
  9457. auto res = cli.Post("/post-none", {}, {}, {});
  9458. ASSERT_TRUE(res);
  9459. ASSERT_EQ(StatusCode::OK_200, res->status);
  9460. }
  9461. FormDataProviderItems providers;
  9462. {
  9463. auto res =
  9464. cli.Post("/post-items", {}, items, providers); // empty providers
  9465. ASSERT_TRUE(res);
  9466. ASSERT_EQ(StatusCode::OK_200, res->status);
  9467. }
  9468. providers.push_back({"name3",
  9469. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9470. // test the offset is given correctly at each step
  9471. if (!offset)
  9472. sink.os.write(rand1.data(), 30);
  9473. else if (offset == 30)
  9474. sink.os.write(rand1.data() + 30, 300);
  9475. else if (offset == 330)
  9476. sink.os.write(rand1.data() + 330, 670);
  9477. else if (offset == rand1.size())
  9478. sink.done();
  9479. return true;
  9480. },
  9481. "filename3",
  9482. {}});
  9483. providers.push_back({"name4",
  9484. [&](size_t offset, httplib::DataSink &sink) -> bool {
  9485. // test the offset is given correctly at each step
  9486. if (!offset)
  9487. sink.os.write(rand2.data(), 2000);
  9488. else if (offset == 2000)
  9489. sink.os.write(rand2.data() + 2000, 1);
  9490. else if (offset == 2001)
  9491. sink.os.write(rand2.data() + 2001, 999);
  9492. else if (offset == rand2.size())
  9493. sink.done();
  9494. return true;
  9495. },
  9496. "filename4",
  9497. {}});
  9498. {
  9499. auto res = cli.Post("/post-providers", {}, {}, providers);
  9500. ASSERT_TRUE(res);
  9501. ASSERT_EQ(StatusCode::OK_200, res->status);
  9502. }
  9503. {
  9504. auto res = cli.Post("/post-both", {}, items, providers);
  9505. ASSERT_TRUE(res);
  9506. ASSERT_EQ(StatusCode::OK_200, res->status);
  9507. }
  9508. }
  9509. }
  9510. TEST(MultipartFormDataTest, BadHeader) {
  9511. Server svr;
  9512. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9513. res.set_content("ok", "text/plain");
  9514. });
  9515. thread t = thread([&] { svr.listen(HOST, PORT); });
  9516. auto se = detail::scope_exit([&] {
  9517. svr.stop();
  9518. t.join();
  9519. ASSERT_FALSE(svr.is_running());
  9520. });
  9521. svr.wait_until_ready();
  9522. const std::string body =
  9523. "This is the preamble. It is to be ignored, though it\r\n"
  9524. "is a handy place for composition agents to include an\r\n"
  9525. "explanatory note to non-MIME conformant readers.\r\n"
  9526. "\r\n"
  9527. "\r\n"
  9528. "--simple boundary\r\n"
  9529. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9530. ": BAD...\r\n"
  9531. "\r\n"
  9532. "value1\r\n"
  9533. "--simple boundary\r\n"
  9534. "Content-Disposition: form-data; name=\"field2\"; "
  9535. "filename=\"example.txt\"\r\n"
  9536. "\r\n"
  9537. "value2\r\n"
  9538. "--simple boundary--\r\n"
  9539. "This is the epilogue. It is also to be ignored.\r\n";
  9540. std::string content_type =
  9541. R"(multipart/form-data; boundary="simple boundary")";
  9542. Client cli(HOST, PORT);
  9543. auto res = cli.Post("/post", body, content_type.c_str());
  9544. ASSERT_TRUE(res);
  9545. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9546. }
  9547. TEST(MultipartFormDataTest, WithPreamble) {
  9548. Server svr;
  9549. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  9550. res.set_content("ok", "text/plain");
  9551. });
  9552. thread t = thread([&] { svr.listen(HOST, PORT); });
  9553. auto se = detail::scope_exit([&] {
  9554. svr.stop();
  9555. t.join();
  9556. ASSERT_FALSE(svr.is_running());
  9557. });
  9558. svr.wait_until_ready();
  9559. const std::string body =
  9560. "This is the preamble. It is to be ignored, though it\r\n"
  9561. "is a handy place for composition agents to include an\r\n"
  9562. "explanatory note to non-MIME conformant readers.\r\n"
  9563. "\r\n"
  9564. "\r\n"
  9565. "--simple boundary\r\n"
  9566. "Content-Disposition: form-data; name=\"field1\"\r\n"
  9567. "\r\n"
  9568. "value1\r\n"
  9569. "--simple boundary\r\n"
  9570. "Content-Disposition: form-data; name=\"field2\"; "
  9571. "filename=\"example.txt\"\r\n"
  9572. "\r\n"
  9573. "value2\r\n"
  9574. "--simple boundary--\r\n"
  9575. "This is the epilogue. It is also to be ignored.\r\n";
  9576. std::string content_type =
  9577. R"(multipart/form-data; boundary="simple boundary")";
  9578. Client cli(HOST, PORT);
  9579. auto res = cli.Post("/post", body, content_type.c_str());
  9580. ASSERT_TRUE(res);
  9581. EXPECT_EQ(StatusCode::OK_200, res->status);
  9582. }
  9583. TEST(MultipartFormDataTest, PostCustomBoundary) {
  9584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9585. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  9586. const ContentReader &content_reader) {
  9587. if (req.is_multipart_form_data()) {
  9588. std::vector<FormData> items;
  9589. content_reader(
  9590. [&](const FormData &file) {
  9591. items.push_back(file);
  9592. return true;
  9593. },
  9594. [&](const char *data, size_t data_length) {
  9595. items.back().content.append(data, data_length);
  9596. return true;
  9597. });
  9598. EXPECT_TRUE(std::string(items[0].name) == "document");
  9599. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9600. EXPECT_TRUE(items[0].filename == "2MB_data");
  9601. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9602. EXPECT_TRUE(items[1].name == "hello");
  9603. EXPECT_TRUE(items[1].content == "world");
  9604. EXPECT_TRUE(items[1].filename == "");
  9605. EXPECT_TRUE(items[1].content_type == "");
  9606. } else {
  9607. std::string body;
  9608. content_reader([&](const char *data, size_t data_length) {
  9609. body.append(data, data_length);
  9610. return true;
  9611. });
  9612. }
  9613. });
  9614. auto port = svr.bind_to_any_port("localhost");
  9615. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9616. auto se = detail::scope_exit([&] {
  9617. svr.stop();
  9618. t.join();
  9619. ASSERT_FALSE(svr.is_running());
  9620. });
  9621. svr.wait_until_ready();
  9622. {
  9623. std::string data(1024 * 1024 * 2, '.');
  9624. std::stringstream buffer;
  9625. buffer << data;
  9626. SSLClient cli("localhost", port);
  9627. cli.enable_server_certificate_verification(false);
  9628. UploadFormDataItems items{
  9629. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9630. {"hello", "world", "", ""},
  9631. };
  9632. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  9633. ASSERT_TRUE(res);
  9634. ASSERT_EQ(StatusCode::OK_200, res->status);
  9635. }
  9636. }
  9637. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  9638. std::string data(1024 * 1024 * 2, '&');
  9639. std::stringstream buffer;
  9640. buffer << data;
  9641. Client cli("https://localhost:8080");
  9642. UploadFormDataItems items{
  9643. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9644. {"hello", "world", "", ""},
  9645. };
  9646. for (const char &c : " \t\r\n") {
  9647. auto res =
  9648. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  9649. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9650. ASSERT_FALSE(res);
  9651. }
  9652. }
  9653. TEST(MultipartFormDataTest, PutFormData) {
  9654. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9655. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  9656. const ContentReader &content_reader) {
  9657. if (req.is_multipart_form_data()) {
  9658. std::vector<FormData> items;
  9659. content_reader(
  9660. [&](const FormData &file) {
  9661. items.push_back(file);
  9662. return true;
  9663. },
  9664. [&](const char *data, size_t data_length) {
  9665. items.back().content.append(data, data_length);
  9666. return true;
  9667. });
  9668. EXPECT_TRUE(std::string(items[0].name) == "document");
  9669. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9670. EXPECT_TRUE(items[0].filename == "2MB_data");
  9671. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9672. EXPECT_TRUE(items[1].name == "hello");
  9673. EXPECT_TRUE(items[1].content == "world");
  9674. EXPECT_TRUE(items[1].filename == "");
  9675. EXPECT_TRUE(items[1].content_type == "");
  9676. } else {
  9677. std::string body;
  9678. content_reader([&](const char *data, size_t data_length) {
  9679. body.append(data, data_length);
  9680. return true;
  9681. });
  9682. }
  9683. });
  9684. auto port = svr.bind_to_any_port("localhost");
  9685. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. ASSERT_FALSE(svr.is_running());
  9690. });
  9691. svr.wait_until_ready();
  9692. {
  9693. std::string data(1024 * 1024 * 2, '&');
  9694. std::stringstream buffer;
  9695. buffer << data;
  9696. SSLClient cli("localhost", port);
  9697. cli.enable_server_certificate_verification(false);
  9698. UploadFormDataItems items{
  9699. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9700. {"hello", "world", "", ""},
  9701. };
  9702. auto res = cli.Put("/put", items);
  9703. ASSERT_TRUE(res);
  9704. ASSERT_EQ(StatusCode::OK_200, res->status);
  9705. }
  9706. }
  9707. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  9708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9709. svr.Put("/put_customboundary",
  9710. [&](const Request &req, const Response & /*res*/,
  9711. const ContentReader &content_reader) {
  9712. if (req.is_multipart_form_data()) {
  9713. std::vector<FormData> items;
  9714. content_reader(
  9715. [&](const FormData &file) {
  9716. items.push_back(file);
  9717. return true;
  9718. },
  9719. [&](const char *data, size_t data_length) {
  9720. items.back().content.append(data, data_length);
  9721. return true;
  9722. });
  9723. EXPECT_TRUE(std::string(items[0].name) == "document");
  9724. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  9725. EXPECT_TRUE(items[0].filename == "2MB_data");
  9726. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  9727. EXPECT_TRUE(items[1].name == "hello");
  9728. EXPECT_TRUE(items[1].content == "world");
  9729. EXPECT_TRUE(items[1].filename == "");
  9730. EXPECT_TRUE(items[1].content_type == "");
  9731. } else {
  9732. std::string body;
  9733. content_reader([&](const char *data, size_t data_length) {
  9734. body.append(data, data_length);
  9735. return true;
  9736. });
  9737. }
  9738. });
  9739. auto port = svr.bind_to_any_port("localhost");
  9740. auto t = std::thread([&]() { svr.listen_after_bind(); });
  9741. auto se = detail::scope_exit([&] {
  9742. svr.stop();
  9743. t.join();
  9744. ASSERT_FALSE(svr.is_running());
  9745. });
  9746. svr.wait_until_ready();
  9747. {
  9748. std::string data(1024 * 1024 * 2, '&');
  9749. std::stringstream buffer;
  9750. buffer << data;
  9751. SSLClient cli("localhost", port);
  9752. cli.enable_server_certificate_verification(false);
  9753. UploadFormDataItems items{
  9754. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9755. {"hello", "world", "", ""},
  9756. };
  9757. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  9758. ASSERT_TRUE(res);
  9759. ASSERT_EQ(StatusCode::OK_200, res->status);
  9760. }
  9761. }
  9762. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  9763. std::string data(1024 * 1024 * 2, '&');
  9764. std::stringstream buffer;
  9765. buffer << data;
  9766. Client cli("https://localhost:8080");
  9767. cli.enable_server_certificate_verification(false);
  9768. UploadFormDataItems items{
  9769. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  9770. {"hello", "world", "", ""},
  9771. };
  9772. for (const char &c : " \t\r\n") {
  9773. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  9774. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  9775. ASSERT_FALSE(res);
  9776. }
  9777. }
  9778. TEST(MultipartFormDataTest, AlternateFilename) {
  9779. auto handled = false;
  9780. Server svr;
  9781. svr.Post("/test", [&](const Request &req, Response &res) {
  9782. ASSERT_EQ(2u, req.form.files.size());
  9783. ASSERT_EQ(1u, req.form.fields.size());
  9784. // Test files
  9785. const auto &file1 = req.form.get_file("file1");
  9786. ASSERT_EQ("file1", file1.name);
  9787. ASSERT_EQ("A.txt", file1.filename);
  9788. ASSERT_EQ("text/plain", file1.content_type);
  9789. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  9790. const auto &file2 = req.form.get_file("file2");
  9791. ASSERT_EQ("file2", file2.name);
  9792. ASSERT_EQ("a.html", file2.filename);
  9793. ASSERT_EQ("text/html", file2.content_type);
  9794. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  9795. file2.content);
  9796. // Test text field
  9797. const auto &text = req.form.get_field("text");
  9798. ASSERT_EQ("text default", text);
  9799. res.set_content("ok", "text/plain");
  9800. handled = true;
  9801. });
  9802. thread t = thread([&] { svr.listen(HOST, PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. t.join();
  9806. ASSERT_FALSE(svr.is_running());
  9807. ASSERT_TRUE(handled);
  9808. });
  9809. svr.wait_until_ready();
  9810. auto req = "POST /test HTTP/1.1\r\n"
  9811. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9812. "Content-Length: 399\r\n"
  9813. "\r\n"
  9814. "----------\r\n"
  9815. "Content-Disposition: form-data; name=\"text\"\r\n"
  9816. "\r\n"
  9817. "text default\r\n"
  9818. "----------\r\n"
  9819. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9820. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9821. "Content-Type: text/plain\r\n"
  9822. "\r\n"
  9823. "Content of a.txt.\r\n"
  9824. "\r\n"
  9825. "----------\r\n"
  9826. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9827. "\"a.html\"\r\n"
  9828. "Content-Type: text/html\r\n"
  9829. "\r\n"
  9830. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9831. "\r\n"
  9832. "------------\r\n";
  9833. ASSERT_TRUE(send_request(1, req));
  9834. }
  9835. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  9836. auto handled = false;
  9837. Server svr;
  9838. svr.Post("/test", [&](const Request &req, Response &res) {
  9839. // Case-insensitive "utf-8''" prefix with a long value
  9840. const auto &file = req.form.get_file("file1");
  9841. ASSERT_EQ("file1", file.name);
  9842. // 8000 chars exercises both the Content-Disposition parser and the
  9843. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  9844. // Prior to the fix, std::regex_match on this header would cause O(N)
  9845. // stack recursion in libstdc++, leading to SIGSEGV.
  9846. std::string expected_filename(8000, 'A');
  9847. ASSERT_EQ(expected_filename, file.filename);
  9848. res.set_content("ok", "text/plain");
  9849. handled = true;
  9850. });
  9851. thread t = thread([&] { svr.listen(HOST, PORT); });
  9852. auto se = detail::scope_exit([&] {
  9853. svr.stop();
  9854. t.join();
  9855. ASSERT_FALSE(svr.is_running());
  9856. ASSERT_TRUE(handled);
  9857. });
  9858. svr.wait_until_ready();
  9859. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  9860. // Regression test for GHSA-qq6v-r583-3h69
  9861. std::string long_filename(8000, 'A');
  9862. std::string body = "----------\r\n"
  9863. "Content-Disposition: form-data; name=\"file1\"; "
  9864. "filename*=\"Utf-8''" +
  9865. long_filename +
  9866. "\"\r\n"
  9867. "\r\n"
  9868. "hello\r\n"
  9869. "------------\r\n";
  9870. auto req = "POST /test HTTP/1.1\r\n"
  9871. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9872. "Content-Length: " +
  9873. std::to_string(body.size()) + "\r\n\r\n" + body;
  9874. ASSERT_TRUE(send_request(1, req));
  9875. }
  9876. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9877. auto handled = false;
  9878. Server svr;
  9879. svr.Post("/test", [&](const Request &req, Response &) {
  9880. ASSERT_EQ(2u, req.form.fields.size());
  9881. const auto &text1 = req.form.get_field("text1");
  9882. ASSERT_EQ("text1", text1);
  9883. const auto &text2 = req.form.get_field("text2");
  9884. ASSERT_EQ("text2", text2);
  9885. handled = true;
  9886. });
  9887. thread t = thread([&] { svr.listen(HOST, PORT); });
  9888. auto se = detail::scope_exit([&] {
  9889. svr.stop();
  9890. t.join();
  9891. ASSERT_FALSE(svr.is_running());
  9892. ASSERT_TRUE(handled);
  9893. });
  9894. svr.wait_until_ready();
  9895. auto req = "POST /test HTTP/1.1\r\n"
  9896. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9897. "Content-Length: 146\r\n"
  9898. "\r\n----------\r\n"
  9899. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9900. "\r\n"
  9901. "text1"
  9902. "\r\n----------\r\n"
  9903. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9904. "\r\n"
  9905. "text2"
  9906. "\r\n------------";
  9907. std::string response;
  9908. ASSERT_TRUE(send_request(1, req, &response));
  9909. ASSERT_EQ("200", response.substr(9, 3));
  9910. }
  9911. TEST(MultipartFormDataTest, ContentLength) {
  9912. auto handled = false;
  9913. Server svr;
  9914. svr.Post("/test", [&](const Request &req, Response &) {
  9915. ASSERT_EQ(2u, req.form.fields.size());
  9916. const auto &text1 = req.form.get_field("text1");
  9917. ASSERT_EQ("text1", text1);
  9918. const auto &text2 = req.form.get_field("text2");
  9919. ASSERT_EQ("text2", text2);
  9920. handled = true;
  9921. });
  9922. thread t = thread([&] { svr.listen(HOST, PORT); });
  9923. auto se = detail::scope_exit([&] {
  9924. svr.stop();
  9925. t.join();
  9926. ASSERT_FALSE(svr.is_running());
  9927. ASSERT_TRUE(handled);
  9928. });
  9929. svr.wait_until_ready();
  9930. auto req = "POST /test HTTP/1.1\r\n"
  9931. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9932. "Content-Length: 167\r\n"
  9933. "\r\n----------\r\n"
  9934. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9935. "Content-Length: 5\r\n"
  9936. "\r\n"
  9937. "text1"
  9938. "\r\n----------\r\n"
  9939. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9940. "\r\n"
  9941. "text2"
  9942. "\r\n------------\r\n";
  9943. std::string response;
  9944. ASSERT_TRUE(send_request(1, req, &response));
  9945. ASSERT_EQ("200", response.substr(9, 3));
  9946. }
  9947. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9948. auto handled = false;
  9949. Server svr;
  9950. svr.Post("/test", [&](const Request &req, Response &) {
  9951. ASSERT_EQ(2u, req.form.fields.size());
  9952. const auto &text1 = req.form.get_field("text1");
  9953. ASSERT_EQ("text1", text1);
  9954. // TODO: Add header access for text fields if needed
  9955. const auto &text2 = req.form.get_field("text2");
  9956. ASSERT_EQ("text2", text2);
  9957. // TODO: Header access for text fields needs to be implemented
  9958. // auto &headers = it->second.headers;
  9959. // ASSERT_EQ(3U, headers.size());
  9960. // auto custom_header = headers.find("x-whatever");
  9961. // ASSERT_TRUE(custom_header != headers.end());
  9962. // ASSERT_NE("customvalue", custom_header->second);
  9963. // ASSERT_EQ("CustomValue", custom_header->second);
  9964. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9965. handled = true;
  9966. });
  9967. thread t = thread([&] { svr.listen(HOST, PORT); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. t.join();
  9971. ASSERT_FALSE(svr.is_running());
  9972. ASSERT_TRUE(handled);
  9973. });
  9974. svr.wait_until_ready();
  9975. auto req = "POST /test HTTP/1.1\r\n"
  9976. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9977. "Content-Length: 232\r\n"
  9978. "\r\n----------\r\n"
  9979. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9980. "Content-Length: 5\r\n"
  9981. "X-Test: 1\r\n"
  9982. "\r\n"
  9983. "text1"
  9984. "\r\n----------\r\n"
  9985. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9986. "Content-Type: text/plain\r\n"
  9987. "X-Whatever: CustomValue\r\n"
  9988. "\r\n"
  9989. "text2"
  9990. "\r\n------------\r\n"
  9991. "That should be disregarded. Not even read";
  9992. std::string response;
  9993. ASSERT_TRUE(send_request(1, req, &response));
  9994. ASSERT_EQ("200", response.substr(9, 3));
  9995. }
  9996. TEST(MultipartFormDataTest, LargeHeader) {
  9997. auto handled = false;
  9998. Server svr;
  9999. svr.Post("/test", [&](const Request &req, Response &) {
  10000. ASSERT_EQ(1u, req.form.fields.size());
  10001. const auto &text = req.form.get_field("name1");
  10002. ASSERT_EQ("text1", text);
  10003. handled = true;
  10004. });
  10005. thread t = thread([&] { svr.listen(HOST, PORT); });
  10006. auto se = detail::scope_exit([&] {
  10007. svr.stop();
  10008. t.join();
  10009. ASSERT_FALSE(svr.is_running());
  10010. ASSERT_TRUE(handled);
  10011. });
  10012. svr.wait_until_ready();
  10013. auto boundary = std::string("cpp-httplib-multipart-data");
  10014. std::string content = "--" + boundary +
  10015. "\r\n"
  10016. "Content-Disposition: form-data; name=\"name1\"\r\n"
  10017. "\r\n"
  10018. "text1\r\n"
  10019. "--" +
  10020. boundary + "--\r\n";
  10021. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  10022. "Content-Type: multipart/form-data;boundary=" +
  10023. boundary +
  10024. "\r\n"
  10025. "Content-Length: " +
  10026. std::to_string(content.size()) +
  10027. "\r\n"
  10028. "Dummy-Header: ";
  10029. std::string header_suffix = "\r\n"
  10030. "\r\n";
  10031. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  10032. size_t header_dummy_size =
  10033. read_buff_size -
  10034. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  10035. auto header_dummy = std::string(header_dummy_size, '@');
  10036. auto req = header_prefix + header_dummy + header_suffix + content;
  10037. std::string response;
  10038. ASSERT_TRUE(send_request(1, req, &response));
  10039. ASSERT_EQ("200", response.substr(9, 3));
  10040. }
  10041. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  10042. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  10043. // (not chunked Transfer-Encoding) after the streaming refactor.
  10044. auto handled = false;
  10045. Server svr;
  10046. svr.Post("/upload", [&](const Request &req, Response &res) {
  10047. auto cl_it = req.headers.find("Content-Length");
  10048. EXPECT_TRUE(cl_it != req.headers.end());
  10049. auto te_it = req.headers.find("Transfer-Encoding");
  10050. EXPECT_TRUE(te_it == req.headers.end());
  10051. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  10052. res.set_content("ok", "text/plain");
  10053. handled = true;
  10054. });
  10055. auto port = svr.bind_to_any_port(HOST);
  10056. auto t = thread([&] { svr.listen_after_bind(); });
  10057. auto se = detail::scope_exit([&] {
  10058. svr.stop();
  10059. t.join();
  10060. ASSERT_FALSE(svr.is_running());
  10061. ASSERT_TRUE(handled);
  10062. });
  10063. svr.wait_until_ready();
  10064. UploadFormDataItems items = {
  10065. {"field1", "hello", "", "text/plain"},
  10066. {"file1", "world", "test.txt", "application/octet-stream"},
  10067. };
  10068. Client cli(HOST, port);
  10069. auto res = cli.Post("/upload", {}, items);
  10070. ASSERT_TRUE(res);
  10071. EXPECT_EQ(StatusCode::OK_200, res->status);
  10072. }
  10073. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  10074. // Verify that make_multipart_content_provider coalesces many small segments
  10075. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  10076. constexpr size_t kItemCount = 1000;
  10077. UploadFormDataItems items;
  10078. items.reserve(kItemCount);
  10079. for (size_t i = 0; i < kItemCount; i++) {
  10080. items.push_back(
  10081. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10082. }
  10083. const std::string boundary = "----test-boundary";
  10084. auto content_length = detail::get_multipart_content_length(items, boundary);
  10085. auto provider = detail::make_multipart_content_provider(items, boundary);
  10086. // Drive the provider the same way write_content_with_progress does
  10087. size_t write_count = 0;
  10088. size_t total_bytes = 0;
  10089. DataSink sink;
  10090. size_t offset = 0;
  10091. sink.write = [&](const char *d, size_t l) -> bool {
  10092. (void)d;
  10093. write_count++;
  10094. total_bytes += l;
  10095. offset += l;
  10096. return true;
  10097. };
  10098. sink.is_writable = []() -> bool { return true; };
  10099. while (offset < content_length) {
  10100. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  10101. }
  10102. EXPECT_EQ(content_length, total_bytes);
  10103. // The total number of segments is 3 * kItemCount + 1 = 3001.
  10104. // With buffering into 64KB blocks, write_count should be much smaller.
  10105. auto segment_count = 3 * kItemCount + 1;
  10106. EXPECT_LT(write_count, segment_count / 10);
  10107. }
  10108. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  10109. // Integration test: send many UploadFormDataItems and verify the server
  10110. // receives all of them correctly (#2410).
  10111. constexpr size_t kItemCount = 500;
  10112. auto handled = false;
  10113. Server svr;
  10114. svr.Post("/upload", [&](const Request &req, Response &res) {
  10115. EXPECT_EQ(kItemCount, req.form.fields.size());
  10116. for (size_t i = 0; i < kItemCount; i++) {
  10117. auto key = "field" + std::to_string(i);
  10118. auto val = "value" + std::to_string(i);
  10119. auto it = req.form.fields.find(key);
  10120. if (it != req.form.fields.end()) {
  10121. EXPECT_EQ(val, it->second.content);
  10122. } else {
  10123. ADD_FAILURE() << "Missing field: " << key;
  10124. }
  10125. }
  10126. res.set_content("ok", "text/plain");
  10127. handled = true;
  10128. });
  10129. auto port = svr.bind_to_any_port(HOST);
  10130. auto t = thread([&] { svr.listen_after_bind(); });
  10131. auto se = detail::scope_exit([&] {
  10132. svr.stop();
  10133. t.join();
  10134. ASSERT_FALSE(svr.is_running());
  10135. ASSERT_TRUE(handled);
  10136. });
  10137. svr.wait_until_ready();
  10138. UploadFormDataItems items;
  10139. items.reserve(kItemCount);
  10140. for (size_t i = 0; i < kItemCount; i++) {
  10141. items.push_back(
  10142. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  10143. }
  10144. Client cli(HOST, port);
  10145. auto res = cli.Post("/upload", items);
  10146. ASSERT_TRUE(res);
  10147. EXPECT_EQ(StatusCode::OK_200, res->status);
  10148. }
  10149. TEST(MultipartFormDataTest, MakeFileProvider) {
  10150. // Verify make_file_provider sends a file's contents correctly.
  10151. const std::string file_content(4096, 'Z');
  10152. const std::string tmp_path = "/tmp/httplib_test_make_file_provider.bin";
  10153. {
  10154. std::ofstream ofs(tmp_path, std::ios::binary);
  10155. ofs.write(file_content.data(),
  10156. static_cast<std::streamsize>(file_content.size()));
  10157. }
  10158. auto handled = false;
  10159. Server svr;
  10160. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  10161. const ContentReader &content_reader) {
  10162. ASSERT_TRUE(req.is_multipart_form_data());
  10163. std::vector<FormData> items;
  10164. content_reader(
  10165. [&](const FormData &file) {
  10166. items.push_back(file);
  10167. return true;
  10168. },
  10169. [&](const char *data, size_t data_length) {
  10170. items.back().content.append(data, data_length);
  10171. return true;
  10172. });
  10173. ASSERT_EQ(1u, items.size());
  10174. EXPECT_EQ("myfile", items[0].name);
  10175. EXPECT_EQ("data.bin", items[0].filename);
  10176. EXPECT_EQ("application/octet-stream", items[0].content_type);
  10177. EXPECT_EQ(file_content, items[0].content);
  10178. handled = true;
  10179. });
  10180. auto port = svr.bind_to_any_port(HOST);
  10181. auto t = thread([&] { svr.listen_after_bind(); });
  10182. auto se = detail::scope_exit([&] {
  10183. svr.stop();
  10184. t.join();
  10185. ASSERT_FALSE(svr.is_running());
  10186. ASSERT_TRUE(handled);
  10187. std::remove(tmp_path.c_str());
  10188. });
  10189. svr.wait_until_ready();
  10190. FormDataProviderItems providers;
  10191. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  10192. "application/octet-stream"));
  10193. Client cli(HOST, port);
  10194. auto res = cli.Post("/upload", {}, {}, providers);
  10195. ASSERT_TRUE(res);
  10196. EXPECT_EQ(StatusCode::OK_200, res->status);
  10197. }
  10198. TEST(MakeFileBodyTest, Basic) {
  10199. const std::string file_content(4096, 'Z');
  10200. const std::string tmp_path = "/tmp/httplib_test_make_file_body.bin";
  10201. {
  10202. std::ofstream ofs(tmp_path, std::ios::binary);
  10203. ofs.write(file_content.data(),
  10204. static_cast<std::streamsize>(file_content.size()));
  10205. }
  10206. auto handled = false;
  10207. Server svr;
  10208. svr.Post("/upload", [&](const Request &req, Response &res) {
  10209. EXPECT_EQ(file_content, req.body);
  10210. handled = true;
  10211. res.status = StatusCode::OK_200;
  10212. });
  10213. auto port = svr.bind_to_any_port(HOST);
  10214. auto t = thread([&] { svr.listen_after_bind(); });
  10215. auto se = detail::scope_exit([&] {
  10216. svr.stop();
  10217. t.join();
  10218. ASSERT_FALSE(svr.is_running());
  10219. ASSERT_TRUE(handled);
  10220. std::remove(tmp_path.c_str());
  10221. });
  10222. svr.wait_until_ready();
  10223. auto fb = make_file_body(tmp_path);
  10224. ASSERT_GT(fb.first, 0u);
  10225. Client cli(HOST, port);
  10226. auto res =
  10227. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  10228. ASSERT_TRUE(res);
  10229. EXPECT_EQ(StatusCode::OK_200, res->status);
  10230. }
  10231. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  10232. static constexpr unsigned int number_of_tasks{1000000};
  10233. std::atomic_uint count{0};
  10234. std::unique_ptr<TaskQueue> task_queue{
  10235. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  10236. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10237. auto queued = task_queue->enqueue(
  10238. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  10239. EXPECT_TRUE(queued);
  10240. }
  10241. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10242. task_queue->shutdown();
  10243. #else
  10244. EXPECT_NO_THROW(task_queue->shutdown());
  10245. #endif
  10246. EXPECT_EQ(number_of_tasks, count.load());
  10247. }
  10248. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  10249. static constexpr unsigned int number_of_tasks{1000000};
  10250. static constexpr unsigned int qlimit{2};
  10251. unsigned int queued_count{0};
  10252. std::atomic_uint count{0};
  10253. std::unique_ptr<TaskQueue> task_queue{
  10254. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  10255. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  10256. if (task_queue->enqueue(
  10257. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  10258. queued_count++;
  10259. }
  10260. }
  10261. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10262. task_queue->shutdown();
  10263. #else
  10264. EXPECT_NO_THROW(task_queue->shutdown());
  10265. #endif
  10266. EXPECT_EQ(queued_count, count.load());
  10267. EXPECT_TRUE(queued_count <= number_of_tasks);
  10268. EXPECT_TRUE(queued_count >= qlimit);
  10269. }
  10270. TEST(TaskQueueTest, MaxQueuedRequests) {
  10271. static constexpr unsigned int qlimit{3};
  10272. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  10273. std::condition_variable sem_cv;
  10274. std::mutex sem_mtx;
  10275. int credits = 0;
  10276. bool queued;
  10277. /* Fill up the queue with tasks that will block until we give them credits to
  10278. * complete. */
  10279. for (unsigned int n = 0; n <= qlimit;) {
  10280. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  10281. std::unique_lock<std::mutex> lock(sem_mtx);
  10282. while (credits <= 0) {
  10283. sem_cv.wait(lock);
  10284. }
  10285. /* Consume the credit and signal the test code if they are all gone. */
  10286. if (--credits == 0) { sem_cv.notify_one(); }
  10287. });
  10288. if (n < qlimit) {
  10289. /* The first qlimit enqueues must succeed. */
  10290. EXPECT_TRUE(queued);
  10291. } else {
  10292. /* The last one will succeed only when the worker thread
  10293. * starts and dequeues the first blocking task. Although
  10294. * not necessary for the correctness of this test, we sleep for
  10295. * a short while to avoid busy waiting. */
  10296. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10297. }
  10298. if (queued) { n++; }
  10299. }
  10300. /* Further enqueues must fail since the queue is full. */
  10301. for (auto i = 0; i < 4; i++) {
  10302. queued = task_queue->enqueue([] {});
  10303. EXPECT_FALSE(queued);
  10304. }
  10305. /* Give the credits to allow the previous tasks to complete. */
  10306. {
  10307. std::unique_lock<std::mutex> lock(sem_mtx);
  10308. credits += qlimit + 1;
  10309. }
  10310. sem_cv.notify_all();
  10311. /* Wait for all the credits to be consumed. */
  10312. {
  10313. std::unique_lock<std::mutex> lock(sem_mtx);
  10314. while (credits > 0) {
  10315. sem_cv.wait(lock);
  10316. }
  10317. }
  10318. /* Check that we are able again to enqueue at least qlimit tasks. */
  10319. for (unsigned int i = 0; i < qlimit; i++) {
  10320. queued = task_queue->enqueue([] {});
  10321. EXPECT_TRUE(queued);
  10322. }
  10323. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10324. task_queue->shutdown();
  10325. #else
  10326. EXPECT_NO_THROW(task_queue->shutdown());
  10327. #endif
  10328. }
  10329. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  10330. Server svr;
  10331. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10332. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  10333. });
  10334. svr.Get("/hello", [](const Request &req, Response &res) {
  10335. res.set_content(req.get_param_value("key"), "text/plain");
  10336. });
  10337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10338. auto se = detail::scope_exit([&] {
  10339. svr.stop();
  10340. thread.join();
  10341. ASSERT_FALSE(svr.is_running());
  10342. });
  10343. svr.wait_until_ready();
  10344. {
  10345. Client cli(HOST, PORT);
  10346. cli.set_follow_location(true);
  10347. auto res = cli.Get("/");
  10348. ASSERT_TRUE(res);
  10349. EXPECT_EQ(StatusCode::OK_200, res->status);
  10350. EXPECT_EQ("val&key2=val2", res->body);
  10351. }
  10352. }
  10353. #endif
  10354. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  10355. Server svr;
  10356. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10357. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  10358. });
  10359. svr.Get("/hello", [](const Request &req, Response &res) {
  10360. res.set_content(req.get_param_value("key"), "text/plain");
  10361. });
  10362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10363. auto se = detail::scope_exit([&] {
  10364. svr.stop();
  10365. thread.join();
  10366. ASSERT_FALSE(svr.is_running());
  10367. });
  10368. svr.wait_until_ready();
  10369. {
  10370. Client cli(HOST, PORT);
  10371. cli.set_follow_location(true);
  10372. auto res = cli.Get("/");
  10373. ASSERT_TRUE(res);
  10374. EXPECT_EQ(StatusCode::OK_200, res->status);
  10375. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  10376. }
  10377. }
  10378. TEST(RedirectTest, RedirectWithPlusInPath) {
  10379. Server svr;
  10380. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10381. res.set_redirect("/a+b");
  10382. });
  10383. // Route pattern uses regex; escape + as \\+
  10384. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  10385. res.set_content(req.path, "text/plain");
  10386. });
  10387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10388. auto se = detail::scope_exit([&] {
  10389. svr.stop();
  10390. thread.join();
  10391. ASSERT_FALSE(svr.is_running());
  10392. });
  10393. svr.wait_until_ready();
  10394. {
  10395. Client cli(HOST, PORT);
  10396. cli.set_follow_location(true);
  10397. auto res = cli.Get("/");
  10398. ASSERT_TRUE(res);
  10399. EXPECT_EQ(StatusCode::OK_200, res->status);
  10400. EXPECT_EQ("/a+b", res->body);
  10401. }
  10402. }
  10403. #ifdef CPPHTTPLIB_SSL_ENABLED
  10404. TEST(RedirectTest, Issue2185_Online) {
  10405. SSLClient client("github.com");
  10406. client.set_follow_location(true);
  10407. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  10408. "Coollab-Windows.zip");
  10409. ASSERT_TRUE(res);
  10410. EXPECT_EQ(StatusCode::OK_200, res->status);
  10411. EXPECT_EQ(9920427U, res->body.size());
  10412. }
  10413. #endif
  10414. TEST(VulnerabilityTest, CRLFInjection) {
  10415. Server svr;
  10416. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  10417. res.set_content("Hello 1", "text/plain");
  10418. });
  10419. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  10420. res.set_content("Hello 2", "text/plain");
  10421. });
  10422. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  10423. res.set_content("Hello 3", "text/plain");
  10424. });
  10425. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  10426. res.set_content("Hello 4", "text/plain");
  10427. });
  10428. svr.set_logger([](const Request &req, const Response & /*res*/) {
  10429. for (const auto &x : req.headers) {
  10430. auto key = x.first;
  10431. EXPECT_STRNE("evil", key.c_str());
  10432. }
  10433. });
  10434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10435. auto se = detail::scope_exit([&] {
  10436. svr.stop();
  10437. thread.join();
  10438. ASSERT_FALSE(svr.is_running());
  10439. });
  10440. svr.wait_until_ready();
  10441. {
  10442. Client cli(HOST, PORT);
  10443. cli.Post("/test1", "A=B",
  10444. "application/x-www-form-urlencoded\r\nevil: hello1");
  10445. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  10446. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  10447. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  10448. }
  10449. }
  10450. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  10451. auto server_thread = std::thread([] {
  10452. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10453. default_socket_options(srv);
  10454. sockaddr_in addr{};
  10455. addr.sin_family = AF_INET;
  10456. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  10457. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10458. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10459. ::listen(srv, 1);
  10460. sockaddr_in cli_addr{};
  10461. socklen_t cli_len = sizeof(cli_addr);
  10462. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10463. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  10464. std::string buf_all;
  10465. char buf[2048];
  10466. ssize_t n;
  10467. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  10468. buf_all.append(buf, static_cast<size_t>(n));
  10469. size_t pos;
  10470. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  10471. auto request_block = buf_all.substr(0, pos + 4); // include separator
  10472. auto e = request_block.find("\r\n");
  10473. if (e != std::string::npos) {
  10474. auto request_line = request_block.substr(0, e);
  10475. std::string msg =
  10476. "CRLF injection detected in request line: '" + request_line + "'";
  10477. EXPECT_FALSE(true) << msg;
  10478. }
  10479. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  10480. ::send(cli,
  10481. #ifdef _WIN32
  10482. static_cast<const char *>(resp.c_str()),
  10483. static_cast<int>(resp.size()),
  10484. #else
  10485. resp.c_str(), resp.size(),
  10486. #endif
  10487. 0);
  10488. buf_all.erase(0, pos + 4);
  10489. }
  10490. }
  10491. detail::close_socket(cli);
  10492. detail::close_socket(srv);
  10493. });
  10494. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  10495. auto cli = Client("127.0.0.1", PORT + 1);
  10496. auto headers = Headers{
  10497. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  10498. {"Connection", "keep-alive"}};
  10499. auto res = cli.Get("/hi", headers);
  10500. EXPECT_FALSE(res);
  10501. EXPECT_EQ(Error::InvalidHeaders, res.error());
  10502. server_thread.join();
  10503. }
  10504. TEST(PathParamsTest, StaticMatch) {
  10505. const auto pattern = "/users/all";
  10506. detail::PathParamsMatcher matcher(pattern);
  10507. Request request;
  10508. request.path = "/users/all";
  10509. ASSERT_TRUE(matcher.match(request));
  10510. std::unordered_map<std::string, std::string> expected_params = {};
  10511. EXPECT_EQ(request.path_params, expected_params);
  10512. }
  10513. TEST(PathParamsTest, StaticMismatch) {
  10514. const auto pattern = "/users/all";
  10515. detail::PathParamsMatcher matcher(pattern);
  10516. Request request;
  10517. request.path = "/users/1";
  10518. ASSERT_FALSE(matcher.match(request));
  10519. }
  10520. TEST(PathParamsTest, SingleParamInTheMiddle) {
  10521. const auto pattern = "/users/:id/subscriptions";
  10522. detail::PathParamsMatcher matcher(pattern);
  10523. Request request;
  10524. request.path = "/users/42/subscriptions";
  10525. ASSERT_TRUE(matcher.match(request));
  10526. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10527. EXPECT_EQ(request.path_params, expected_params);
  10528. }
  10529. TEST(PathParamsTest, SingleParamInTheEnd) {
  10530. const auto pattern = "/users/:id";
  10531. detail::PathParamsMatcher matcher(pattern);
  10532. Request request;
  10533. request.path = "/users/24";
  10534. ASSERT_TRUE(matcher.match(request));
  10535. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  10536. EXPECT_EQ(request.path_params, expected_params);
  10537. }
  10538. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  10539. const auto pattern = "/users/:id/";
  10540. detail::PathParamsMatcher matcher(pattern);
  10541. Request request;
  10542. request.path = "/users/42/";
  10543. ASSERT_TRUE(matcher.match(request));
  10544. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  10545. EXPECT_EQ(request.path_params, expected_params);
  10546. }
  10547. TEST(PathParamsTest, EmptyParam) {
  10548. const auto pattern = "/users/:id/";
  10549. detail::PathParamsMatcher matcher(pattern);
  10550. Request request;
  10551. request.path = "/users//";
  10552. ASSERT_TRUE(matcher.match(request));
  10553. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  10554. EXPECT_EQ(request.path_params, expected_params);
  10555. }
  10556. TEST(PathParamsTest, FragmentMismatch) {
  10557. const auto pattern = "/users/:id/";
  10558. detail::PathParamsMatcher matcher(pattern);
  10559. Request request;
  10560. request.path = "/admins/24/";
  10561. ASSERT_FALSE(matcher.match(request));
  10562. }
  10563. TEST(PathParamsTest, ExtraFragments) {
  10564. const auto pattern = "/users/:id";
  10565. detail::PathParamsMatcher matcher(pattern);
  10566. Request request;
  10567. request.path = "/users/42/subscriptions";
  10568. ASSERT_FALSE(matcher.match(request));
  10569. }
  10570. TEST(PathParamsTest, MissingTrailingParam) {
  10571. const auto pattern = "/users/:id";
  10572. detail::PathParamsMatcher matcher(pattern);
  10573. Request request;
  10574. request.path = "/users";
  10575. ASSERT_FALSE(matcher.match(request));
  10576. }
  10577. TEST(PathParamsTest, MissingParamInTheMiddle) {
  10578. const auto pattern = "/users/:id/subscriptions";
  10579. detail::PathParamsMatcher matcher(pattern);
  10580. Request request;
  10581. request.path = "/users/subscriptions";
  10582. ASSERT_FALSE(matcher.match(request));
  10583. }
  10584. TEST(PathParamsTest, MultipleParams) {
  10585. const auto pattern = "/users/:userid/subscriptions/:subid";
  10586. detail::PathParamsMatcher matcher(pattern);
  10587. Request request;
  10588. request.path = "/users/42/subscriptions/2";
  10589. ASSERT_TRUE(matcher.match(request));
  10590. std::unordered_map<std::string, std::string> expected_params = {
  10591. {"userid", "42"}, {"subid", "2"}};
  10592. EXPECT_EQ(request.path_params, expected_params);
  10593. }
  10594. TEST(PathParamsTest, SequenceOfParams) {
  10595. const auto pattern = "/values/:x/:y/:z";
  10596. detail::PathParamsMatcher matcher(pattern);
  10597. Request request;
  10598. request.path = "/values/1/2/3";
  10599. ASSERT_TRUE(matcher.match(request));
  10600. std::unordered_map<std::string, std::string> expected_params = {
  10601. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  10602. EXPECT_EQ(request.path_params, expected_params);
  10603. }
  10604. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  10605. const auto pattern = "/prefix:suffix";
  10606. detail::PathParamsMatcher matcher(pattern);
  10607. Request request;
  10608. request.path = "/prefix:suffix";
  10609. ASSERT_TRUE(matcher.match(request));
  10610. const std::unordered_map<std::string, std::string> expected_params = {};
  10611. EXPECT_EQ(request.path_params, expected_params);
  10612. }
  10613. TEST(ParseUrlTest, VariousPatterns) {
  10614. {
  10615. detail::UrlComponents uc;
  10616. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  10617. EXPECT_EQ("http", uc.scheme);
  10618. EXPECT_EQ("example.com", uc.host);
  10619. EXPECT_EQ("8080", uc.port);
  10620. EXPECT_EQ("/path", uc.path);
  10621. EXPECT_EQ("?q=1", uc.query);
  10622. }
  10623. {
  10624. detail::UrlComponents uc;
  10625. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  10626. EXPECT_EQ("https", uc.scheme);
  10627. EXPECT_EQ("example.com", uc.host);
  10628. EXPECT_TRUE(uc.port.empty());
  10629. EXPECT_EQ("/path", uc.path);
  10630. }
  10631. {
  10632. detail::UrlComponents uc;
  10633. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  10634. EXPECT_EQ("::1", uc.host);
  10635. EXPECT_EQ("8080", uc.port);
  10636. EXPECT_EQ("/path", uc.path);
  10637. }
  10638. {
  10639. detail::UrlComponents uc;
  10640. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  10641. }
  10642. {
  10643. detail::UrlComponents uc;
  10644. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  10645. EXPECT_TRUE(uc.scheme.empty());
  10646. EXPECT_EQ("example.com", uc.host);
  10647. EXPECT_EQ("/path", uc.path);
  10648. EXPECT_EQ("?q=1", uc.query);
  10649. }
  10650. {
  10651. detail::UrlComponents uc;
  10652. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  10653. EXPECT_TRUE(uc.host.empty());
  10654. EXPECT_EQ("/path", uc.path);
  10655. EXPECT_EQ("?q=1", uc.query);
  10656. }
  10657. {
  10658. detail::UrlComponents uc;
  10659. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  10660. EXPECT_EQ("example.com", uc.host);
  10661. EXPECT_EQ("8080", uc.port);
  10662. }
  10663. {
  10664. // Unix socket path — must not be parsed as host
  10665. detail::UrlComponents uc;
  10666. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  10667. EXPECT_TRUE(uc.host.empty());
  10668. }
  10669. {
  10670. detail::UrlComponents uc;
  10671. ASSERT_TRUE(detail::parse_url("", uc));
  10672. EXPECT_TRUE(uc.host.empty());
  10673. EXPECT_TRUE(uc.path.empty());
  10674. }
  10675. {
  10676. detail::UrlComponents uc;
  10677. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  10678. }
  10679. {
  10680. detail::UrlComponents uc;
  10681. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  10682. }
  10683. {
  10684. // Accepted by parse_url; callers restrict to http/https
  10685. detail::UrlComponents uc;
  10686. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  10687. EXPECT_EQ("ftp", uc.scheme);
  10688. }
  10689. {
  10690. detail::UrlComponents uc;
  10691. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  10692. }
  10693. {
  10694. detail::UrlComponents uc;
  10695. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  10696. }
  10697. }
  10698. TEST(ParseUrlTest, FragmentHandling) {
  10699. {
  10700. detail::UrlComponents uc;
  10701. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  10702. EXPECT_EQ("/path", uc.path);
  10703. EXPECT_TRUE(uc.query.empty());
  10704. }
  10705. {
  10706. detail::UrlComponents uc;
  10707. ASSERT_TRUE(detail::parse_url("#frag", uc));
  10708. EXPECT_TRUE(uc.path.empty());
  10709. EXPECT_TRUE(uc.query.empty());
  10710. }
  10711. }
  10712. TEST(ParseUrlTest, UserinfoHandling) {
  10713. // Userinfo with @ but no colon — host includes @
  10714. detail::UrlComponents uc;
  10715. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  10716. EXPECT_EQ("user@host.com", uc.host);
  10717. EXPECT_EQ("/path", uc.path);
  10718. }
  10719. TEST(ParseUrlTest, IPv6EdgeCases) {
  10720. {
  10721. detail::UrlComponents uc;
  10722. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  10723. EXPECT_TRUE(uc.scheme.empty());
  10724. EXPECT_EQ("::1", uc.host);
  10725. EXPECT_EQ("8080", uc.port);
  10726. }
  10727. {
  10728. // Zone ID '%25' is not in [a-fA-F0-9:]
  10729. detail::UrlComponents uc;
  10730. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  10731. }
  10732. }
  10733. TEST(ParseUrlTest, SchemeEdgeCases) {
  10734. {
  10735. detail::UrlComponents uc;
  10736. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  10737. }
  10738. {
  10739. detail::UrlComponents uc;
  10740. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  10741. }
  10742. {
  10743. detail::UrlComponents uc;
  10744. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  10745. }
  10746. }
  10747. TEST(ParseUrlTest, PortEdgeCases) {
  10748. {
  10749. detail::UrlComponents uc;
  10750. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  10751. EXPECT_TRUE(uc.port.empty());
  10752. EXPECT_EQ("/path", uc.path);
  10753. }
  10754. {
  10755. // parse_url accepts any port string; validation is done by parse_port
  10756. detail::UrlComponents uc;
  10757. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  10758. EXPECT_EQ("abc", uc.port);
  10759. }
  10760. }
  10761. TEST(ParseUrlTest, WebSocketPatterns) {
  10762. {
  10763. detail::UrlComponents uc;
  10764. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  10765. EXPECT_EQ("ws", uc.scheme);
  10766. EXPECT_EQ("echo.example.com", uc.host);
  10767. EXPECT_EQ("8080", uc.port);
  10768. EXPECT_EQ("/ws", uc.path);
  10769. }
  10770. {
  10771. detail::UrlComponents uc;
  10772. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  10773. EXPECT_EQ("wss", uc.scheme);
  10774. EXPECT_EQ("echo.example.com", uc.host);
  10775. EXPECT_TRUE(uc.port.empty());
  10776. EXPECT_EQ("/ws", uc.path);
  10777. }
  10778. }
  10779. TEST(ParseUrlTest, QueryOnly) {
  10780. detail::UrlComponents uc;
  10781. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  10782. EXPECT_TRUE(uc.host.empty());
  10783. EXPECT_TRUE(uc.path.empty());
  10784. EXPECT_EQ("?q=1&r=2", uc.query);
  10785. }
  10786. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  10787. detail::UrlComponents uc;
  10788. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  10789. EXPECT_TRUE(uc.scheme.empty());
  10790. EXPECT_EQ("example.com", uc.host);
  10791. EXPECT_EQ("443", uc.port);
  10792. EXPECT_EQ("/path", uc.path);
  10793. }
  10794. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  10795. // If ipv6 regex working, regex match codepath is taken.
  10796. // else port will default to 80 in Client impl
  10797. int clientImplMagicPort = 80;
  10798. int port = 4321;
  10799. // above ports must be different to avoid false negative
  10800. EXPECT_NE(clientImplMagicPort, port);
  10801. std::string ipV6TestURL = "http://[ff06::c3]";
  10802. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  10803. CLIENT_PRIVATE_KEY_FILE);
  10804. EXPECT_EQ(cli.port(), port);
  10805. }
  10806. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  10807. auto file_path = "./www/dir/index.html";
  10808. auto dir_path = "./www/dir";
  10809. detail::FileStat stat_file(file_path);
  10810. EXPECT_TRUE(stat_file.is_file());
  10811. EXPECT_FALSE(stat_file.is_dir());
  10812. detail::FileStat stat_dir(dir_path);
  10813. EXPECT_FALSE(stat_dir.is_file());
  10814. EXPECT_TRUE(stat_dir.is_dir());
  10815. }
  10816. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  10817. // IPv4 with default HTTP port (80)
  10818. EXPECT_EQ("example.com",
  10819. detail::make_host_and_port_string("example.com", 80, false));
  10820. // IPv4 with default HTTPS port (443)
  10821. EXPECT_EQ("example.com",
  10822. detail::make_host_and_port_string("example.com", 443, true));
  10823. // IPv4 with non-default HTTP port
  10824. EXPECT_EQ("example.com:8080",
  10825. detail::make_host_and_port_string("example.com", 8080, false));
  10826. // IPv4 with non-default HTTPS port
  10827. EXPECT_EQ("example.com:8443",
  10828. detail::make_host_and_port_string("example.com", 8443, true));
  10829. // IPv6 with default HTTP port (80)
  10830. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  10831. // IPv6 with default HTTPS port (443)
  10832. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  10833. // IPv6 with non-default HTTP port
  10834. EXPECT_EQ("[::1]:8080",
  10835. detail::make_host_and_port_string("::1", 8080, false));
  10836. // IPv6 with non-default HTTPS port
  10837. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  10838. // IPv6 full address with default port
  10839. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  10840. detail::make_host_and_port_string(
  10841. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  10842. // IPv6 full address with non-default port
  10843. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  10844. detail::make_host_and_port_string(
  10845. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  10846. // IPv6 localhost with non-default port
  10847. EXPECT_EQ("[::1]:3000",
  10848. detail::make_host_and_port_string("::1", 3000, false));
  10849. // IPv6 with zone ID (link-local address) with default port
  10850. EXPECT_EQ("[fe80::1%eth0]",
  10851. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  10852. // IPv6 with zone ID (link-local address) with non-default port
  10853. EXPECT_EQ("[fe80::1%eth0]:8080",
  10854. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  10855. // Edge case: Port 443 with is_ssl=false (should add port)
  10856. EXPECT_EQ("example.com:443",
  10857. detail::make_host_and_port_string("example.com", 443, false));
  10858. // Edge case: Port 80 with is_ssl=true (should add port)
  10859. EXPECT_EQ("example.com:80",
  10860. detail::make_host_and_port_string("example.com", 80, true));
  10861. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  10862. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  10863. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  10864. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  10865. // Security fix: Already bracketed IPv6 should not get double brackets
  10866. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  10867. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  10868. EXPECT_EQ("[::1]:8080",
  10869. detail::make_host_and_port_string("[::1]", 8080, false));
  10870. EXPECT_EQ("[2001:db8::1]:8080",
  10871. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  10872. EXPECT_EQ("[fe80::1%eth0]",
  10873. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  10874. EXPECT_EQ("[fe80::1%eth0]:8080",
  10875. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  10876. // Edge case: Empty host (should return as-is)
  10877. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  10878. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  10879. // This is a known limitation but shouldn't crash
  10880. EXPECT_EQ("[host:name]",
  10881. detail::make_host_and_port_string("host:name", 80, false));
  10882. // Port number edge cases (no validation, but should not crash)
  10883. EXPECT_EQ("example.com:0",
  10884. detail::make_host_and_port_string("example.com", 0, false));
  10885. EXPECT_EQ("example.com:-1",
  10886. detail::make_host_and_port_string("example.com", -1, false));
  10887. EXPECT_EQ("example.com:65535",
  10888. detail::make_host_and_port_string("example.com", 65535, false));
  10889. EXPECT_EQ("example.com:65536",
  10890. detail::make_host_and_port_string("example.com", 65536, false));
  10891. }
  10892. #ifdef CPPHTTPLIB_SSL_ENABLED
  10893. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  10894. httplib::SSLClient cli("roblox.com", 443);
  10895. cli.set_follow_location(true);
  10896. auto res = cli.Get("/");
  10897. ASSERT_TRUE(res);
  10898. EXPECT_EQ(StatusCode::OK_200, res->status);
  10899. }
  10900. #endif
  10901. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  10902. Server svr;
  10903. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  10904. EXPECT_EQ(res.status, 400);
  10905. });
  10906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10907. auto se = detail::scope_exit([&] {
  10908. svr.stop();
  10909. thread.join();
  10910. ASSERT_FALSE(svr.is_running());
  10911. });
  10912. svr.wait_until_ready();
  10913. Client cli(HOST, PORT);
  10914. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  10915. }
  10916. TEST(InvalidHeaderCharsTest, is_field_name) {
  10917. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  10918. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  10919. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  10920. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  10921. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  10922. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  10923. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  10924. EXPECT_FALSE(detail::fields::is_field_name(""));
  10925. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  10926. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  10927. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  10928. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  10929. }
  10930. TEST(InvalidHeaderCharsTest, is_field_value) {
  10931. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  10932. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  10933. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  10934. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  10935. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  10936. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  10937. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  10938. EXPECT_TRUE(detail::fields::is_field_value(""));
  10939. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  10940. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  10941. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  10942. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  10943. EXPECT_TRUE(detail::fields::is_field_value("0"));
  10944. }
  10945. TEST(InvalidHeaderCharsTest, OnServer) {
  10946. Server svr;
  10947. svr.Get("/test_name", [&](const Request &req, Response &res) {
  10948. std::string header = "Not Set";
  10949. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10950. res.set_header(header, "value");
  10951. res.set_content("Page Content Page Content", "text/plain");
  10952. });
  10953. svr.Get("/test_value", [&](const Request &req, Response &res) {
  10954. std::string header = "Not Set";
  10955. if (req.has_param("header")) { header = req.get_param_value("header"); }
  10956. res.set_header("X-Test", header);
  10957. res.set_content("Page Content Page Content", "text/plain");
  10958. });
  10959. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10960. auto se = detail::scope_exit([&] {
  10961. svr.stop();
  10962. thread.join();
  10963. ASSERT_FALSE(svr.is_running());
  10964. });
  10965. svr.wait_until_ready();
  10966. Client cli(HOST, PORT);
  10967. {
  10968. auto res = cli.Get(
  10969. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10970. ASSERT_TRUE(res);
  10971. EXPECT_EQ("Page Content Page Content", res->body);
  10972. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10973. }
  10974. {
  10975. auto res = cli.Get(
  10976. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  10977. ASSERT_TRUE(res);
  10978. EXPECT_EQ("Page Content Page Content", res->body);
  10979. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  10980. }
  10981. }
  10982. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  10983. auto handled = false;
  10984. Server svr;
  10985. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  10986. thread t = thread([&] { svr.listen(HOST, PORT); });
  10987. auto se = detail::scope_exit([&] {
  10988. svr.stop();
  10989. t.join();
  10990. ASSERT_FALSE(svr.is_running());
  10991. ASSERT_FALSE(handled);
  10992. });
  10993. svr.wait_until_ready();
  10994. auto req = "POST /test HTTP/1.1\r\n"
  10995. "Content-Length: x\r\n"
  10996. "\r\n";
  10997. std::string response;
  10998. ASSERT_TRUE(send_request(1, req, &response));
  10999. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11000. response.substr(0, response.find("\r\n")));
  11001. }
  11002. #ifndef _WIN32
  11003. TEST(Expect100ContinueTest, ServerClosesConnection) {
  11004. static constexpr char reject[] = "Unauthorized";
  11005. static constexpr char accept[] = "Upload accepted";
  11006. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  11007. Server svr;
  11008. svr.set_expect_100_continue_handler(
  11009. [](const Request & /*req*/, Response &res) {
  11010. res.status = StatusCode::Unauthorized_401;
  11011. res.set_content(reject, "text/plain");
  11012. return res.status;
  11013. });
  11014. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  11015. res.set_content(accept, "text/plain");
  11016. });
  11017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11018. auto se = detail::scope_exit([&] {
  11019. svr.stop();
  11020. thread.join();
  11021. ASSERT_FALSE(svr.is_running());
  11022. });
  11023. svr.wait_until_ready();
  11024. {
  11025. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  11026. curl_easy_init(), &curl_easy_cleanup};
  11027. ASSERT_NE(curl, nullptr);
  11028. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  11029. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  11030. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  11031. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  11032. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  11033. &curl_slist_free_all};
  11034. ASSERT_NE(list, nullptr);
  11035. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  11036. struct read_data {
  11037. size_t read_size;
  11038. size_t total_size;
  11039. } data = {0, total_size};
  11040. using read_callback_t =
  11041. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11042. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  11043. void *userdata) -> size_t {
  11044. read_data *data = (read_data *)userdata;
  11045. if (!userdata || data->read_size >= data->total_size) { return 0; }
  11046. std::fill_n(ptr, size * nmemb, 'A');
  11047. data->read_size += size * nmemb;
  11048. return size * nmemb;
  11049. };
  11050. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  11051. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  11052. std::vector<char> buffer;
  11053. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  11054. using write_callback_t =
  11055. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  11056. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  11057. void *userdata) -> size_t {
  11058. std::vector<char> *buffer = (std::vector<char> *)userdata;
  11059. buffer->reserve(buffer->size() + size * nmemb + 1);
  11060. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  11061. return size * nmemb;
  11062. };
  11063. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  11064. {
  11065. const auto res = curl_easy_perform(curl.get());
  11066. ASSERT_EQ(res, CURLE_OK);
  11067. }
  11068. {
  11069. auto response_code = long{};
  11070. const auto res =
  11071. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  11072. ASSERT_EQ(res, CURLE_OK);
  11073. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  11074. }
  11075. {
  11076. auto dl = curl_off_t{};
  11077. const auto res =
  11078. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  11079. ASSERT_EQ(res, CURLE_OK);
  11080. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  11081. }
  11082. {
  11083. buffer.push_back('\0');
  11084. ASSERT_STRCASEEQ(buffer.data(), reject);
  11085. }
  11086. }
  11087. }
  11088. #endif
  11089. template <typename S, typename C>
  11090. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  11091. svr.Get("/stream", [&](const Request &, Response &res) {
  11092. auto data = new std::string("01234567890123456789");
  11093. res.set_content_provider(
  11094. data->size(), "text/plain",
  11095. [&, data](size_t offset, size_t length, DataSink &sink) {
  11096. const size_t DATA_CHUNK_SIZE = 4;
  11097. const auto &d = *data;
  11098. std::this_thread::sleep_for(std::chrono::seconds(1));
  11099. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  11100. return true;
  11101. },
  11102. [data](bool success) {
  11103. EXPECT_FALSE(success);
  11104. delete data;
  11105. });
  11106. });
  11107. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  11108. auto i = new size_t(0);
  11109. res.set_content_provider(
  11110. "text/plain",
  11111. [i](size_t, DataSink &sink) {
  11112. if (*i < 5) {
  11113. std::this_thread::sleep_for(std::chrono::seconds(1));
  11114. sink.write("abcd", 4);
  11115. (*i)++;
  11116. } else {
  11117. sink.done();
  11118. }
  11119. return true;
  11120. },
  11121. [i](bool success) {
  11122. EXPECT_FALSE(success);
  11123. delete i;
  11124. });
  11125. });
  11126. svr.Get("/chunked", [&](const Request &, Response &res) {
  11127. auto i = new size_t(0);
  11128. res.set_chunked_content_provider(
  11129. "text/plain",
  11130. [i](size_t, DataSink &sink) {
  11131. if (*i < 5) {
  11132. std::this_thread::sleep_for(std::chrono::seconds(1));
  11133. sink.os << "abcd";
  11134. (*i)++;
  11135. } else {
  11136. sink.done();
  11137. }
  11138. return true;
  11139. },
  11140. [i](bool success) {
  11141. EXPECT_FALSE(success);
  11142. delete i;
  11143. });
  11144. });
  11145. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11146. auto se = detail::scope_exit([&] {
  11147. svr.stop();
  11148. listen_thread.join();
  11149. ASSERT_FALSE(svr.is_running());
  11150. });
  11151. svr.wait_until_ready();
  11152. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  11153. {
  11154. auto start = std::chrono::steady_clock::now();
  11155. auto res = cli.Get("/stream");
  11156. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11157. std::chrono::steady_clock::now() - start)
  11158. .count();
  11159. ASSERT_FALSE(res);
  11160. EXPECT_EQ(Error::Read, res.error());
  11161. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11162. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11163. }
  11164. {
  11165. auto start = std::chrono::steady_clock::now();
  11166. auto res = cli.Get("/stream_without_length");
  11167. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11168. std::chrono::steady_clock::now() - start)
  11169. .count();
  11170. ASSERT_FALSE(res);
  11171. EXPECT_EQ(Error::Read, res.error());
  11172. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11173. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11174. }
  11175. {
  11176. auto start = std::chrono::steady_clock::now();
  11177. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  11178. EXPECT_EQ("abcd", string(data, data_length));
  11179. return true;
  11180. });
  11181. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11182. std::chrono::steady_clock::now() - start)
  11183. .count();
  11184. ASSERT_FALSE(res);
  11185. EXPECT_EQ(Error::Read, res.error());
  11186. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  11187. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  11188. }
  11189. }
  11190. TEST(MaxTimeoutTest, ContentStream) {
  11191. time_t timeout = 2000;
  11192. time_t threshold = 200;
  11193. Server svr;
  11194. Client cli("localhost", PORT);
  11195. max_timeout_test(svr, cli, timeout, threshold);
  11196. }
  11197. #ifdef CPPHTTPLIB_SSL_ENABLED
  11198. TEST(MaxTimeoutTest, ContentStreamSSL) {
  11199. time_t timeout = 2000;
  11200. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  11201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11202. SSLClient cli("localhost", PORT);
  11203. cli.enable_server_certificate_verification(false);
  11204. max_timeout_test(svr, cli, timeout, threshold);
  11205. }
  11206. #endif
  11207. class EventDispatcher {
  11208. public:
  11209. EventDispatcher() {}
  11210. bool wait_event(DataSink *sink) {
  11211. unique_lock<mutex> lk(m_);
  11212. int id = id_;
  11213. // Wait with timeout to prevent hanging if client disconnects
  11214. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  11215. [&] { return cid_ == id; })) {
  11216. return false; // Timeout occurred
  11217. }
  11218. sink->write(message_.data(), message_.size());
  11219. return true;
  11220. }
  11221. void send_event(const string &message) {
  11222. lock_guard<mutex> lk(m_);
  11223. cid_ = id_++;
  11224. message_ = message;
  11225. cv_.notify_all();
  11226. }
  11227. private:
  11228. mutex m_;
  11229. condition_variable cv_;
  11230. atomic_int id_{0};
  11231. atomic_int cid_{-1};
  11232. string message_;
  11233. };
  11234. TEST(ClientInThreadTest, Issue2068) {
  11235. EventDispatcher ed;
  11236. Server svr;
  11237. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  11238. res.set_chunked_content_provider("text/event-stream",
  11239. [&](size_t /*offset*/, DataSink &sink) {
  11240. return ed.wait_event(&sink);
  11241. });
  11242. });
  11243. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11244. svr.wait_until_ready();
  11245. thread event_thread([&] {
  11246. int id = 0;
  11247. while (svr.is_running()) {
  11248. this_thread::sleep_for(chrono::milliseconds(500));
  11249. std::stringstream ss;
  11250. ss << "data: " << id << "\n\n";
  11251. ed.send_event(ss.str());
  11252. id++;
  11253. }
  11254. });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. listen_thread.join();
  11258. event_thread.join();
  11259. ASSERT_FALSE(svr.is_running());
  11260. });
  11261. {
  11262. auto client = detail::make_unique<Client>(HOST, PORT);
  11263. client->set_read_timeout(std::chrono::minutes(10));
  11264. std::atomic<bool> stop{false};
  11265. std::thread t([&] {
  11266. client->Get("/event1",
  11267. [&](const char *, size_t) -> bool { return !stop; });
  11268. });
  11269. std::this_thread::sleep_for(std::chrono::seconds(2));
  11270. stop = true;
  11271. client->stop();
  11272. t.join();
  11273. // Reset client after thread has finished
  11274. client.reset();
  11275. }
  11276. }
  11277. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  11278. auto handled = false;
  11279. Server svr;
  11280. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  11281. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11282. auto se = detail::scope_exit([&] {
  11283. svr.stop();
  11284. t.join();
  11285. ASSERT_FALSE(svr.is_running());
  11286. ASSERT_FALSE(handled);
  11287. });
  11288. svr.wait_until_ready();
  11289. // Two Content-Length headers with different values — must be rejected
  11290. auto req = "POST /test HTTP/1.1\r\n"
  11291. "Content-Length: 5\r\n"
  11292. "Content-Length: 10\r\n"
  11293. "\r\n"
  11294. "hello";
  11295. std::string response;
  11296. ASSERT_TRUE(send_request(1, req, &response));
  11297. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  11298. response.substr(0, response.find("\r\n")));
  11299. }
  11300. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  11301. auto handled = false;
  11302. Server svr;
  11303. svr.Post("/test", [&](const Request &, Response &res) {
  11304. handled = true;
  11305. res.set_content("ok", "text/plain");
  11306. });
  11307. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11308. auto se = detail::scope_exit([&] {
  11309. svr.stop();
  11310. t.join();
  11311. ASSERT_FALSE(svr.is_running());
  11312. ASSERT_TRUE(handled);
  11313. });
  11314. svr.wait_until_ready();
  11315. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  11316. auto req = "POST /test HTTP/1.1\r\n"
  11317. "Content-Length: 5\r\n"
  11318. "Content-Length: 5\r\n"
  11319. "\r\n"
  11320. "hello";
  11321. std::string response;
  11322. ASSERT_TRUE(send_request(1, req, &response));
  11323. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  11324. }
  11325. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  11326. Server svr;
  11327. svr.Get("/", [](const Request &req, Response &res) {
  11328. EXPECT_EQ(2U, req.trailers.size());
  11329. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  11330. // Denied
  11331. EXPECT_FALSE(req.has_trailer("Content-Length"));
  11332. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  11333. // Accepted
  11334. EXPECT_TRUE(req.has_trailer("X-Hello"));
  11335. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  11336. EXPECT_TRUE(req.has_trailer("X-World"));
  11337. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  11338. res.set_content("ok", "text/plain");
  11339. });
  11340. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11341. auto se = detail::scope_exit([&] {
  11342. svr.stop();
  11343. t.join();
  11344. ASSERT_FALSE(svr.is_running());
  11345. });
  11346. svr.wait_until_ready();
  11347. const std::string req = "GET / HTTP/1.1\r\n"
  11348. "Transfer-Encoding: chunked\r\n"
  11349. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  11350. "\r\n"
  11351. "0\r\n"
  11352. "Content-Length: 10\r\n"
  11353. "Host: internal.local\r\n"
  11354. "Content-Type: malicious/content\r\n"
  11355. "Cookie: any\r\n"
  11356. "Set-Cookie: any\r\n"
  11357. "X-Forwarded-For: attacker.com\r\n"
  11358. "X-Real-Ip: 1.1.1.1\r\n"
  11359. "X-Hello: hello\r\n"
  11360. "X-World: world\r\n"
  11361. "\r\n";
  11362. std::string res;
  11363. ASSERT_TRUE(send_request(1, req, &res));
  11364. }
  11365. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  11366. Server svr;
  11367. std::string observed_remote_addr;
  11368. std::string observed_xff;
  11369. svr.Get("/ip", [&](const Request &req, Response &res) {
  11370. observed_remote_addr = req.remote_addr;
  11371. observed_xff = req.get_header_value("X-Forwarded-For");
  11372. res.set_content("ok", "text/plain");
  11373. });
  11374. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11375. auto se = detail::scope_exit([&] {
  11376. svr.stop();
  11377. t.join();
  11378. ASSERT_FALSE(svr.is_running());
  11379. });
  11380. svr.wait_until_ready();
  11381. Client cli(HOST, PORT);
  11382. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  11383. ASSERT_TRUE(res);
  11384. EXPECT_EQ(StatusCode::OK_200, res->status);
  11385. EXPECT_EQ(observed_xff, "203.0.113.66");
  11386. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11387. observed_remote_addr == "127.0.0.1");
  11388. }
  11389. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  11390. Server svr;
  11391. svr.set_trusted_proxies({"203.0.113.66"});
  11392. std::string observed_remote_addr;
  11393. std::string observed_xff;
  11394. svr.Get("/ip", [&](const Request &req, Response &res) {
  11395. observed_remote_addr = req.remote_addr;
  11396. observed_xff = req.get_header_value("X-Forwarded-For");
  11397. res.set_content("ok", "text/plain");
  11398. });
  11399. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11400. auto se = detail::scope_exit([&] {
  11401. svr.stop();
  11402. t.join();
  11403. ASSERT_FALSE(svr.is_running());
  11404. });
  11405. svr.wait_until_ready();
  11406. Client cli(HOST, PORT);
  11407. auto res = cli.Get("/ip");
  11408. ASSERT_TRUE(res);
  11409. EXPECT_EQ(StatusCode::OK_200, res->status);
  11410. EXPECT_EQ(observed_xff, "");
  11411. EXPECT_TRUE(observed_remote_addr == "::1" ||
  11412. observed_remote_addr == "127.0.0.1");
  11413. }
  11414. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  11415. Server svr;
  11416. svr.set_trusted_proxies({"203.0.113.66"});
  11417. std::string observed_remote_addr;
  11418. std::string observed_xff;
  11419. svr.Get("/ip", [&](const Request &req, Response &res) {
  11420. observed_remote_addr = req.remote_addr;
  11421. observed_xff = req.get_header_value("X-Forwarded-For");
  11422. res.set_content("ok", "text/plain");
  11423. });
  11424. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11425. auto se = detail::scope_exit([&] {
  11426. svr.stop();
  11427. t.join();
  11428. ASSERT_FALSE(svr.is_running());
  11429. });
  11430. svr.wait_until_ready();
  11431. Client cli(HOST, PORT);
  11432. auto res =
  11433. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  11434. ASSERT_TRUE(res);
  11435. EXPECT_EQ(StatusCode::OK_200, res->status);
  11436. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  11437. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11438. }
  11439. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  11440. Server svr;
  11441. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  11442. std::string observed_remote_addr;
  11443. std::string observed_xff;
  11444. svr.Get("/ip", [&](const Request &req, Response &res) {
  11445. observed_remote_addr = req.remote_addr;
  11446. observed_xff = req.get_header_value("X-Forwarded-For");
  11447. res.set_content("ok", "text/plain");
  11448. });
  11449. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11450. auto se = detail::scope_exit([&] {
  11451. svr.stop();
  11452. t.join();
  11453. ASSERT_FALSE(svr.is_running());
  11454. });
  11455. svr.wait_until_ready();
  11456. Client cli(HOST, PORT);
  11457. auto res = cli.Get(
  11458. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11459. ASSERT_TRUE(res);
  11460. EXPECT_EQ(StatusCode::OK_200, res->status);
  11461. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11462. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11463. }
  11464. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  11465. Server svr;
  11466. svr.set_trusted_proxies({"192.0.2.45"});
  11467. std::string observed_remote_addr;
  11468. std::string observed_xff;
  11469. svr.Get("/ip", [&](const Request &req, Response &res) {
  11470. observed_remote_addr = req.remote_addr;
  11471. observed_xff = req.get_header_value("X-Forwarded-For");
  11472. res.set_content("ok", "text/plain");
  11473. });
  11474. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11475. auto se = detail::scope_exit([&] {
  11476. svr.stop();
  11477. t.join();
  11478. ASSERT_FALSE(svr.is_running());
  11479. });
  11480. svr.wait_until_ready();
  11481. Client cli(HOST, PORT);
  11482. auto res =
  11483. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  11484. ASSERT_TRUE(res);
  11485. EXPECT_EQ(StatusCode::OK_200, res->status);
  11486. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  11487. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  11488. }
  11489. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  11490. Server svr;
  11491. svr.set_trusted_proxies({"192.0.2.45"});
  11492. std::string observed_remote_addr;
  11493. std::string observed_xff;
  11494. svr.Get("/ip", [&](const Request &req, Response &res) {
  11495. observed_remote_addr = req.remote_addr;
  11496. observed_xff = req.get_header_value("X-Forwarded-For");
  11497. res.set_content("ok", "text/plain");
  11498. });
  11499. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11500. auto se = detail::scope_exit([&] {
  11501. svr.stop();
  11502. t.join();
  11503. ASSERT_FALSE(svr.is_running());
  11504. });
  11505. svr.wait_until_ready();
  11506. Client cli(HOST, PORT);
  11507. auto res = cli.Get(
  11508. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  11509. ASSERT_TRUE(res);
  11510. EXPECT_EQ(StatusCode::OK_200, res->status);
  11511. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  11512. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11513. }
  11514. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  11515. Server svr;
  11516. svr.set_trusted_proxies({"192.0.2.45"});
  11517. std::string observed_remote_addr;
  11518. std::string observed_xff;
  11519. svr.Get("/ip", [&](const Request &req, Response &res) {
  11520. observed_remote_addr = req.remote_addr;
  11521. observed_xff = req.get_header_value("X-Forwarded-For");
  11522. res.set_content("ok", "text/plain");
  11523. });
  11524. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11525. auto se = detail::scope_exit([&] {
  11526. svr.stop();
  11527. t.join();
  11528. ASSERT_FALSE(svr.is_running());
  11529. });
  11530. svr.wait_until_ready();
  11531. std::string raw_req =
  11532. "GET /ip HTTP/1.1\r\n"
  11533. "Host: localhost\r\n"
  11534. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  11535. "Connection: close\r\n"
  11536. "\r\n";
  11537. std::string out;
  11538. ASSERT_TRUE(send_request(5, raw_req, &out));
  11539. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11540. // Header parser trims surrounding whitespace of the header value
  11541. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  11542. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  11543. }
  11544. #ifndef _WIN32
  11545. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  11546. Server svr;
  11547. svr.Post("/post", [&](const Request &req, Response &res) {
  11548. res.set_content(req.body, "text/plain");
  11549. });
  11550. svr.Put("/put", [&](const Request &req, Response &res) {
  11551. res.set_content(req.body, "text/plain");
  11552. });
  11553. svr.Patch("/patch", [&](const Request &req, Response &res) {
  11554. res.set_content(req.body, "text/plain");
  11555. });
  11556. svr.Delete("/delete", [&](const Request &req, Response &res) {
  11557. res.set_content(req.body, "text/plain");
  11558. });
  11559. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11560. auto se = detail::scope_exit([&] {
  11561. svr.stop();
  11562. t.join();
  11563. ASSERT_FALSE(svr.is_running());
  11564. });
  11565. svr.wait_until_ready();
  11566. std::string resp;
  11567. // POST without Content-Length
  11568. ASSERT_TRUE(send_request(5,
  11569. "POST /post HTTP/1.1\r\n"
  11570. "Host: localhost\r\n"
  11571. "Connection: close\r\n"
  11572. "\r\n",
  11573. &resp));
  11574. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11575. // PUT without Content-Length
  11576. resp.clear();
  11577. ASSERT_TRUE(send_request(5,
  11578. "PUT /put HTTP/1.1\r\n"
  11579. "Host: localhost\r\n"
  11580. "Connection: close\r\n"
  11581. "\r\n",
  11582. &resp));
  11583. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11584. // PATCH without Content-Length
  11585. resp.clear();
  11586. ASSERT_TRUE(send_request(5,
  11587. "PATCH /patch HTTP/1.1\r\n"
  11588. "Host: localhost\r\n"
  11589. "Connection: close\r\n"
  11590. "\r\n",
  11591. &resp));
  11592. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11593. // DELETE without Content-Length
  11594. resp.clear();
  11595. ASSERT_TRUE(send_request(5,
  11596. "DELETE /delete HTTP/1.1\r\n"
  11597. "Host: localhost\r\n"
  11598. "Connection: close\r\n"
  11599. "\r\n",
  11600. &resp));
  11601. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  11602. }
  11603. #endif
  11604. //==============================================================================
  11605. // open_stream() Tests
  11606. //==============================================================================
  11607. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  11608. std::string result;
  11609. char buf[8192];
  11610. ssize_t n;
  11611. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11612. result.append(buf, static_cast<size_t>(n));
  11613. }
  11614. return result;
  11615. }
  11616. // Mock stream for unit tests
  11617. class MockStream : public Stream {
  11618. public:
  11619. std::string data;
  11620. size_t pos = 0;
  11621. ssize_t error_after = -1; // -1 = no error
  11622. explicit MockStream(const std::string &d, ssize_t err = -1)
  11623. : data(d), error_after(err) {}
  11624. bool is_readable() const override { return true; }
  11625. bool wait_readable() const override { return true; }
  11626. bool wait_writable() const override { return true; }
  11627. ssize_t read(char *ptr, size_t size) override {
  11628. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  11629. if (pos >= data.size()) return 0;
  11630. size_t limit =
  11631. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  11632. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  11633. std::memcpy(ptr, data.data() + pos, to_read);
  11634. pos += to_read;
  11635. return static_cast<ssize_t>(to_read);
  11636. }
  11637. ssize_t write(const char *, size_t) override { return -1; }
  11638. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  11639. ip = "127.0.0.1";
  11640. port = 0;
  11641. }
  11642. void get_local_ip_and_port(std::string &ip, int &port) const override {
  11643. ip = "127.0.0.1";
  11644. port = 0;
  11645. }
  11646. socket_t socket() const override { return INVALID_SOCKET; }
  11647. time_t duration() const override { return 0; }
  11648. };
  11649. TEST(StreamHandleTest, Basic) {
  11650. ClientImpl::StreamHandle handle;
  11651. EXPECT_FALSE(handle.is_valid());
  11652. handle.response = detail::make_unique<Response>();
  11653. handle.error = Error::Connection;
  11654. EXPECT_FALSE(handle.is_valid());
  11655. handle.error = Error::Success;
  11656. EXPECT_TRUE(handle.is_valid());
  11657. }
  11658. TEST(BodyReaderTest, Basic) {
  11659. MockStream stream("Hello, World!");
  11660. detail::BodyReader reader;
  11661. reader.stream = &stream;
  11662. reader.content_length = 13;
  11663. char buf[32];
  11664. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  11665. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  11666. EXPECT_TRUE(reader.eof);
  11667. }
  11668. TEST(BodyReaderTest, NoStream) {
  11669. detail::BodyReader reader;
  11670. char buf[32];
  11671. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11672. EXPECT_EQ(Error::Connection, reader.last_error);
  11673. }
  11674. TEST(BodyReaderTest, Error) {
  11675. MockStream stream("Hello, World!", 5);
  11676. detail::BodyReader reader;
  11677. reader.stream = &stream;
  11678. reader.content_length = 13;
  11679. char buf[32];
  11680. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  11681. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  11682. EXPECT_EQ(Error::Read, reader.last_error);
  11683. }
  11684. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  11685. // Mock-based StreamHandle tests relying on private internals are removed.
  11686. class OpenStreamTest : public ::testing::Test {
  11687. protected:
  11688. void SetUp() override {
  11689. svr_.Get("/hello", [](const Request &, Response &res) {
  11690. res.set_content("Hello World!", "text/plain");
  11691. });
  11692. svr_.Get("/large", [](const Request &, Response &res) {
  11693. res.set_content(std::string(10000, 'X'), "text/plain");
  11694. });
  11695. svr_.Get("/chunked", [](const Request &, Response &res) {
  11696. res.set_chunked_content_provider("text/plain",
  11697. [](size_t offset, DataSink &sink) {
  11698. if (offset < 15) {
  11699. sink.write("chunk", 5);
  11700. return true;
  11701. }
  11702. sink.done();
  11703. return true;
  11704. });
  11705. });
  11706. svr_.Get("/compressible", [](const Request &, Response &res) {
  11707. res.set_chunked_content_provider("text/plain", [](size_t offset,
  11708. DataSink &sink) {
  11709. if (offset < 100 * 1024) {
  11710. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  11711. sink.write(chunk.data(), chunk.size());
  11712. return true;
  11713. }
  11714. sink.done();
  11715. return true;
  11716. });
  11717. });
  11718. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  11719. [](const Request & /*req*/, Response &res) {
  11720. auto i = new int(0);
  11721. res.set_header("Trailer", "Content-Length, X-Allowed");
  11722. res.set_chunked_content_provider(
  11723. "text/plain",
  11724. [i](size_t /*offset*/, DataSink &sink) {
  11725. switch (*i) {
  11726. case 0: sink.os << "123"; break;
  11727. case 1: sink.os << "456"; break;
  11728. case 2: sink.os << "789"; break;
  11729. case 3: {
  11730. sink.done_with_trailer(
  11731. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  11732. } break;
  11733. }
  11734. (*i)++;
  11735. return true;
  11736. },
  11737. [i](bool success) {
  11738. EXPECT_TRUE(success);
  11739. delete i;
  11740. });
  11741. });
  11742. // Echo headers endpoint for header-related tests
  11743. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  11744. std::string body;
  11745. for (const auto &h : req.headers) {
  11746. body.append(h.first);
  11747. body.push_back(':');
  11748. body.append(h.second);
  11749. body.push_back('\n');
  11750. }
  11751. res.set_content(body, "text/plain");
  11752. });
  11753. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  11754. std::string body;
  11755. for (const auto &h : req.headers) {
  11756. body.append(h.first);
  11757. body.push_back(':');
  11758. body.append(h.second);
  11759. body.push_back('\n');
  11760. }
  11761. res.set_content(body, "text/plain");
  11762. });
  11763. port_ = svr_.bind_to_any_port("127.0.0.1");
  11764. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  11765. svr_.wait_until_ready();
  11766. }
  11767. void TearDown() override {
  11768. svr_.stop();
  11769. if (thread_.joinable()) thread_.join();
  11770. }
  11771. Server svr_;
  11772. std::thread thread_;
  11773. int port_ = 0;
  11774. };
  11775. TEST_F(OpenStreamTest, Basic) {
  11776. Client cli("127.0.0.1", port_);
  11777. auto handle = cli.open_stream("GET", "/hello");
  11778. EXPECT_TRUE(handle.is_valid());
  11779. EXPECT_EQ("Hello World!", read_all(handle));
  11780. }
  11781. TEST_F(OpenStreamTest, SmallBuffer) {
  11782. Client cli("127.0.0.1", port_);
  11783. auto handle = cli.open_stream("GET", "/hello");
  11784. std::string result;
  11785. char buf[4];
  11786. ssize_t n;
  11787. while ((n = handle.read(buf, sizeof(buf))) > 0)
  11788. result.append(buf, static_cast<size_t>(n));
  11789. EXPECT_EQ("Hello World!", result);
  11790. }
  11791. TEST_F(OpenStreamTest, DefaultHeaders) {
  11792. Client cli("127.0.0.1", port_);
  11793. // open_stream GET should include Host, User-Agent and Accept-Encoding
  11794. {
  11795. auto handle = cli.open_stream("GET", "/echo-headers");
  11796. ASSERT_TRUE(handle.is_valid());
  11797. auto body = read_all(handle);
  11798. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  11799. std::string::npos);
  11800. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  11801. std::string::npos);
  11802. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  11803. }
  11804. // open_stream POST with body and no explicit content_type should NOT add
  11805. // text/plain Content-Type (behavior differs from non-streaming path), but
  11806. // should include Content-Length
  11807. {
  11808. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  11809. ASSERT_TRUE(handle.is_valid());
  11810. auto body = read_all(handle);
  11811. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  11812. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  11813. }
  11814. // open_stream POST with explicit Content-Type should preserve it
  11815. {
  11816. auto handle = cli.open_stream("POST", "/echo-headers", {},
  11817. {{"Content-Type", "application/custom"}},
  11818. "{}", "application/custom");
  11819. ASSERT_TRUE(handle.is_valid());
  11820. auto body = read_all(handle);
  11821. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  11822. }
  11823. // User-specified User-Agent must not be overwritten for stream API
  11824. {
  11825. auto handle = cli.open_stream("GET", "/echo-headers", {},
  11826. {{"User-Agent", "MyAgent/1.2"}});
  11827. ASSERT_TRUE(handle.is_valid());
  11828. auto body = read_all(handle);
  11829. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  11830. }
  11831. }
  11832. TEST_F(OpenStreamTest, Large) {
  11833. Client cli("127.0.0.1", port_);
  11834. auto handle = cli.open_stream("GET", "/large");
  11835. EXPECT_EQ(10000u, read_all(handle).size());
  11836. }
  11837. TEST_F(OpenStreamTest, ConnectionError) {
  11838. Client cli("127.0.0.1", 9999);
  11839. auto handle = cli.open_stream("GET", "/hello");
  11840. EXPECT_FALSE(handle.is_valid());
  11841. }
  11842. TEST_F(OpenStreamTest, Chunked) {
  11843. Client cli("127.0.0.1", port_);
  11844. auto handle = cli.open_stream("GET", "/chunked");
  11845. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  11846. "Transfer-Encoding") == "chunked");
  11847. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  11848. }
  11849. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  11850. Client cli("127.0.0.1", port_);
  11851. auto handle =
  11852. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  11853. ASSERT_TRUE(handle.is_valid());
  11854. // Consume body to allow trailers to be received/parsed
  11855. auto body = read_all(handle);
  11856. // Explicitly parse trailers (ensure trailers are available for assertion)
  11857. handle.parse_trailers_if_needed();
  11858. EXPECT_EQ(std::string("123456789"), body);
  11859. // The response should include a Trailer header declaring both names
  11860. ASSERT_TRUE(handle.response);
  11861. EXPECT_TRUE(handle.response->has_header("Trailer"));
  11862. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  11863. handle.response->get_header_value("Trailer"));
  11864. // Prohibited trailer must not be present
  11865. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  11866. // Allowed trailer should be present
  11867. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  11868. EXPECT_EQ(std::string("yes"),
  11869. handle.response->get_trailer_value("X-Allowed"));
  11870. // Verify trailers are NOT present as regular headers
  11871. EXPECT_EQ(std::string(""),
  11872. handle.response->get_header_value("Content-Length"));
  11873. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  11874. }
  11875. static std::thread serve_single_response(std::promise<int> &port_promise,
  11876. const std::string &response) {
  11877. return std::thread([&port_promise, response] {
  11878. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11879. default_socket_options(srv);
  11880. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11882. sockaddr_in addr{};
  11883. addr.sin_family = AF_INET;
  11884. addr.sin_port = htons(0); // Let OS assign a free port
  11885. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11886. int opt = 1;
  11887. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11888. #ifdef _WIN32
  11889. reinterpret_cast<const char *>(&opt),
  11890. #else
  11891. &opt,
  11892. #endif
  11893. sizeof(opt));
  11894. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  11895. ::listen(srv, 1) != 0) {
  11896. port_promise.set_value(-1);
  11897. detail::close_socket(srv);
  11898. return;
  11899. }
  11900. socklen_t addr_len = sizeof(addr);
  11901. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  11902. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  11903. sockaddr_in cli_addr{};
  11904. socklen_t cli_len = sizeof(cli_addr);
  11905. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11906. if (cli != INVALID_SOCKET) {
  11907. char buf[4096];
  11908. ::recv(cli, buf, sizeof(buf), 0);
  11909. ::send(cli,
  11910. #ifdef _WIN32
  11911. static_cast<const char *>(response.c_str()),
  11912. static_cast<int>(response.size()),
  11913. #else
  11914. response.c_str(), response.size(),
  11915. #endif
  11916. 0);
  11917. detail::close_socket(cli);
  11918. }
  11919. detail::close_socket(srv);
  11920. });
  11921. }
  11922. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  11923. #ifndef _WIN32
  11924. signal(SIGPIPE, SIG_IGN);
  11925. #endif
  11926. std::promise<int> port_promise;
  11927. auto port_future = port_promise.get_future();
  11928. auto server_thread =
  11929. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  11930. "Content-Type: text/plain\r\n"
  11931. "Content-Length: not-a-number\r\n"
  11932. "Connection: close\r\n"
  11933. "\r\n"
  11934. "hello");
  11935. auto port = port_future.get();
  11936. ASSERT_GT(port, 0);
  11937. Client cli("127.0.0.1", port);
  11938. auto handle = cli.open_stream("GET", "/");
  11939. EXPECT_FALSE(handle.is_valid());
  11940. server_thread.join();
  11941. }
  11942. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  11943. #ifndef _WIN32
  11944. signal(SIGPIPE, SIG_IGN);
  11945. #endif
  11946. std::promise<int> port_promise;
  11947. auto port_future = port_promise.get_future();
  11948. auto server_thread = serve_single_response(
  11949. port_promise, "HTTP/1.1 200 OK\r\n"
  11950. "Content-Type: text/plain\r\n"
  11951. "Content-Length: 99999999999999999999999999\r\n"
  11952. "Connection: close\r\n"
  11953. "\r\n"
  11954. "hello");
  11955. auto port = port_future.get();
  11956. ASSERT_GT(port, 0);
  11957. // Before the fix, std::stoull would throw std::out_of_range here and
  11958. // crash the process. After the fix, strtoull silently clamps to
  11959. // ULLONG_MAX so the stream opens without crashing. The important thing
  11960. // is that the process does NOT terminate.
  11961. Client cli("127.0.0.1", port);
  11962. auto handle = cli.open_stream("GET", "/");
  11963. EXPECT_TRUE(handle.is_valid());
  11964. server_thread.join();
  11965. }
  11966. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11967. TEST_F(OpenStreamTest, Gzip) {
  11968. Client cli("127.0.0.1", port_);
  11969. auto handle = cli.open_stream("GET", "/compressible", {},
  11970. {{"Accept-Encoding", "gzip"}});
  11971. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  11972. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11973. }
  11974. #endif
  11975. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11976. TEST_F(OpenStreamTest, Brotli) {
  11977. Client cli("127.0.0.1", port_);
  11978. auto handle =
  11979. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  11980. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  11981. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11982. }
  11983. #endif
  11984. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11985. TEST_F(OpenStreamTest, Zstd) {
  11986. Client cli("127.0.0.1", port_);
  11987. auto handle = cli.open_stream("GET", "/compressible", {},
  11988. {{"Accept-Encoding", "zstd"}});
  11989. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  11990. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  11991. }
  11992. #endif
  11993. #ifdef CPPHTTPLIB_SSL_ENABLED
  11994. class SSLOpenStreamTest : public ::testing::Test {
  11995. protected:
  11996. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  11997. void SetUp() override {
  11998. svr_.Get("/hello", [](const Request &, Response &res) {
  11999. res.set_content("Hello SSL World!", "text/plain");
  12000. });
  12001. svr_.Get("/chunked", [](const Request &, Response &res) {
  12002. res.set_chunked_content_provider("text/plain",
  12003. [](size_t offset, DataSink &sink) {
  12004. if (offset < 15) {
  12005. sink.write("chunk", 5);
  12006. return true;
  12007. }
  12008. sink.done();
  12009. return true;
  12010. });
  12011. });
  12012. svr_.Post("/echo", [](const Request &req, Response &res) {
  12013. res.set_content(req.body, req.get_header_value("Content-Type"));
  12014. });
  12015. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  12016. std::string body = req.body;
  12017. res.set_chunked_content_provider(
  12018. "text/plain", [body](size_t offset, DataSink &sink) {
  12019. if (offset < body.size()) {
  12020. sink.write(body.data() + offset, body.size() - offset);
  12021. }
  12022. sink.done();
  12023. return true;
  12024. });
  12025. });
  12026. port_ = svr_.bind_to_any_port("127.0.0.1");
  12027. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12028. svr_.wait_until_ready();
  12029. }
  12030. void TearDown() override {
  12031. svr_.stop();
  12032. if (thread_.joinable()) thread_.join();
  12033. }
  12034. SSLServer svr_;
  12035. std::thread thread_;
  12036. int port_ = 0;
  12037. };
  12038. TEST_F(SSLOpenStreamTest, Basic) {
  12039. SSLClient cli("127.0.0.1", port_);
  12040. cli.enable_server_certificate_verification(false);
  12041. auto handle = cli.open_stream("GET", "/hello");
  12042. ASSERT_TRUE(handle.is_valid());
  12043. EXPECT_EQ("Hello SSL World!", read_all(handle));
  12044. }
  12045. TEST_F(SSLOpenStreamTest, Chunked) {
  12046. SSLClient cli("127.0.0.1", port_);
  12047. cli.enable_server_certificate_verification(false);
  12048. auto handle = cli.open_stream("GET", "/chunked");
  12049. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12050. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  12051. "Transfer-Encoding") == "chunked");
  12052. auto body = read_all(handle);
  12053. EXPECT_EQ("chunkchunkchunk", body);
  12054. }
  12055. TEST_F(SSLOpenStreamTest, Post) {
  12056. SSLClient cli("127.0.0.1", port_);
  12057. cli.enable_server_certificate_verification(false);
  12058. auto handle =
  12059. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  12060. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  12061. EXPECT_EQ(200, handle.response->status);
  12062. auto body = read_all(handle);
  12063. EXPECT_EQ("Hello SSL POST", body);
  12064. }
  12065. TEST_F(SSLOpenStreamTest, PostChunked) {
  12066. SSLClient cli("127.0.0.1", port_);
  12067. cli.enable_server_certificate_verification(false);
  12068. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  12069. "Chunked SSL Data", "text/plain");
  12070. ASSERT_TRUE(handle.is_valid());
  12071. EXPECT_EQ(200, handle.response->status);
  12072. auto body = read_all(handle);
  12073. EXPECT_EQ("Chunked SSL Data", body);
  12074. }
  12075. #endif // CPPHTTPLIB_SSL_ENABLED
  12076. //==============================================================================
  12077. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  12078. // results for various scenarios.
  12079. //==============================================================================
  12080. TEST(ParityTest, GetVsOpenStream) {
  12081. Server svr;
  12082. const std::string path = "/parity";
  12083. const std::string content = "Parity test content: hello world";
  12084. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12085. res.set_content(content, "text/plain");
  12086. });
  12087. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12088. auto se = detail::scope_exit([&] {
  12089. svr.stop();
  12090. t.join();
  12091. ASSERT_FALSE(svr.is_running());
  12092. });
  12093. svr.wait_until_ready();
  12094. Client cli(HOST, PORT);
  12095. // Non-stream path
  12096. auto r1 = cli.Get(path);
  12097. ASSERT_TRUE(r1);
  12098. EXPECT_EQ(StatusCode::OK_200, r1->status);
  12099. // Stream path
  12100. auto h = cli.open_stream("GET", path);
  12101. ASSERT_TRUE(h.is_valid());
  12102. EXPECT_EQ(r1->body, read_all(h));
  12103. }
  12104. // Helper to compress data with provided compressor type T
  12105. template <typename Compressor>
  12106. static std::string compress_payload_for_parity(const std::string &in) {
  12107. std::string out;
  12108. Compressor compressor;
  12109. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  12110. [&](const char *data, size_t n) {
  12111. out.append(data, n);
  12112. return true;
  12113. });
  12114. EXPECT_TRUE(ok);
  12115. return out;
  12116. }
  12117. // Helper function for compression parity tests
  12118. template <typename Compressor>
  12119. static void test_compression_parity(const std::string &original,
  12120. const std::string &path,
  12121. const std::string &encoding) {
  12122. const std::string compressed =
  12123. compress_payload_for_parity<Compressor>(original);
  12124. Server svr;
  12125. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  12126. res.set_content(compressed, "application/octet-stream");
  12127. res.set_header("Content-Encoding", encoding);
  12128. });
  12129. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  12130. auto se = detail::scope_exit([&] {
  12131. svr.stop();
  12132. t.join();
  12133. ASSERT_FALSE(svr.is_running());
  12134. });
  12135. svr.wait_until_ready();
  12136. Client cli(HOST, PORT);
  12137. // Non-streaming
  12138. {
  12139. auto res = cli.Get(path);
  12140. ASSERT_TRUE(res);
  12141. EXPECT_EQ(StatusCode::OK_200, res->status);
  12142. EXPECT_EQ(original, res->body);
  12143. }
  12144. // Streaming
  12145. {
  12146. auto h = cli.open_stream("GET", path);
  12147. ASSERT_TRUE(h.is_valid());
  12148. EXPECT_EQ(original, read_all(h));
  12149. }
  12150. }
  12151. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12152. TEST(ParityTest, Gzip) {
  12153. test_compression_parity<detail::gzip_compressor>(
  12154. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  12155. }
  12156. #endif
  12157. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12158. TEST(ParityTest, Brotli) {
  12159. test_compression_parity<detail::brotli_compressor>(
  12160. "Hello, brotli parity test payload", "/parity-br", "br");
  12161. }
  12162. #endif
  12163. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  12164. TEST(ParityTest, Zstd) {
  12165. test_compression_parity<detail::zstd_compressor>(
  12166. "Zstandard parity test payload", "/parity-zstd", "zstd");
  12167. }
  12168. #endif
  12169. //==============================================================================
  12170. // New Stream API Tests
  12171. //==============================================================================
  12172. inline std::string read_body(httplib::stream::Result &result) {
  12173. std::string body;
  12174. while (result.next()) {
  12175. body.append(result.data(), result.size());
  12176. }
  12177. return body;
  12178. }
  12179. TEST(ClientConnectionTest, Basic) {
  12180. httplib::ClientConnection conn;
  12181. EXPECT_FALSE(conn.is_open());
  12182. conn.sock = 1;
  12183. EXPECT_TRUE(conn.is_open());
  12184. httplib::ClientConnection conn2(std::move(conn));
  12185. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  12186. conn2.sock = INVALID_SOCKET;
  12187. }
  12188. // Unified test server for all stream::* tests
  12189. class StreamApiTest : public ::testing::Test {
  12190. protected:
  12191. void SetUp() override {
  12192. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12193. res.set_content("Hello World!", "text/plain");
  12194. });
  12195. svr_.Get("/echo-params",
  12196. [](const httplib::Request &req, httplib::Response &res) {
  12197. std::string r;
  12198. for (const auto &p : req.params) {
  12199. if (!r.empty()) r += "&";
  12200. r += p.first + "=" + p.second;
  12201. }
  12202. res.set_content(r, "text/plain");
  12203. });
  12204. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12205. res.set_content(req.body, req.get_header_value("Content-Type"));
  12206. });
  12207. svr_.Post("/echo-headers",
  12208. [](const httplib::Request &req, httplib::Response &res) {
  12209. std::string r;
  12210. for (const auto &h : req.headers)
  12211. r += h.first + ": " + h.second + "\n";
  12212. res.set_content(r, "text/plain");
  12213. });
  12214. svr_.Post("/echo-params",
  12215. [](const httplib::Request &req, httplib::Response &res) {
  12216. std::string r = "params:";
  12217. for (const auto &p : req.params)
  12218. r += p.first + "=" + p.second + ";";
  12219. res.set_content(r + " body:" + req.body, "text/plain");
  12220. });
  12221. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  12222. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  12223. });
  12224. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12225. res.set_content("PUT:" + req.body, "text/plain");
  12226. });
  12227. svr_.Patch("/echo",
  12228. [](const httplib::Request &req, httplib::Response &res) {
  12229. res.set_content("PATCH:" + req.body, "text/plain");
  12230. });
  12231. svr_.Delete(
  12232. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  12233. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  12234. "text/plain");
  12235. });
  12236. svr_.Get("/head-test",
  12237. [](const httplib::Request &, httplib::Response &res) {
  12238. res.set_content("body for HEAD", "text/plain");
  12239. });
  12240. svr_.Options("/options",
  12241. [](const httplib::Request &, httplib::Response &res) {
  12242. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  12243. });
  12244. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  12245. svr_.wait_until_ready();
  12246. }
  12247. void TearDown() override {
  12248. svr_.stop();
  12249. if (thread_.joinable()) thread_.join();
  12250. }
  12251. httplib::Server svr_;
  12252. std::thread thread_;
  12253. };
  12254. // stream::Get tests
  12255. TEST_F(StreamApiTest, GetBasic) {
  12256. httplib::Client cli(HOST, PORT);
  12257. auto result = httplib::stream::Get(cli, "/hello");
  12258. ASSERT_TRUE(result.is_valid());
  12259. EXPECT_EQ(200, result.status());
  12260. EXPECT_EQ("Hello World!", read_body(result));
  12261. }
  12262. TEST_F(StreamApiTest, GetWithParams) {
  12263. httplib::Client cli(HOST, PORT);
  12264. httplib::Params params{{"foo", "bar"}};
  12265. auto result = httplib::stream::Get(cli, "/echo-params", params);
  12266. ASSERT_TRUE(result.is_valid());
  12267. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  12268. }
  12269. TEST_F(StreamApiTest, GetConnectionError) {
  12270. httplib::Client cli(HOST, 9999);
  12271. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  12272. }
  12273. TEST_F(StreamApiTest, Get404) {
  12274. httplib::Client cli(HOST, PORT);
  12275. auto result = httplib::stream::Get(cli, "/nonexistent");
  12276. EXPECT_TRUE(result.is_valid());
  12277. EXPECT_EQ(404, result.status());
  12278. }
  12279. // stream::Post tests
  12280. TEST_F(StreamApiTest, PostBasic) {
  12281. httplib::Client cli(HOST, PORT);
  12282. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  12283. "application/json");
  12284. ASSERT_TRUE(result.is_valid());
  12285. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  12286. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  12287. }
  12288. TEST_F(StreamApiTest, PostWithHeaders) {
  12289. httplib::Client cli(HOST, PORT);
  12290. httplib::Headers headers{{"X-Custom", "value"}};
  12291. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  12292. "text/plain");
  12293. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  12294. }
  12295. TEST_F(StreamApiTest, PostWithParams) {
  12296. httplib::Client cli(HOST, PORT);
  12297. httplib::Params params{{"k", "v"}};
  12298. auto result =
  12299. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  12300. auto body = read_body(result);
  12301. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  12302. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  12303. }
  12304. TEST_F(StreamApiTest, PostLarge) {
  12305. httplib::Client cli(HOST, PORT);
  12306. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  12307. size_t total = 0;
  12308. while (result.next()) {
  12309. total += result.size();
  12310. }
  12311. EXPECT_EQ(100u * 1024u, total);
  12312. }
  12313. // stream::Put/Patch tests
  12314. TEST_F(StreamApiTest, PutAndPatch) {
  12315. httplib::Client cli(HOST, PORT);
  12316. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  12317. EXPECT_EQ("PUT:test", read_body(put));
  12318. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  12319. EXPECT_EQ("PATCH:test", read_body(patch));
  12320. }
  12321. // stream::Delete tests
  12322. TEST_F(StreamApiTest, Delete) {
  12323. httplib::Client cli(HOST, PORT);
  12324. auto del1 = httplib::stream::Delete(cli, "/resource");
  12325. EXPECT_EQ("Deleted", read_body(del1));
  12326. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  12327. EXPECT_EQ("Deleted:data", read_body(del2));
  12328. }
  12329. // stream::Head/Options tests
  12330. TEST_F(StreamApiTest, HeadAndOptions) {
  12331. httplib::Client cli(HOST, PORT);
  12332. auto head = httplib::stream::Head(cli, "/head-test");
  12333. EXPECT_TRUE(head.is_valid());
  12334. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  12335. auto opts = httplib::stream::Options(cli, "/options");
  12336. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  12337. }
  12338. // SSL stream::* tests
  12339. #ifdef CPPHTTPLIB_SSL_ENABLED
  12340. class SSLStreamApiTest : public ::testing::Test {
  12341. protected:
  12342. void SetUp() override {
  12343. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  12344. res.set_content("Hello SSL!", "text/plain");
  12345. });
  12346. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  12347. res.set_content(req.body, "text/plain");
  12348. });
  12349. port_ = svr_.bind_to_any_port("127.0.0.1");
  12350. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  12351. svr_.wait_until_ready();
  12352. }
  12353. void TearDown() override {
  12354. svr_.stop();
  12355. if (thread_.joinable()) thread_.join();
  12356. }
  12357. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  12358. std::thread thread_;
  12359. int port_ = 0;
  12360. };
  12361. TEST_F(SSLStreamApiTest, GetAndPost) {
  12362. httplib::SSLClient cli("127.0.0.1", port_);
  12363. cli.enable_server_certificate_verification(false);
  12364. auto get = httplib::stream::Get(cli, "/hello");
  12365. EXPECT_EQ("Hello SSL!", read_body(get));
  12366. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  12367. EXPECT_EQ("test", read_body(post));
  12368. }
  12369. #endif
  12370. // Tests for Error::Timeout and Error::ConnectionClosed error types
  12371. // These errors are set in SocketStream/SSLSocketStream and propagated through
  12372. // BodyReader
  12373. TEST(ErrorHandlingTest, StreamReadTimeout) {
  12374. // Test that read timeout during streaming is detected
  12375. // Use a large content-length response where server delays mid-stream
  12376. Server svr;
  12377. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12378. // Send a large response with delay in the middle
  12379. res.set_content_provider(
  12380. 1000, // content_length
  12381. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  12382. if (offset < 100) {
  12383. // Send first 100 bytes immediately
  12384. std::string data(100, 'A');
  12385. sink.write(data.c_str(), data.size());
  12386. return true;
  12387. }
  12388. // Then delay longer than client timeout
  12389. std::this_thread::sleep_for(std::chrono::seconds(3));
  12390. std::string data(900, 'B');
  12391. sink.write(data.c_str(), data.size());
  12392. return true;
  12393. });
  12394. });
  12395. auto port = 8091;
  12396. std::thread t([&]() { svr.listen("localhost", port); });
  12397. svr.wait_until_ready();
  12398. Client cli("localhost", port);
  12399. cli.set_read_timeout(1, 0); // 1 second timeout
  12400. auto handle = cli.open_stream("GET", "/slow-stream");
  12401. ASSERT_TRUE(handle.is_valid());
  12402. char buf[256];
  12403. ssize_t total = 0;
  12404. ssize_t n;
  12405. bool got_error = false;
  12406. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12407. total += n;
  12408. }
  12409. if (n < 0) {
  12410. got_error = true;
  12411. // Should be timeout or read error
  12412. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12413. handle.get_read_error() == Error::Read)
  12414. << "Actual error: " << to_string(handle.get_read_error());
  12415. }
  12416. // Either we got an error, or we got less data than expected
  12417. EXPECT_TRUE(got_error || total < 1000)
  12418. << "Expected timeout but got all " << total << " bytes";
  12419. svr.stop();
  12420. t.join();
  12421. }
  12422. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  12423. // Test connection closed detection via BodyReader
  12424. Server svr;
  12425. std::atomic<bool> close_now{false};
  12426. svr.Get("/will-close", [&](const Request &, Response &res) {
  12427. res.set_content_provider(
  12428. 10000, // Large content_length that we won't fully send
  12429. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12430. if (offset < 100) {
  12431. std::string data(100, 'X');
  12432. sink.write(data.c_str(), data.size());
  12433. return true;
  12434. }
  12435. // Wait for signal then abort
  12436. while (!close_now) {
  12437. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12438. }
  12439. return false; // Abort - server will close connection
  12440. });
  12441. });
  12442. auto port = 8092;
  12443. std::thread t([&]() { svr.listen("localhost", port); });
  12444. svr.wait_until_ready();
  12445. Client cli("localhost", port);
  12446. auto handle = cli.open_stream("GET", "/will-close");
  12447. ASSERT_TRUE(handle.is_valid());
  12448. char buf[256];
  12449. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12450. EXPECT_GT(n, 0) << "First read should succeed";
  12451. // Signal server to close
  12452. close_now = true;
  12453. // Keep reading until error or EOF
  12454. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12455. // Keep reading
  12456. }
  12457. // Should get an error since content_length wasn't satisfied
  12458. if (n < 0) {
  12459. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12460. handle.get_read_error() == Error::Read)
  12461. << "Actual error: " << to_string(handle.get_read_error());
  12462. }
  12463. svr.stop();
  12464. t.join();
  12465. }
  12466. #ifdef CPPHTTPLIB_SSL_ENABLED
  12467. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  12468. // Test that read timeout during SSL streaming is detected
  12469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12470. svr.Get("/slow-stream", [](const Request &, Response &res) {
  12471. res.set_content_provider(
  12472. 1000, "text/plain",
  12473. [](size_t offset, size_t /*length*/, DataSink &sink) {
  12474. if (offset < 100) {
  12475. std::string data(100, 'A');
  12476. sink.write(data.c_str(), data.size());
  12477. return true;
  12478. }
  12479. std::this_thread::sleep_for(std::chrono::seconds(3));
  12480. std::string data(900, 'B');
  12481. sink.write(data.c_str(), data.size());
  12482. return true;
  12483. });
  12484. });
  12485. auto port = 8093;
  12486. std::thread t([&]() { svr.listen("localhost", port); });
  12487. svr.wait_until_ready();
  12488. SSLClient cli("localhost", port);
  12489. cli.enable_server_certificate_verification(false);
  12490. cli.set_read_timeout(1, 0); // 1 second timeout
  12491. auto handle = cli.open_stream("GET", "/slow-stream");
  12492. ASSERT_TRUE(handle.is_valid());
  12493. char buf[256];
  12494. ssize_t total = 0;
  12495. ssize_t n;
  12496. bool got_error = false;
  12497. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12498. total += n;
  12499. }
  12500. if (n < 0) {
  12501. got_error = true;
  12502. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  12503. handle.get_read_error() == Error::Read)
  12504. << "Actual error: " << to_string(handle.get_read_error());
  12505. }
  12506. EXPECT_TRUE(got_error || total < 1000)
  12507. << "Expected timeout but got all " << total << " bytes";
  12508. svr.stop();
  12509. t.join();
  12510. }
  12511. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  12512. // Test SSL connection closed detection
  12513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12514. std::atomic<bool> close_now{false};
  12515. svr.Get("/will-close", [&](const Request &, Response &res) {
  12516. res.set_content_provider(
  12517. 10000, "text/plain",
  12518. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  12519. if (offset < 100) {
  12520. std::string data(100, 'X');
  12521. sink.write(data.c_str(), data.size());
  12522. return true;
  12523. }
  12524. while (!close_now) {
  12525. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  12526. }
  12527. return false;
  12528. });
  12529. });
  12530. auto port = 8094;
  12531. std::thread t([&]() { svr.listen("localhost", port); });
  12532. svr.wait_until_ready();
  12533. SSLClient cli("localhost", port);
  12534. cli.enable_server_certificate_verification(false);
  12535. auto handle = cli.open_stream("GET", "/will-close");
  12536. ASSERT_TRUE(handle.is_valid());
  12537. char buf[256];
  12538. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  12539. EXPECT_GT(n, 0);
  12540. // Signal server to close
  12541. close_now = true;
  12542. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12543. // Keep reading
  12544. }
  12545. if (n < 0) {
  12546. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  12547. handle.get_read_error() == Error::Read)
  12548. << "Actual error: " << to_string(handle.get_read_error());
  12549. }
  12550. svr.stop();
  12551. t.join();
  12552. }
  12553. #endif
  12554. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  12555. using namespace httplib;
  12556. // Create a test file
  12557. const char *fname = "etag_testfile.txt";
  12558. const char *content = "etag-content";
  12559. {
  12560. std::ofstream ofs(fname);
  12561. ofs << content;
  12562. ASSERT_TRUE(ofs.good());
  12563. }
  12564. Server svr;
  12565. svr.set_mount_point("/static", ".");
  12566. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12567. svr.wait_until_ready();
  12568. Client cli(HOST, PORT);
  12569. // First request: should get 200 with ETag header
  12570. auto res1 = cli.Get("/static/etag_testfile.txt");
  12571. ASSERT_TRUE(res1);
  12572. ASSERT_EQ(200, res1->status);
  12573. ASSERT_TRUE(res1->has_header("ETag"));
  12574. std::string etag = res1->get_header_value("ETag");
  12575. EXPECT_FALSE(etag.empty());
  12576. // Verify ETag format: W/"hex-hex"
  12577. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  12578. EXPECT_EQ('W', etag[0]);
  12579. EXPECT_EQ('/', etag[1]);
  12580. EXPECT_EQ('"', etag[2]);
  12581. EXPECT_EQ('"', etag.back());
  12582. // Exact match: expect 304 Not Modified
  12583. Headers h2 = {{"If-None-Match", etag}};
  12584. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  12585. ASSERT_TRUE(res2);
  12586. EXPECT_EQ(304, res2->status);
  12587. // Wildcard match: expect 304 Not Modified
  12588. Headers h3 = {{"If-None-Match", "*"}};
  12589. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  12590. ASSERT_TRUE(res3);
  12591. EXPECT_EQ(304, res3->status);
  12592. // Non-matching ETag: expect 200
  12593. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  12594. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  12595. ASSERT_TRUE(res4);
  12596. EXPECT_EQ(200, res4->status);
  12597. // Multiple ETags with one matching: expect 304
  12598. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  12599. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  12600. ASSERT_TRUE(res5);
  12601. EXPECT_EQ(304, res5->status);
  12602. svr.stop();
  12603. t.join();
  12604. std::remove(fname);
  12605. }
  12606. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  12607. using namespace httplib;
  12608. Server svr;
  12609. svr.set_mount_point("/static", ".");
  12610. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12611. svr.wait_until_ready();
  12612. Client cli(HOST, PORT);
  12613. // Send If-None-Match: * to a non-existent file
  12614. Headers h = {{"If-None-Match", "*"}};
  12615. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  12616. ASSERT_TRUE(res);
  12617. EXPECT_EQ(404, res->status);
  12618. svr.stop();
  12619. t.join();
  12620. }
  12621. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  12622. using namespace httplib;
  12623. // Create a test file
  12624. const char *fname = "etag_boundary_testfile.txt";
  12625. const char *content = "boundary-test";
  12626. {
  12627. std::ofstream ofs(fname);
  12628. ofs << content;
  12629. ASSERT_TRUE(ofs.good());
  12630. }
  12631. Server svr;
  12632. svr.set_mount_point("/static", ".");
  12633. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  12634. svr.wait_until_ready();
  12635. Client cli(HOST, PORT);
  12636. // Get the actual ETag
  12637. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  12638. ASSERT_TRUE(res1);
  12639. ASSERT_EQ(200, res1->status);
  12640. ASSERT_TRUE(res1->has_header("ETag"));
  12641. std::string etag = res1->get_header_value("ETag");
  12642. // Test 1: Very long ETag value (longer than actual ETag)
  12643. // Should NOT match and return 200 (not trigger out-of-bounds read)
  12644. Headers h1 = {{"If-None-Match", "W/"
  12645. "\"very-long-etag-value-that-is-much-longer-"
  12646. "than-the-actual-etag-value\""}};
  12647. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  12648. ASSERT_TRUE(res2);
  12649. EXPECT_EQ(200, res2->status); // Should not match
  12650. // Test 2: Long string followed by wildcard
  12651. // Should match on "*" and return 304 (without out-of-bounds read on the long
  12652. // string)
  12653. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  12654. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  12655. ASSERT_TRUE(res3);
  12656. EXPECT_EQ(304, res3->status); // Should match on "*"
  12657. // Test 3: Wildcard followed by long string
  12658. // Should match on "*" immediately and return 304
  12659. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  12660. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  12661. ASSERT_TRUE(res4);
  12662. EXPECT_EQ(304, res4->status); // Should match on "*"
  12663. // Test 4: Multiple long non-matching values
  12664. // Should NOT match and return 200 (test that all comparisons are safe)
  12665. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  12666. "W/\"second-long-non-matching-value\", "
  12667. "W/\"third-long-non-matching-value\""}};
  12668. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  12669. ASSERT_TRUE(res5);
  12670. EXPECT_EQ(200, res5->status); // Should not match
  12671. // Test 5: Single character that is not "*" (edge case)
  12672. Headers h5 = {{"If-None-Match", "X"}};
  12673. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  12674. ASSERT_TRUE(res6);
  12675. EXPECT_EQ(200, res6->status); // Should not match
  12676. svr.stop();
  12677. t.join();
  12678. std::remove(fname);
  12679. }
  12680. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  12681. using namespace httplib;
  12682. // Create a test file
  12683. const char *fname = "ims_testfile.txt";
  12684. const char *content = "if-modified-since-test";
  12685. {
  12686. std::ofstream ofs(fname);
  12687. ofs << content;
  12688. ASSERT_TRUE(ofs.good());
  12689. }
  12690. Server svr;
  12691. svr.set_mount_point("/static", ".");
  12692. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12693. svr.wait_until_ready();
  12694. Client cli(HOST, PORT);
  12695. // First request: should get 200 with Last-Modified header
  12696. auto res1 = cli.Get("/static/ims_testfile.txt");
  12697. ASSERT_TRUE(res1);
  12698. ASSERT_EQ(200, res1->status);
  12699. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12700. std::string last_modified = res1->get_header_value("Last-Modified");
  12701. EXPECT_FALSE(last_modified.empty());
  12702. // If-Modified-Since with same time: expect 304
  12703. Headers h2 = {{"If-Modified-Since", last_modified}};
  12704. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  12705. ASSERT_TRUE(res2);
  12706. EXPECT_EQ(304, res2->status);
  12707. // If-Modified-Since with future time: expect 304
  12708. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12709. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  12710. ASSERT_TRUE(res3);
  12711. EXPECT_EQ(304, res3->status);
  12712. // If-Modified-Since with past time: expect 200
  12713. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12714. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  12715. ASSERT_TRUE(res4);
  12716. EXPECT_EQ(200, res4->status);
  12717. // If-None-Match takes precedence over If-Modified-Since
  12718. // (send matching ETag with old If-Modified-Since -> should still be 304)
  12719. ASSERT_TRUE(res1->has_header("ETag"));
  12720. std::string etag = res1->get_header_value("ETag");
  12721. Headers h5 = {{"If-None-Match", etag},
  12722. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12723. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  12724. ASSERT_TRUE(res5);
  12725. EXPECT_EQ(304, res5->status);
  12726. svr.stop();
  12727. t.join();
  12728. std::remove(fname);
  12729. }
  12730. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  12731. using namespace httplib;
  12732. Server svr;
  12733. // Endpoint that returns compressible content
  12734. svr.Get("/compressible", [](const Request &, Response &res) {
  12735. // Return a large enough body to trigger compression
  12736. std::string body(1000, 'a');
  12737. res.set_content(body, "text/plain");
  12738. });
  12739. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12740. svr.wait_until_ready();
  12741. Client cli(HOST, PORT);
  12742. // Request with gzip support: should get Vary header when compressed
  12743. cli.set_compress(true);
  12744. auto res1 = cli.Get("/compressible");
  12745. ASSERT_TRUE(res1);
  12746. EXPECT_EQ(200, res1->status);
  12747. // If Content-Encoding is set, Vary should also be set
  12748. if (res1->has_header("Content-Encoding")) {
  12749. EXPECT_TRUE(res1->has_header("Vary"));
  12750. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  12751. }
  12752. // Request without Accept-Encoding header: should not have compression
  12753. Headers h_no_compress;
  12754. auto res2 = cli.Get("/compressible", h_no_compress);
  12755. ASSERT_TRUE(res2);
  12756. EXPECT_EQ(200, res2->status);
  12757. // Verify Vary header is present when compression is applied
  12758. // (the exact behavior depends on server configuration)
  12759. svr.stop();
  12760. t.join();
  12761. }
  12762. TEST(ETagTest, IfRangeWithETag) {
  12763. using namespace httplib;
  12764. // Create a test file with known content
  12765. const char *fname = "if_range_testfile.txt";
  12766. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  12767. {
  12768. std::ofstream ofs(fname);
  12769. ofs << content;
  12770. ASSERT_TRUE(ofs.good());
  12771. }
  12772. Server svr;
  12773. svr.set_mount_point("/static", ".");
  12774. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12775. svr.wait_until_ready();
  12776. Client cli(HOST, PORT);
  12777. // First request: get ETag
  12778. auto res1 = cli.Get("/static/if_range_testfile.txt");
  12779. ASSERT_TRUE(res1);
  12780. ASSERT_EQ(200, res1->status);
  12781. ASSERT_TRUE(res1->has_header("ETag"));
  12782. std::string etag = res1->get_header_value("ETag");
  12783. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  12784. // Since our server generates weak ETags (W/"..."), If-Range with our
  12785. // ETag should NOT result in partial content - it should return full content.
  12786. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  12787. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  12788. ASSERT_TRUE(res2);
  12789. // Weak ETag in If-Range -> full content (200), not partial (206)
  12790. EXPECT_EQ(200, res2->status);
  12791. EXPECT_EQ(content, res2->body);
  12792. EXPECT_FALSE(res2->has_header("Content-Range"));
  12793. // Range request with non-matching If-Range (ETag): should get 200 (full
  12794. // content)
  12795. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  12796. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  12797. ASSERT_TRUE(res3);
  12798. EXPECT_EQ(200, res3->status);
  12799. EXPECT_EQ(content, res3->body);
  12800. EXPECT_FALSE(res3->has_header("Content-Range"));
  12801. // Range request with strong ETag (hypothetical - our server doesn't generate
  12802. // strong ETags, but if client sends a strong ETag that doesn't match, it
  12803. // should return full content)
  12804. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  12805. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  12806. ASSERT_TRUE(res4);
  12807. EXPECT_EQ(200, res4->status);
  12808. EXPECT_EQ(content, res4->body);
  12809. EXPECT_FALSE(res4->has_header("Content-Range"));
  12810. svr.stop();
  12811. t.join();
  12812. std::remove(fname);
  12813. }
  12814. TEST(ETagTest, IfRangeWithDate) {
  12815. using namespace httplib;
  12816. // Create a test file
  12817. const char *fname = "if_range_date_testfile.txt";
  12818. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  12819. {
  12820. std::ofstream ofs(fname);
  12821. ofs << content;
  12822. ASSERT_TRUE(ofs.good());
  12823. }
  12824. Server svr;
  12825. svr.set_mount_point("/static", ".");
  12826. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12827. svr.wait_until_ready();
  12828. Client cli(HOST, PORT);
  12829. // First request: get Last-Modified
  12830. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  12831. ASSERT_TRUE(res1);
  12832. ASSERT_EQ(200, res1->status);
  12833. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12834. std::string last_modified = res1->get_header_value("Last-Modified");
  12835. // Range request with matching If-Range (date): should get 206
  12836. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  12837. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  12838. ASSERT_TRUE(res2);
  12839. EXPECT_EQ(206, res2->status);
  12840. EXPECT_EQ("FGHIJ", res2->body);
  12841. // Range request with old If-Range date: should get 200 (full content)
  12842. Headers h3 = {{"Range", "bytes=5-9"},
  12843. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  12844. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  12845. ASSERT_TRUE(res3);
  12846. EXPECT_EQ(200, res3->status);
  12847. EXPECT_EQ(content, res3->body);
  12848. // Range request with future If-Range date: should get 206
  12849. Headers h4 = {{"Range", "bytes=0-4"},
  12850. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  12851. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  12852. ASSERT_TRUE(res4);
  12853. EXPECT_EQ(206, res4->status);
  12854. EXPECT_EQ("ABCDE", res4->body);
  12855. svr.stop();
  12856. t.join();
  12857. std::remove(fname);
  12858. }
  12859. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  12860. using namespace httplib;
  12861. const char *fname = "etag_malformed.txt";
  12862. const char *content = "malformed-etag";
  12863. {
  12864. std::ofstream ofs(fname);
  12865. ofs << content;
  12866. ASSERT_TRUE(ofs.good());
  12867. }
  12868. Server svr;
  12869. svr.set_mount_point("/static", ".");
  12870. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12871. svr.wait_until_ready();
  12872. Client cli(HOST, PORT);
  12873. // baseline: should get 200 and an ETag
  12874. auto res1 = cli.Get("/static/etag_malformed.txt");
  12875. ASSERT_TRUE(res1);
  12876. ASSERT_EQ(200, res1->status);
  12877. ASSERT_TRUE(res1->has_header("ETag"));
  12878. // Malformed ETag value (missing quotes) should be treated as non-matching
  12879. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  12880. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  12881. ASSERT_TRUE(res_bad);
  12882. EXPECT_EQ(200, res_bad->status);
  12883. // Whitespace-only header value should be considered invalid / non-matching
  12884. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  12885. "Host: localhost\r\n"
  12886. "If-None-Match: \r\n"
  12887. "Connection: close\r\n"
  12888. "\r\n";
  12889. std::string out;
  12890. ASSERT_TRUE(send_request(5, raw_req, &out));
  12891. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  12892. svr.stop();
  12893. t.join();
  12894. std::remove(fname);
  12895. }
  12896. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  12897. using namespace httplib;
  12898. const char *fname = "ims_invalid_format.txt";
  12899. const char *content = "ims-bad-format";
  12900. {
  12901. std::ofstream ofs(fname);
  12902. ofs << content;
  12903. ASSERT_TRUE(ofs.good());
  12904. }
  12905. Server svr;
  12906. svr.set_mount_point("/static", ".");
  12907. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12908. svr.wait_until_ready();
  12909. Client cli(HOST, PORT);
  12910. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  12911. ASSERT_TRUE(res1);
  12912. ASSERT_EQ(200, res1->status);
  12913. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12914. // If-Modified-Since with invalid format should not result in 304
  12915. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  12916. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  12917. ASSERT_TRUE(res_bad);
  12918. EXPECT_EQ(200, res_bad->status);
  12919. // If-Range with invalid date format should be treated as mismatch -> full
  12920. // content (200)
  12921. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  12922. {"If-Range", "invalid-date"}};
  12923. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  12924. ASSERT_TRUE(res_ifrange);
  12925. EXPECT_EQ(200, res_ifrange->status);
  12926. svr.stop();
  12927. t.join();
  12928. std::remove(fname);
  12929. }
  12930. TEST(ETagTest, IfRangeWithMalformedETag) {
  12931. using namespace httplib;
  12932. const char *fname = "ifrange_malformed.txt";
  12933. const std::string content = "0123456789";
  12934. {
  12935. std::ofstream ofs(fname);
  12936. ofs << content;
  12937. ASSERT_TRUE(ofs.good());
  12938. }
  12939. Server svr;
  12940. svr.set_mount_point("/static", ".");
  12941. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12942. svr.wait_until_ready();
  12943. Client cli(HOST, PORT);
  12944. // First request: get ETag
  12945. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  12946. ASSERT_TRUE(res1);
  12947. ASSERT_EQ(200, res1->status);
  12948. ASSERT_TRUE(res1->has_header("ETag"));
  12949. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  12950. // full content (200)
  12951. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  12952. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  12953. ASSERT_TRUE(res2);
  12954. EXPECT_EQ(200, res2->status);
  12955. EXPECT_EQ(content, res2->body);
  12956. svr.stop();
  12957. t.join();
  12958. std::remove(fname);
  12959. }
  12960. TEST(ETagTest, ExtremeLargeDateValues) {
  12961. using namespace httplib;
  12962. const char *fname = "ims_extreme_date.txt";
  12963. const char *content = "ims-extreme-date";
  12964. {
  12965. std::ofstream ofs(fname);
  12966. ofs << content;
  12967. ASSERT_TRUE(ofs.good());
  12968. }
  12969. Server svr;
  12970. svr.set_mount_point("/static", ".");
  12971. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12972. svr.wait_until_ready();
  12973. Client cli(HOST, PORT);
  12974. auto res1 = cli.Get(std::string("/static/") + fname);
  12975. ASSERT_TRUE(res1);
  12976. ASSERT_EQ(200, res1->status);
  12977. ASSERT_TRUE(res1->has_header("Last-Modified"));
  12978. // Extremely large year that may overflow date parsing routines.
  12979. Headers h_large_date = {
  12980. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12981. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  12982. ASSERT_TRUE(res_bad);
  12983. // Expect server to treat this as invalid/mismatch and return full content
  12984. EXPECT_EQ(200, res_bad->status);
  12985. // If-Range with extremely large date should be treated as mismatch -> full
  12986. // content (200)
  12987. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  12988. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  12989. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  12990. ASSERT_TRUE(res_ifrange);
  12991. EXPECT_EQ(200, res_ifrange->status);
  12992. svr.stop();
  12993. t.join();
  12994. std::remove(fname);
  12995. }
  12996. TEST(ETagTest, NegativeFileModificationTime) {
  12997. using namespace httplib;
  12998. const char *fname = "ims_negative_mtime.txt";
  12999. const std::string content = "negative-mtime";
  13000. {
  13001. std::ofstream ofs(fname);
  13002. ofs << content;
  13003. ASSERT_TRUE(ofs.good());
  13004. }
  13005. // Try to set file mtime to a negative value. This may fail on some
  13006. // platforms/filesystems; if it fails, the test will still verify server
  13007. // behaves safely by performing a regular conditional request.
  13008. #if defined(__APPLE__) || defined(__linux__)
  13009. bool set_negative = false;
  13010. do {
  13011. struct timeval times[2];
  13012. // access time: now
  13013. times[0].tv_sec = time(nullptr);
  13014. times[0].tv_usec = 0;
  13015. // modification time: negative (e.g., -1)
  13016. times[1].tv_sec = -1;
  13017. times[1].tv_usec = 0;
  13018. if (utimes(fname, times) == 0) { set_negative = true; }
  13019. } while (0);
  13020. #else
  13021. bool set_negative = false;
  13022. #endif
  13023. Server svr;
  13024. svr.set_mount_point("/static", ".");
  13025. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13026. svr.wait_until_ready();
  13027. Client cli(HOST, PORT);
  13028. auto res1 = cli.Get(std::string("/static/") + fname);
  13029. ASSERT_TRUE(res1);
  13030. ASSERT_EQ(200, res1->status);
  13031. bool has_last_modified = res1->has_header("Last-Modified");
  13032. std::string last_modified;
  13033. if (has_last_modified) {
  13034. last_modified = res1->get_header_value("Last-Modified");
  13035. }
  13036. if (set_negative) {
  13037. // If we successfully set a negative mtime, ensure server returns a
  13038. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  13039. // with an old date and ensure server handles it without crash.
  13040. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  13041. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  13042. ASSERT_TRUE(res2);
  13043. // Behavior may vary; at minimum ensure server responds (200 or 304).
  13044. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  13045. } else {
  13046. // Could not set negative mtime on this platform; fall back to verifying
  13047. // that normal invalid/malformed dates are treated safely (non-304).
  13048. Headers h_bad_date = {
  13049. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  13050. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  13051. ASSERT_TRUE(res_bad);
  13052. EXPECT_EQ(200, res_bad->status);
  13053. }
  13054. svr.stop();
  13055. t.join();
  13056. std::remove(fname);
  13057. }
  13058. //==============================================================================
  13059. // SSE Parsing Tests
  13060. //==============================================================================
  13061. class SSEParsingTest : public ::testing::Test {
  13062. protected:
  13063. // Test helper that mimics SSE parsing behavior
  13064. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  13065. int &retry_ms) {
  13066. // Blank line signals end of event
  13067. if (line.empty() || line == "\r") { return true; }
  13068. // Lines starting with ':' are comments (ignored)
  13069. if (!line.empty() && line[0] == ':') { return false; }
  13070. // Find the colon separator
  13071. auto colon_pos = line.find(':');
  13072. if (colon_pos == std::string::npos) {
  13073. // Line with no colon is treated as field name with empty value
  13074. return false;
  13075. }
  13076. std::string field = line.substr(0, colon_pos);
  13077. std::string value;
  13078. // Value starts after colon, skip optional single space
  13079. if (colon_pos + 1 < line.size()) {
  13080. size_t value_start = colon_pos + 1;
  13081. if (line[value_start] == ' ') { value_start++; }
  13082. value = line.substr(value_start);
  13083. // Remove trailing \r if present
  13084. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  13085. }
  13086. // Handle known fields
  13087. if (field == "event") {
  13088. msg.event = value;
  13089. } else if (field == "data") {
  13090. // Multiple data lines are concatenated with newlines
  13091. if (!msg.data.empty()) { msg.data += "\n"; }
  13092. msg.data += value;
  13093. } else if (field == "id") {
  13094. // Empty id is valid (clears the last event ID)
  13095. msg.id = value;
  13096. } else if (field == "retry") {
  13097. // Parse retry interval in milliseconds
  13098. {
  13099. int v = 0;
  13100. auto res =
  13101. detail::from_chars(value.data(), value.data() + value.size(), v);
  13102. if (res.ec == std::errc{}) { retry_ms = v; }
  13103. }
  13104. }
  13105. // Unknown fields are ignored per SSE spec
  13106. return false;
  13107. }
  13108. };
  13109. // Test: Single-line data
  13110. TEST_F(SSEParsingTest, SingleLineData) {
  13111. sse::SSEMessage msg;
  13112. int retry_ms = 3000;
  13113. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  13114. EXPECT_EQ(msg.data, "hello");
  13115. EXPECT_EQ(msg.event, "message");
  13116. // Blank line ends event
  13117. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13118. }
  13119. // Test: Multi-line data
  13120. TEST_F(SSEParsingTest, MultiLineData) {
  13121. sse::SSEMessage msg;
  13122. int retry_ms = 3000;
  13123. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  13124. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  13125. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  13126. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  13127. }
  13128. // Test: Custom event types
  13129. TEST_F(SSEParsingTest, CustomEventType) {
  13130. sse::SSEMessage msg;
  13131. int retry_ms = 3000;
  13132. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  13133. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  13134. EXPECT_EQ(msg.event, "update");
  13135. EXPECT_EQ(msg.data, "payload");
  13136. }
  13137. // Test: Event ID handling
  13138. TEST_F(SSEParsingTest, EventIdHandling) {
  13139. sse::SSEMessage msg;
  13140. int retry_ms = 3000;
  13141. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  13142. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  13143. EXPECT_EQ(msg.id, "12345");
  13144. }
  13145. // Test: Empty event ID (clears last event ID)
  13146. TEST_F(SSEParsingTest, EmptyEventId) {
  13147. sse::SSEMessage msg;
  13148. msg.id = "previous";
  13149. int retry_ms = 3000;
  13150. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  13151. EXPECT_EQ(msg.id, "");
  13152. }
  13153. // Test: Retry field parsing
  13154. TEST_F(SSEParsingTest, RetryFieldParsing) {
  13155. sse::SSEMessage msg;
  13156. int retry_ms = 3000;
  13157. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  13158. EXPECT_EQ(retry_ms, 5000);
  13159. }
  13160. // Test: Invalid retry value
  13161. TEST_F(SSEParsingTest, InvalidRetryValue) {
  13162. sse::SSEMessage msg;
  13163. int retry_ms = 3000;
  13164. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  13165. EXPECT_EQ(retry_ms, 3000); // Unchanged
  13166. }
  13167. // Test: Comments (lines starting with :)
  13168. TEST_F(SSEParsingTest, CommentsIgnored) {
  13169. sse::SSEMessage msg;
  13170. int retry_ms = 3000;
  13171. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  13172. EXPECT_EQ(msg.data, "");
  13173. EXPECT_EQ(msg.event, "message");
  13174. }
  13175. // Test: Colon in value
  13176. TEST_F(SSEParsingTest, ColonInValue) {
  13177. sse::SSEMessage msg;
  13178. int retry_ms = 3000;
  13179. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  13180. EXPECT_EQ(msg.data, "hello:world:test");
  13181. }
  13182. // Test: Line with no colon (field name only)
  13183. TEST_F(SSEParsingTest, FieldNameOnly) {
  13184. sse::SSEMessage msg;
  13185. int retry_ms = 3000;
  13186. // According to SSE spec, this is treated as field name with empty value
  13187. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  13188. // Since we don't recognize "data" without colon, data should be empty
  13189. EXPECT_EQ(msg.data, "");
  13190. }
  13191. // Test: Trailing \r handling
  13192. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  13193. sse::SSEMessage msg;
  13194. int retry_ms = 3000;
  13195. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  13196. EXPECT_EQ(msg.data, "hello");
  13197. }
  13198. // Test: Unknown fields ignored
  13199. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  13200. sse::SSEMessage msg;
  13201. int retry_ms = 3000;
  13202. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  13203. EXPECT_EQ(msg.data, "");
  13204. EXPECT_EQ(msg.event, "message");
  13205. }
  13206. // Test: Space after colon is optional
  13207. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  13208. sse::SSEMessage msg1, msg2;
  13209. int retry_ms = 3000;
  13210. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  13211. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  13212. EXPECT_EQ(msg1.data, "hello");
  13213. EXPECT_EQ(msg2.data, "hello");
  13214. }
  13215. // Test: SSEMessage clear
  13216. TEST_F(SSEParsingTest, MessageClear) {
  13217. sse::SSEMessage msg;
  13218. msg.event = "custom";
  13219. msg.data = "some data";
  13220. msg.id = "123";
  13221. msg.clear();
  13222. EXPECT_EQ(msg.event, "message");
  13223. EXPECT_EQ(msg.data, "");
  13224. EXPECT_EQ(msg.id, "");
  13225. }
  13226. // Test: Complete event parsing
  13227. TEST_F(SSEParsingTest, CompleteEventParsing) {
  13228. sse::SSEMessage msg;
  13229. int retry_ms = 3000;
  13230. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  13231. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  13232. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  13233. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  13234. // Blank line ends event
  13235. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  13236. EXPECT_EQ(msg.event, "notification");
  13237. EXPECT_EQ(msg.id, "evt-42");
  13238. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  13239. EXPECT_EQ(retry_ms, 1000);
  13240. }
  13241. //==============================================================================
  13242. // Integration Tests with Server
  13243. //==============================================================================
  13244. class SSEIntegrationTest : public ::testing::Test {
  13245. protected:
  13246. void SetUp() override {
  13247. stop_server_.store(false);
  13248. events_.clear();
  13249. server_ = httplib::detail::make_unique<Server>();
  13250. setup_server();
  13251. start_server();
  13252. }
  13253. void TearDown() override {
  13254. stop_server_.store(true);
  13255. event_cv_.notify_all();
  13256. server_->stop();
  13257. if (server_thread_.joinable()) { server_thread_.join(); }
  13258. }
  13259. void setup_server() {
  13260. // Simple SSE endpoint
  13261. server_->Get("/events", [this](const Request &req, Response &res) {
  13262. auto last_id = req.get_header_value("Last-Event-ID");
  13263. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  13264. res.set_chunked_content_provider(
  13265. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  13266. std::unique_lock<std::mutex> lock(event_mutex_);
  13267. if (event_cv_.wait_for(
  13268. lock, std::chrono::milliseconds(200), [this] {
  13269. return !events_.empty() || stop_server_.load();
  13270. })) {
  13271. if (stop_server_.load()) { return false; }
  13272. if (!events_.empty()) {
  13273. std::string event = events_.front();
  13274. events_.erase(events_.begin());
  13275. sink.write(event.data(), event.size());
  13276. return true;
  13277. }
  13278. }
  13279. return !stop_server_.load();
  13280. });
  13281. });
  13282. // Endpoint that returns error
  13283. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  13284. res.status = 500;
  13285. res.set_content("Internal Server Error", "text/plain");
  13286. });
  13287. // Endpoint for custom event types
  13288. server_->Get("/custom-events", [](const Request &, Response &res) {
  13289. res.set_chunked_content_provider(
  13290. "text/event-stream", [](size_t offset, DataSink &sink) {
  13291. if (offset == 0) {
  13292. std::string event = "event: update\ndata: updated\n\n"
  13293. "event: delete\ndata: deleted\n\n";
  13294. sink.write(event.data(), event.size());
  13295. }
  13296. return false; // End stream after sending
  13297. });
  13298. });
  13299. }
  13300. void start_server() {
  13301. port_ = server_->bind_to_any_port(HOST);
  13302. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  13303. // Wait for server to start
  13304. while (!server_->is_running()) {
  13305. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  13306. }
  13307. }
  13308. int get_port() const { return port_; }
  13309. void send_event(const std::string &event) {
  13310. std::lock_guard<std::mutex> lock(event_mutex_);
  13311. events_.push_back(event);
  13312. event_cv_.notify_all();
  13313. }
  13314. std::unique_ptr<Server> server_;
  13315. std::thread server_thread_;
  13316. std::mutex event_mutex_;
  13317. std::condition_variable event_cv_;
  13318. std::vector<std::string> events_;
  13319. std::atomic<bool> stop_server_{false};
  13320. std::string last_received_event_id_;
  13321. int port_ = 0;
  13322. };
  13323. // Test: Successful connection and on_open callback
  13324. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  13325. // Add a simple endpoint that sends one event and closes
  13326. server_->Get("/simple-event", [](const Request &, Response &res) {
  13327. res.set_chunked_content_provider(
  13328. "text/event-stream", [](size_t offset, DataSink &sink) {
  13329. if (offset == 0) {
  13330. std::string event = "data: hello\n\n";
  13331. sink.write(event.data(), event.size());
  13332. }
  13333. return false; // Close stream after sending
  13334. });
  13335. });
  13336. Client client("localhost", get_port());
  13337. sse::SSEClient sse(client, "/simple-event");
  13338. std::atomic<bool> open_called{false};
  13339. std::atomic<bool> message_received{false};
  13340. sse.on_open([&open_called]() { open_called.store(true); });
  13341. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  13342. if (msg.data == "hello") { message_received.store(true); }
  13343. });
  13344. sse.set_reconnect_interval(100);
  13345. sse.set_max_reconnect_attempts(1);
  13346. // Start async
  13347. sse.start_async();
  13348. // Wait for message to be processed
  13349. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13350. sse.stop();
  13351. EXPECT_TRUE(open_called.load());
  13352. EXPECT_TRUE(message_received.load());
  13353. }
  13354. // Test: on_message callback
  13355. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  13356. // Endpoint that sends multiple events then closes
  13357. server_->Get("/multi-event", [](const Request &, Response &res) {
  13358. res.set_chunked_content_provider(
  13359. "text/event-stream", [](size_t offset, DataSink &sink) {
  13360. if (offset == 0) {
  13361. std::string events = "data: message1\n\ndata: message2\n\n";
  13362. sink.write(events.data(), events.size());
  13363. }
  13364. return false;
  13365. });
  13366. });
  13367. Client client("localhost", get_port());
  13368. sse::SSEClient sse(client, "/multi-event");
  13369. std::vector<std::string> received_messages;
  13370. std::mutex messages_mutex;
  13371. sse.on_message([&](const sse::SSEMessage &msg) {
  13372. std::lock_guard<std::mutex> lock(messages_mutex);
  13373. received_messages.push_back(msg.data);
  13374. });
  13375. sse.set_reconnect_interval(100);
  13376. sse.set_max_reconnect_attempts(1);
  13377. sse.start_async();
  13378. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13379. sse.stop();
  13380. std::lock_guard<std::mutex> lock(messages_mutex);
  13381. EXPECT_GE(received_messages.size(), 2u);
  13382. if (received_messages.size() >= 2) {
  13383. EXPECT_EQ(received_messages[0], "message1");
  13384. EXPECT_EQ(received_messages[1], "message2");
  13385. }
  13386. }
  13387. // Test: on_event for specific types
  13388. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  13389. Client client("localhost", get_port());
  13390. sse::SSEClient sse(client, "/custom-events");
  13391. std::atomic<bool> update_received{false};
  13392. std::atomic<bool> delete_received{false};
  13393. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  13394. if (msg.data == "updated") { update_received.store(true); }
  13395. });
  13396. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  13397. if (msg.data == "deleted") { delete_received.store(true); }
  13398. });
  13399. sse.set_max_reconnect_attempts(1);
  13400. sse.start_async();
  13401. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  13402. sse.stop();
  13403. EXPECT_TRUE(update_received.load());
  13404. EXPECT_TRUE(delete_received.load());
  13405. }
  13406. // Test: on_error callback on connection failure
  13407. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  13408. // Connect to a non-existent port
  13409. Client client("localhost", 59999);
  13410. sse::SSEClient sse(client, "/events");
  13411. std::atomic<bool> error_called{false};
  13412. Error received_error = Error::Success;
  13413. sse.on_error([&](Error err) {
  13414. error_called.store(true);
  13415. received_error = err;
  13416. });
  13417. sse.set_reconnect_interval(50);
  13418. sse.set_max_reconnect_attempts(1);
  13419. sse.start_async();
  13420. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13421. sse.stop();
  13422. EXPECT_TRUE(error_called.load());
  13423. EXPECT_NE(received_error, Error::Success);
  13424. }
  13425. // Test: Last-Event-ID header sent on reconnect
  13426. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  13427. // Endpoint that sends event with ID
  13428. server_->Get("/event-with-id", [](const Request &, Response &res) {
  13429. res.set_chunked_content_provider(
  13430. "text/event-stream", [](size_t offset, DataSink &sink) {
  13431. if (offset == 0) {
  13432. std::string event = "id: evt-123\ndata: test\n\n";
  13433. sink.write(event.data(), event.size());
  13434. }
  13435. return false;
  13436. });
  13437. });
  13438. Client client("localhost", get_port());
  13439. sse::SSEClient sse(client, "/event-with-id");
  13440. std::atomic<bool> id_received{false};
  13441. sse.on_message([&](const sse::SSEMessage &msg) {
  13442. if (!msg.id.empty()) { id_received.store(true); }
  13443. });
  13444. sse.set_reconnect_interval(100);
  13445. sse.set_max_reconnect_attempts(1);
  13446. sse.start_async();
  13447. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13448. sse.stop();
  13449. EXPECT_TRUE(id_received.load());
  13450. EXPECT_EQ(sse.last_event_id(), "evt-123");
  13451. }
  13452. // Test: Manual stop
  13453. TEST_F(SSEIntegrationTest, ManualStop) {
  13454. // Endpoint that sends one event and stays open briefly
  13455. std::atomic<bool> handler_running{true};
  13456. server_->Get("/stay-open", [&handler_running](const Request &,
  13457. Response &res) {
  13458. res.set_chunked_content_provider(
  13459. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  13460. if (offset == 0) {
  13461. std::string event = "data: connected\n\n";
  13462. sink.write(event.data(), event.size());
  13463. }
  13464. // Keep connection open while handler_running is true
  13465. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  13466. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13467. }
  13468. return false;
  13469. });
  13470. });
  13471. Client client("localhost", get_port());
  13472. sse::SSEClient sse(client, "/stay-open");
  13473. std::atomic<bool> connected{false};
  13474. sse.on_open([&connected]() { connected.store(true); });
  13475. sse.set_reconnect_interval(100);
  13476. sse.set_max_reconnect_attempts(1);
  13477. sse.start_async();
  13478. // Wait for connection to establish
  13479. for (int i = 0; i < 20 && !connected.load(); ++i) {
  13480. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  13481. }
  13482. EXPECT_TRUE(connected.load());
  13483. EXPECT_TRUE(sse.is_connected());
  13484. // Signal handler to stop
  13485. handler_running.store(false);
  13486. // Stop SSE client
  13487. sse.stop();
  13488. EXPECT_FALSE(sse.is_connected());
  13489. }
  13490. // Test: SSEClient with custom headers
  13491. TEST_F(SSEIntegrationTest, CustomHeaders) {
  13492. // Setup a server endpoint that checks for custom header
  13493. std::atomic<bool> header_received{false};
  13494. server_->Get("/header-check", [&](const Request &req, Response &res) {
  13495. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  13496. header_received.store(true);
  13497. }
  13498. res.set_chunked_content_provider("text/event-stream",
  13499. [](size_t, DataSink &) { return false; });
  13500. });
  13501. Client client("localhost", get_port());
  13502. Headers headers = {{"X-Custom-Header", "custom-value"}};
  13503. sse::SSEClient sse(client, "/header-check", headers);
  13504. sse.set_max_reconnect_attempts(1);
  13505. sse.start_async();
  13506. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13507. sse.stop();
  13508. EXPECT_TRUE(header_received.load());
  13509. }
  13510. // Test: Reconnect interval configuration
  13511. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  13512. Client client("localhost", get_port());
  13513. sse::SSEClient sse(client, "/events");
  13514. auto &result = sse.set_reconnect_interval(500);
  13515. // Builder pattern should return reference to self
  13516. EXPECT_EQ(&result, &sse);
  13517. }
  13518. // Test: Max reconnect attempts
  13519. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  13520. // Connect to non-existent port to force reconnects
  13521. Client client("localhost", 59998);
  13522. sse::SSEClient sse(client, "/events");
  13523. std::atomic<int> error_count{0};
  13524. sse.on_error([&](Error) { error_count.fetch_add(1); });
  13525. sse.set_reconnect_interval(50);
  13526. sse.set_max_reconnect_attempts(2);
  13527. auto start = std::chrono::steady_clock::now();
  13528. sse.start(); // Blocking call
  13529. auto end = std::chrono::steady_clock::now();
  13530. // Should have stopped after 2 failed attempts
  13531. EXPECT_GE(error_count.load(), 2);
  13532. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  13533. auto duration =
  13534. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  13535. #ifdef _WIN32
  13536. // Windows is much slower for socket connection failures
  13537. EXPECT_LT(duration.count(), 7000);
  13538. #else
  13539. EXPECT_LT(duration.count(), 1000);
  13540. #endif
  13541. }
  13542. // Test: Multi-line data in integration
  13543. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  13544. // Endpoint with multi-line data
  13545. server_->Get("/multiline-data", [](const Request &, Response &res) {
  13546. res.set_chunked_content_provider(
  13547. "text/event-stream", [](size_t offset, DataSink &sink) {
  13548. if (offset == 0) {
  13549. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  13550. sink.write(event.data(), event.size());
  13551. }
  13552. return false;
  13553. });
  13554. });
  13555. Client client("localhost", get_port());
  13556. sse::SSEClient sse(client, "/multiline-data");
  13557. std::string received_data;
  13558. std::mutex data_mutex;
  13559. sse.on_message([&](const sse::SSEMessage &msg) {
  13560. std::lock_guard<std::mutex> lock(data_mutex);
  13561. received_data = msg.data;
  13562. });
  13563. sse.set_reconnect_interval(100);
  13564. sse.set_max_reconnect_attempts(1);
  13565. sse.start_async();
  13566. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13567. sse.stop();
  13568. std::lock_guard<std::mutex> lock(data_mutex);
  13569. EXPECT_EQ(received_data, "line1\nline2\nline3");
  13570. }
  13571. // Test: Auto-reconnect after server disconnection
  13572. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  13573. std::atomic<int> connection_count{0};
  13574. std::atomic<int> message_count{0};
  13575. // Endpoint that sends one event and closes, forcing reconnect
  13576. server_->Get("/reconnect-test",
  13577. [&connection_count](const Request &, Response &res) {
  13578. connection_count.fetch_add(1);
  13579. res.set_chunked_content_provider(
  13580. "text/event-stream", [](size_t offset, DataSink &sink) {
  13581. if (offset == 0) {
  13582. std::string event = "data: hello\n\n";
  13583. sink.write(event.data(), event.size());
  13584. }
  13585. return false; // Close connection after sending
  13586. });
  13587. });
  13588. Client client("localhost", get_port());
  13589. sse::SSEClient sse(client, "/reconnect-test");
  13590. sse.on_message([&message_count](const sse::SSEMessage &) {
  13591. message_count.fetch_add(1);
  13592. });
  13593. sse.set_reconnect_interval(100);
  13594. sse.set_max_reconnect_attempts(3);
  13595. sse.start_async();
  13596. // Wait long enough for multiple reconnects
  13597. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13598. sse.stop();
  13599. // Should have connected multiple times (initial + reconnects)
  13600. EXPECT_GE(connection_count.load(), 2);
  13601. // Should have received messages from multiple connections
  13602. EXPECT_GE(message_count.load(), 2);
  13603. }
  13604. // Test: Last-Event-ID sent on reconnect
  13605. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  13606. std::atomic<int> connection_count{0};
  13607. std::vector<std::string> received_last_event_ids;
  13608. std::mutex id_mutex;
  13609. // Endpoint that checks Last-Event-ID header and sends event with ID
  13610. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  13611. int conn = connection_count.fetch_add(1);
  13612. // Capture the Last-Event-ID header from each connection
  13613. {
  13614. std::lock_guard<std::mutex> lock(id_mutex);
  13615. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  13616. }
  13617. res.set_chunked_content_provider(
  13618. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  13619. if (offset == 0) {
  13620. std::string event =
  13621. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  13622. sink.write(event.data(), event.size());
  13623. }
  13624. return false;
  13625. });
  13626. });
  13627. Client client("localhost", get_port());
  13628. sse::SSEClient sse(client, "/reconnect-with-id");
  13629. sse.set_reconnect_interval(100);
  13630. sse.set_max_reconnect_attempts(3);
  13631. sse.start_async();
  13632. // Wait for at least 2 connections
  13633. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13634. sse.stop();
  13635. // Verify behavior
  13636. std::lock_guard<std::mutex> lock(id_mutex);
  13637. EXPECT_GE(received_last_event_ids.size(), 2u);
  13638. // First connection should have no Last-Event-ID
  13639. if (!received_last_event_ids.empty()) {
  13640. EXPECT_EQ(received_last_event_ids[0], "");
  13641. }
  13642. // Second connection should have Last-Event-ID from first connection
  13643. if (received_last_event_ids.size() >= 2) {
  13644. EXPECT_EQ(received_last_event_ids[1], "event-0");
  13645. }
  13646. }
  13647. // Test: set_headers updates headers used on reconnect
  13648. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  13649. std::vector<std::string> received_tokens;
  13650. std::mutex token_mutex;
  13651. // Endpoint that captures Authorization header
  13652. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  13653. {
  13654. std::lock_guard<std::mutex> lock(token_mutex);
  13655. received_tokens.push_back(req.get_header_value("Authorization"));
  13656. }
  13657. res.set_chunked_content_provider(
  13658. "text/event-stream", [](size_t offset, DataSink &sink) {
  13659. if (offset == 0) {
  13660. std::string event = "data: hello\n\n";
  13661. sink.write(event.data(), event.size());
  13662. }
  13663. return false; // Close connection to trigger reconnect
  13664. });
  13665. });
  13666. Client client("localhost", get_port());
  13667. Headers headers = {{"Authorization", "Bearer old-token"}};
  13668. sse::SSEClient sse(client, "/auth-check", headers);
  13669. // Update headers on each successful connection
  13670. sse.on_open(
  13671. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  13672. sse.set_reconnect_interval(100);
  13673. sse.set_max_reconnect_attempts(3);
  13674. sse.start_async();
  13675. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13676. sse.stop();
  13677. std::lock_guard<std::mutex> lock(token_mutex);
  13678. ASSERT_GE(received_tokens.size(), 2u);
  13679. // First connection uses original header
  13680. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  13681. // Second connection uses updated header from set_headers
  13682. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  13683. }
  13684. // Test: 401 allows reconnection (so on_error can refresh headers)
  13685. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  13686. std::atomic<int> connection_count{0};
  13687. // Endpoint: returns 401 on first attempt, 200 on second
  13688. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  13689. int conn = connection_count.fetch_add(1);
  13690. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  13691. res.status = StatusCode::Unauthorized_401;
  13692. res.set_content("Unauthorized", "text/plain");
  13693. return;
  13694. }
  13695. res.set_chunked_content_provider(
  13696. "text/event-stream", [](size_t offset, DataSink &sink) {
  13697. if (offset == 0) {
  13698. std::string event = "data: authenticated\n\n";
  13699. sink.write(event.data(), event.size());
  13700. }
  13701. return false;
  13702. });
  13703. });
  13704. Client client("localhost", get_port());
  13705. Headers headers = {{"Authorization", "Bearer expired"}};
  13706. sse::SSEClient sse(client, "/auth-retry", headers);
  13707. std::atomic<bool> message_received{false};
  13708. // Refresh token on error
  13709. sse.on_error(
  13710. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  13711. sse.on_message([&](const sse::SSEMessage &msg) {
  13712. if (msg.data == "authenticated") { message_received.store(true); }
  13713. });
  13714. sse.set_reconnect_interval(100);
  13715. sse.set_max_reconnect_attempts(3);
  13716. sse.start_async();
  13717. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  13718. sse.stop();
  13719. // Should have reconnected after 401 and succeeded with new token
  13720. EXPECT_GE(connection_count.load(), 2);
  13721. EXPECT_TRUE(message_received.load());
  13722. }
  13723. TEST(Issue2318Test, EmptyHostString) {
  13724. {
  13725. httplib::Client cli_empty("", PORT);
  13726. auto res = cli_empty.Get("/");
  13727. ASSERT_FALSE(res);
  13728. EXPECT_EQ(httplib::Error::Connection, res.error());
  13729. }
  13730. {
  13731. httplib::Client cli(" ", PORT);
  13732. auto res = cli.Get("/");
  13733. ASSERT_FALSE(res);
  13734. EXPECT_EQ(httplib::Error::Connection, res.error());
  13735. }
  13736. }
  13737. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13738. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  13739. Server svr;
  13740. // Set a small payload limit (1KB)
  13741. svr.set_payload_max_length(1024);
  13742. svr.Post("/test", [&](const Request &req, Response &res) {
  13743. res.set_content("Body size: " + std::to_string(req.body.size()),
  13744. "text/plain");
  13745. });
  13746. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13747. auto se = detail::scope_exit([&] {
  13748. svr.stop();
  13749. listen_thread.join();
  13750. });
  13751. svr.wait_until_ready();
  13752. // Create data that compresses well but exceeds limit when decompressed
  13753. // 8KB of repeated null bytes compresses to a very small size
  13754. std::string original_data(8 * 1024, '\0');
  13755. // Compress the data using gzip
  13756. std::string compressed_data;
  13757. detail::gzip_compressor compressor;
  13758. compressor.compress(original_data.data(), original_data.size(), true,
  13759. [&](const char *data, size_t size) {
  13760. compressed_data.append(data, size);
  13761. return true;
  13762. });
  13763. // Verify compression worked (compressed should be much smaller)
  13764. ASSERT_LT(compressed_data.size(), original_data.size());
  13765. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  13766. // Send compressed data with Content-Encoding: gzip
  13767. Client cli(HOST, PORT);
  13768. Headers headers = {{"Content-Encoding", "gzip"}};
  13769. auto res =
  13770. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  13771. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  13772. ASSERT_TRUE(res);
  13773. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13774. }
  13775. #endif
  13776. // ============================================================================
  13777. // OpenSSL-Specific Tests
  13778. // ============================================================================
  13779. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13780. X509 *readCertificate(const std::string &strFileName) {
  13781. std::ifstream inStream(strFileName);
  13782. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  13783. std::istreambuf_iterator<char>());
  13784. if (strCertPEM.empty()) return (nullptr);
  13785. BIO *pbCert = BIO_new(BIO_s_mem());
  13786. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  13787. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  13788. BIO_free(pbCert);
  13789. return (pCert);
  13790. }
  13791. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  13792. std::ifstream inStream(strFileName);
  13793. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  13794. std::istreambuf_iterator<char>());
  13795. if (strPrivateKeyPEM.empty()) return (nullptr);
  13796. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  13797. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  13798. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  13799. BIO_free(pbPrivKey);
  13800. return (pPrivateKey);
  13801. }
  13802. TEST(BindServerTest, UpdateCerts) {
  13803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13804. int port = svr.bind_to_any_port("0.0.0.0");
  13805. ASSERT_TRUE(svr.is_valid());
  13806. ASSERT_TRUE(port > 0);
  13807. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13808. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13809. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13810. ASSERT_TRUE(cert != nullptr);
  13811. ASSERT_TRUE(ca_cert != nullptr);
  13812. ASSERT_TRUE(key != nullptr);
  13813. X509_STORE *cert_store = X509_STORE_new();
  13814. X509_STORE_add_cert(cert_store, ca_cert);
  13815. // svr.update_certs(cert, key, cert_store); // deprecated
  13816. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13817. CLIENT_CA_CERT_FILE);
  13818. ASSERT_TRUE(svr.is_valid());
  13819. svr.stop();
  13820. X509_STORE_free(cert_store);
  13821. X509_free(cert);
  13822. X509_free(ca_cert);
  13823. EVP_PKEY_free(key);
  13824. }
  13825. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  13826. // client CA list correctly for TLS handshake
  13827. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  13828. X509 *cert = readCertificate(SERVER_CERT_FILE);
  13829. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  13830. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  13831. ASSERT_TRUE(cert != nullptr);
  13832. ASSERT_TRUE(ca_cert != nullptr);
  13833. ASSERT_TRUE(key != nullptr);
  13834. X509_STORE *cert_store = X509_STORE_new();
  13835. X509_STORE_add_cert(cert_store, ca_cert);
  13836. // Use X509-based constructor (deprecated but should still work correctly)
  13837. #pragma GCC diagnostic push
  13838. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  13839. SSLServer svr(cert, key, cert_store);
  13840. #pragma GCC diagnostic pop
  13841. ASSERT_TRUE(svr.is_valid());
  13842. // Verify that client CA list is set in SSL_CTX
  13843. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13844. ASSERT_TRUE(ssl_ctx != nullptr);
  13845. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13846. ASSERT_TRUE(ca_list != nullptr);
  13847. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13848. X509_free(cert);
  13849. X509_free(ca_cert);
  13850. EVP_PKEY_free(key);
  13851. }
  13852. // Test that update_certs() updates client CA list correctly
  13853. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  13854. // Start with file-based constructor
  13855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13856. ASSERT_TRUE(svr.is_valid());
  13857. // Initially no client CA list should be set
  13858. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13859. ASSERT_TRUE(ssl_ctx != nullptr);
  13860. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  13861. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  13862. EXPECT_EQ(0, count_before);
  13863. // Now update with client CA (PEM string)
  13864. std::string cert_pem, key_pem, ca_pem;
  13865. read_file(SERVER_CERT_FILE, cert_pem);
  13866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13867. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13868. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  13869. ASSERT_TRUE(svr.is_valid());
  13870. // Now client CA list should be set
  13871. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  13872. ASSERT_TRUE(ca_list_after != nullptr);
  13873. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  13874. }
  13875. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  13876. // Test that the file-path SSLServer constructor properly sets the client CA
  13877. // list that is sent to clients during the TLS handshake (CertificateRequest)
  13878. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13879. ASSERT_TRUE(svr.is_valid());
  13880. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  13881. ASSERT_TRUE(ssl_ctx != nullptr);
  13882. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  13883. ASSERT_TRUE(ca_list != nullptr);
  13884. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  13885. }
  13886. #endif
  13887. // ============================================================================
  13888. // MbedTLS-Specific Tests
  13889. // ============================================================================
  13890. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  13891. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  13892. using namespace httplib::tls;
  13893. // Track if callback was invoked
  13894. bool callback_invoked = false;
  13895. // The callback receives void* ctx which is actually MbedTlsContext*
  13896. // We can access the mbedtls_ssl_config via the context
  13897. auto setup_callback = [&callback_invoked](void *ctx) {
  13898. callback_invoked = true;
  13899. // Cast to MbedTlsContext* to access the ssl config
  13900. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  13901. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  13902. // Use static variables to hold certificate data (simplified for test)
  13903. static mbedtls_x509_crt own_cert;
  13904. static mbedtls_pk_context own_key;
  13905. static mbedtls_x509_crt ca_chain;
  13906. static bool initialized = false;
  13907. if (!initialized) {
  13908. mbedtls_x509_crt_init(&own_cert);
  13909. mbedtls_pk_init(&own_key);
  13910. mbedtls_x509_crt_init(&ca_chain);
  13911. // Load server certificate
  13912. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  13913. return false;
  13914. }
  13915. // Load server private key
  13916. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  13917. #if MBEDTLS_VERSION_MAJOR >= 3
  13918. ,
  13919. mbedtls_ctr_drbg_random, nullptr
  13920. #endif
  13921. ) != 0) {
  13922. return false;
  13923. }
  13924. // Load CA chain for client verification
  13925. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  13926. return false;
  13927. }
  13928. initialized = true;
  13929. }
  13930. // Configure the SSL config
  13931. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  13932. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  13933. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  13934. // Set minimum TLS version using mbedTLS native API
  13935. #if MBEDTLS_VERSION_MAJOR >= 3
  13936. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  13937. #else
  13938. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  13939. MBEDTLS_SSL_MINOR_VERSION_3);
  13940. #endif
  13941. return true;
  13942. };
  13943. SSLServer svr(setup_callback);
  13944. ASSERT_TRUE(svr.is_valid());
  13945. ASSERT_TRUE(callback_invoked);
  13946. svr.Get("/test", [&](const Request &req, Response &res) {
  13947. res.set_content("test", "text/plain");
  13948. auto cert = req.peer_cert();
  13949. ASSERT_TRUE(static_cast<bool>(cert));
  13950. auto common_name = cert.subject_cn();
  13951. EXPECT_EQ("Common Name", common_name);
  13952. });
  13953. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13954. auto se = detail::scope_exit([&] {
  13955. svr.stop();
  13956. t.join();
  13957. ASSERT_FALSE(svr.is_running());
  13958. });
  13959. svr.wait_until_ready();
  13960. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13961. cli.enable_server_certificate_verification(false);
  13962. cli.set_connection_timeout(30);
  13963. auto res = cli.Get("/test");
  13964. ASSERT_TRUE(res);
  13965. ASSERT_EQ(StatusCode::OK_200, res->status);
  13966. }
  13967. #endif
  13968. // WebSocket Tests
  13969. TEST(WebSocketTest, RSVBitsMustBeZero) {
  13970. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  13971. // defining the meaning of these bits has been negotiated.
  13972. auto make_frame = [](uint8_t first_byte) {
  13973. std::string frame;
  13974. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  13975. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  13976. frame += "Hello";
  13977. return frame;
  13978. };
  13979. // RSV1 set (0x40)
  13980. {
  13981. detail::BufferStream strm;
  13982. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  13983. ws::Opcode opcode;
  13984. std::string payload;
  13985. bool fin;
  13986. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13987. false, 1024));
  13988. }
  13989. // RSV2 set (0x20)
  13990. {
  13991. detail::BufferStream strm;
  13992. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  13993. ws::Opcode opcode;
  13994. std::string payload;
  13995. bool fin;
  13996. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  13997. false, 1024));
  13998. }
  13999. // RSV3 set (0x10)
  14000. {
  14001. detail::BufferStream strm;
  14002. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  14003. ws::Opcode opcode;
  14004. std::string payload;
  14005. bool fin;
  14006. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14007. false, 1024));
  14008. }
  14009. // No RSV bits set - should succeed
  14010. {
  14011. detail::BufferStream strm;
  14012. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  14013. ws::Opcode opcode;
  14014. std::string payload;
  14015. bool fin;
  14016. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14017. false, 1024));
  14018. EXPECT_EQ(ws::Opcode::Text, opcode);
  14019. EXPECT_EQ("Hello", payload);
  14020. EXPECT_TRUE(fin);
  14021. }
  14022. }
  14023. TEST(WebSocketTest, ControlFrameValidation) {
  14024. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  14025. // payload length <= 125.
  14026. // Ping with FIN=0 - must be rejected
  14027. {
  14028. detail::BufferStream strm;
  14029. std::string frame;
  14030. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  14031. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14032. strm.write(frame.data(), frame.size());
  14033. ws::Opcode opcode;
  14034. std::string payload;
  14035. bool fin;
  14036. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14037. false, 1024));
  14038. }
  14039. // Close with FIN=0 - must be rejected
  14040. {
  14041. detail::BufferStream strm;
  14042. std::string frame;
  14043. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  14044. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  14045. strm.write(frame.data(), frame.size());
  14046. ws::Opcode opcode;
  14047. std::string payload;
  14048. bool fin;
  14049. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14050. false, 1024));
  14051. }
  14052. // Ping with payload_len=126 (extended length) - must be rejected
  14053. {
  14054. detail::BufferStream strm;
  14055. std::string frame;
  14056. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14057. frame += static_cast<char>(126); // payload_len=126 (>125)
  14058. frame += static_cast<char>(0x00); // extended length high byte
  14059. frame += static_cast<char>(126); // extended length low byte
  14060. frame += std::string(126, 'x');
  14061. strm.write(frame.data(), frame.size());
  14062. ws::Opcode opcode;
  14063. std::string payload;
  14064. bool fin;
  14065. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14066. false, 1024));
  14067. }
  14068. // Ping with FIN=1 and payload_len=125 - should succeed
  14069. {
  14070. detail::BufferStream strm;
  14071. std::string frame;
  14072. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  14073. frame += static_cast<char>(125); // payload_len=125
  14074. frame += std::string(125, 'x');
  14075. strm.write(frame.data(), frame.size());
  14076. ws::Opcode opcode;
  14077. std::string payload;
  14078. bool fin;
  14079. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14080. false, 1024));
  14081. EXPECT_EQ(ws::Opcode::Ping, opcode);
  14082. EXPECT_EQ(125u, payload.size());
  14083. EXPECT_TRUE(fin);
  14084. }
  14085. }
  14086. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  14087. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  14088. // length MUST be 0.
  14089. // MSB set - must be rejected
  14090. {
  14091. detail::BufferStream strm;
  14092. std::string frame;
  14093. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14094. frame += static_cast<char>(127); // 64-bit extended length
  14095. frame += static_cast<char>(0x80); // MSB set (invalid)
  14096. frame += std::string(7, '\0'); // remaining 7 bytes of length
  14097. strm.write(frame.data(), frame.size());
  14098. ws::Opcode opcode;
  14099. std::string payload;
  14100. bool fin;
  14101. EXPECT_FALSE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14102. false, 1024));
  14103. }
  14104. // MSB clear - should pass length parsing (will be rejected by max_len,
  14105. // but that's a different check; use a small length to verify)
  14106. {
  14107. detail::BufferStream strm;
  14108. std::string frame;
  14109. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  14110. frame += static_cast<char>(127); // 64-bit extended length
  14111. frame += std::string(7, '\0'); // high bytes = 0
  14112. frame += static_cast<char>(0x03); // length = 3
  14113. frame += "abc";
  14114. strm.write(frame.data(), frame.size());
  14115. ws::Opcode opcode;
  14116. std::string payload;
  14117. bool fin;
  14118. EXPECT_TRUE(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  14119. false, 1024));
  14120. EXPECT_EQ(ws::Opcode::Text, opcode);
  14121. EXPECT_EQ("abc", payload);
  14122. }
  14123. }
  14124. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  14125. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  14126. // Valid UTF-8
  14127. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  14128. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  14129. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  14130. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  14131. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  14132. // Invalid UTF-8
  14133. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  14134. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  14135. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  14136. EXPECT_FALSE(
  14137. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  14138. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  14139. }
  14140. TEST(WebSocketTest, ConnectAndDisconnect) {
  14141. Server svr;
  14142. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14143. std::string msg;
  14144. while (ws.read(msg)) {}
  14145. });
  14146. auto port = svr.bind_to_any_port(HOST);
  14147. std::thread t([&]() { svr.listen_after_bind(); });
  14148. svr.wait_until_ready();
  14149. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  14150. ASSERT_TRUE(client.connect());
  14151. EXPECT_TRUE(client.is_open());
  14152. client.close();
  14153. EXPECT_FALSE(client.is_open());
  14154. svr.stop();
  14155. t.join();
  14156. }
  14157. TEST(WebSocketTest, ValidURL) {
  14158. ws::WebSocketClient ws1("ws://localhost:8080/path");
  14159. EXPECT_TRUE(ws1.is_valid());
  14160. ws::WebSocketClient ws2("ws://example.com/path");
  14161. EXPECT_TRUE(ws2.is_valid());
  14162. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  14163. EXPECT_TRUE(ws3.is_valid());
  14164. #ifdef CPPHTTPLIB_SSL_ENABLED
  14165. ws::WebSocketClient wss1("wss://example.com/path");
  14166. EXPECT_TRUE(wss1.is_valid());
  14167. ws::WebSocketClient wss2("wss://example.com:443/path");
  14168. EXPECT_TRUE(wss2.is_valid());
  14169. #endif
  14170. }
  14171. TEST(WebSocketTest, InvalidURL) {
  14172. // No scheme
  14173. ws::WebSocketClient ws1("localhost:8080/path");
  14174. EXPECT_FALSE(ws1.is_valid());
  14175. // No path
  14176. ws::WebSocketClient ws2("ws://localhost:8080");
  14177. EXPECT_FALSE(ws2.is_valid());
  14178. // Empty string
  14179. ws::WebSocketClient ws3("");
  14180. EXPECT_FALSE(ws3.is_valid());
  14181. // Missing host
  14182. ws::WebSocketClient ws4("ws://:8080/path");
  14183. EXPECT_FALSE(ws4.is_valid());
  14184. // Port number overflow — should not crash
  14185. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  14186. EXPECT_FALSE(ws5.is_valid());
  14187. // Port out of range
  14188. ws::WebSocketClient ws6("ws://localhost:99999/path");
  14189. EXPECT_FALSE(ws6.is_valid());
  14190. }
  14191. TEST(WebSocketTest, UnsupportedScheme) {
  14192. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14193. ws::WebSocketClient ws1("http://localhost:8080/path");
  14194. EXPECT_FALSE(ws1.is_valid());
  14195. ws::WebSocketClient ws2("https://localhost:8080/path");
  14196. EXPECT_FALSE(ws2.is_valid());
  14197. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  14198. EXPECT_FALSE(ws3.is_valid());
  14199. #else
  14200. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  14201. std::invalid_argument);
  14202. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  14203. std::invalid_argument);
  14204. #endif
  14205. }
  14206. TEST(WebSocketTest, ConnectWhenInvalid) {
  14207. ws::WebSocketClient ws("not a valid url");
  14208. EXPECT_FALSE(ws.is_valid());
  14209. EXPECT_FALSE(ws.connect());
  14210. }
  14211. TEST(WebSocketTest, DefaultPort) {
  14212. ws::WebSocketClient ws1("ws://example.com/path");
  14213. EXPECT_TRUE(ws1.is_valid());
  14214. // ws:// defaults to port 80 (verified by successful parse)
  14215. #ifdef CPPHTTPLIB_SSL_ENABLED
  14216. ws::WebSocketClient ws2("wss://example.com/path");
  14217. EXPECT_TRUE(ws2.is_valid());
  14218. // wss:// defaults to port 443 (verified by successful parse)
  14219. #endif
  14220. }
  14221. TEST(WebSocketTest, IPv6LiteralAddress) {
  14222. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  14223. EXPECT_TRUE(ws1.is_valid());
  14224. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  14225. EXPECT_TRUE(ws2.is_valid());
  14226. }
  14227. TEST(WebSocketTest, ComplexPath) {
  14228. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  14229. EXPECT_TRUE(ws1.is_valid());
  14230. ws::WebSocketClient ws2("ws://localhost:8080/");
  14231. EXPECT_TRUE(ws2.is_valid());
  14232. }
  14233. class WebSocketIntegrationTest : public ::testing::Test {
  14234. protected:
  14235. void SetUp() override {
  14236. server_ = httplib::detail::make_unique<Server>();
  14237. setup_server();
  14238. start_server();
  14239. }
  14240. void TearDown() override {
  14241. server_->stop();
  14242. if (server_thread_.joinable()) { server_thread_.join(); }
  14243. }
  14244. void setup_server() {
  14245. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14246. std::string msg;
  14247. ws::ReadResult ret;
  14248. while ((ret = ws.read(msg))) {
  14249. if (ret == ws::Binary) {
  14250. ws.send(msg.data(), msg.size());
  14251. } else {
  14252. ws.send(msg);
  14253. }
  14254. }
  14255. });
  14256. server_->WebSocket("/ws-echo-string",
  14257. [](const Request &, ws::WebSocket &ws) {
  14258. std::string msg;
  14259. while (ws.read(msg)) {
  14260. ws.send("echo: " + msg);
  14261. }
  14262. });
  14263. server_->WebSocket(
  14264. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  14265. // Echo back request metadata
  14266. ws.send("path:" + req.path);
  14267. ws.send("header:" + req.get_header_value("X-Test-Header"));
  14268. std::string msg;
  14269. while (ws.read(msg)) {}
  14270. });
  14271. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  14272. std::string msg;
  14273. ws.read(msg); // wait for a message
  14274. ws.close();
  14275. });
  14276. server_->WebSocket("/ws-close-status",
  14277. [](const Request &, ws::WebSocket &ws) {
  14278. std::string msg;
  14279. ws.read(msg); // wait for a message
  14280. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  14281. });
  14282. server_->WebSocket(
  14283. "/ws-subprotocol",
  14284. [](const Request &, ws::WebSocket &ws) {
  14285. std::string msg;
  14286. while (ws.read(msg)) {
  14287. ws.send(msg);
  14288. }
  14289. },
  14290. [](const std::vector<std::string> &protocols) -> std::string {
  14291. for (const auto &p : protocols) {
  14292. if (p == "graphql-ws") { return p; }
  14293. }
  14294. return "";
  14295. });
  14296. }
  14297. void start_server() {
  14298. port_ = server_->bind_to_any_port(HOST);
  14299. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14300. server_->wait_until_ready();
  14301. }
  14302. std::unique_ptr<Server> server_;
  14303. std::thread server_thread_;
  14304. int port_ = 0;
  14305. };
  14306. TEST_F(WebSocketIntegrationTest, TextEcho) {
  14307. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14308. "/ws-echo");
  14309. ASSERT_TRUE(client.connect());
  14310. ASSERT_TRUE(client.is_open());
  14311. ASSERT_TRUE(client.send("Hello WebSocket"));
  14312. std::string msg;
  14313. EXPECT_EQ(ws::Text, client.read(msg));
  14314. EXPECT_EQ("Hello WebSocket", msg);
  14315. client.close();
  14316. }
  14317. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  14318. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14319. "/ws-echo");
  14320. ASSERT_TRUE(client.connect());
  14321. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  14322. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  14323. std::string msg;
  14324. EXPECT_EQ(ws::Binary, client.read(msg));
  14325. EXPECT_EQ(binary_data, msg);
  14326. client.close();
  14327. }
  14328. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  14329. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14330. "/ws-echo");
  14331. ASSERT_TRUE(client.connect());
  14332. for (int i = 0; i < 10; i++) {
  14333. auto text = "message " + std::to_string(i);
  14334. ASSERT_TRUE(client.send(text));
  14335. std::string msg;
  14336. ASSERT_TRUE(client.read(msg));
  14337. EXPECT_EQ(text, msg);
  14338. }
  14339. client.close();
  14340. }
  14341. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  14342. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14343. "/ws-close");
  14344. ASSERT_TRUE(client.connect());
  14345. // Send a message to trigger the server to close
  14346. ASSERT_TRUE(client.send("trigger close"));
  14347. // The server will close, so read should return false
  14348. std::string msg;
  14349. EXPECT_FALSE(client.read(msg));
  14350. EXPECT_FALSE(client.is_open());
  14351. }
  14352. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  14353. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14354. "/ws-echo");
  14355. ASSERT_TRUE(client.connect());
  14356. // 128KB message
  14357. std::string large_data(128 * 1024, 'X');
  14358. ASSERT_TRUE(client.send(large_data));
  14359. std::string msg;
  14360. ASSERT_TRUE(client.read(msg));
  14361. EXPECT_EQ(large_data, msg);
  14362. client.close();
  14363. }
  14364. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  14365. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14366. "/ws-echo");
  14367. ASSERT_TRUE(client.connect());
  14368. const int num_threads = 4;
  14369. std::vector<std::thread> threads;
  14370. std::atomic<int> send_count{0};
  14371. for (int t = 0; t < num_threads; t++) {
  14372. threads.emplace_back([&client, &send_count, t]() {
  14373. for (int i = 0; i < 5; i++) {
  14374. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  14375. if (client.send(text)) { send_count++; }
  14376. }
  14377. });
  14378. }
  14379. for (auto &th : threads) {
  14380. th.join();
  14381. }
  14382. int received = 0;
  14383. std::string msg;
  14384. while (received < send_count.load()) {
  14385. if (!client.read(msg)) { break; }
  14386. received++;
  14387. }
  14388. EXPECT_EQ(send_count.load(), received);
  14389. client.close();
  14390. }
  14391. TEST_F(WebSocketIntegrationTest, ReadString) {
  14392. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14393. "/ws-echo-string");
  14394. ASSERT_TRUE(client.connect());
  14395. ASSERT_TRUE(client.send("hello"));
  14396. std::string msg;
  14397. ASSERT_TRUE(client.read(msg));
  14398. EXPECT_EQ("echo: hello", msg);
  14399. ASSERT_TRUE(client.send("world"));
  14400. ASSERT_TRUE(client.read(msg));
  14401. EXPECT_EQ("echo: world", msg);
  14402. client.close();
  14403. }
  14404. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  14405. Headers headers = {{"X-Test-Header", "test-value"}};
  14406. ws::WebSocketClient client(
  14407. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  14408. ASSERT_TRUE(client.connect());
  14409. std::string msg;
  14410. ASSERT_TRUE(client.read(msg));
  14411. EXPECT_EQ("path:/ws-request-info", msg);
  14412. ASSERT_TRUE(client.read(msg));
  14413. EXPECT_EQ("header:test-value", msg);
  14414. client.close();
  14415. }
  14416. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  14417. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14418. "/ws-echo");
  14419. client.set_read_timeout(1, 0); // 1 second
  14420. ASSERT_TRUE(client.connect());
  14421. // Don't send anything — server echo handler waits for a message,
  14422. // so read() should time out and return false.
  14423. std::string msg;
  14424. EXPECT_FALSE(client.read(msg));
  14425. }
  14426. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  14427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14428. "/ws-echo");
  14429. client.set_read_timeout(5, 0);
  14430. ASSERT_TRUE(client.connect());
  14431. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14432. // The server should reject it and close the connection.
  14433. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  14434. client.send(oversized);
  14435. // The server's read() should have failed due to payload limit,
  14436. // so our read() should return false (connection closed).
  14437. std::string msg;
  14438. EXPECT_FALSE(client.read(msg));
  14439. }
  14440. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  14441. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14442. "/ws-echo");
  14443. client.set_read_timeout(10, 0);
  14444. ASSERT_TRUE(client.connect());
  14445. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  14446. // This should succeed.
  14447. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  14448. ASSERT_TRUE(client.send(at_limit));
  14449. std::string msg;
  14450. ASSERT_TRUE(client.read(msg));
  14451. EXPECT_EQ(at_limit.size(), msg.size());
  14452. client.close();
  14453. }
  14454. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  14455. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14456. "/nonexistent");
  14457. EXPECT_FALSE(client.connect());
  14458. EXPECT_FALSE(client.is_open());
  14459. }
  14460. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  14461. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14462. "/ws-echo");
  14463. ASSERT_TRUE(client.connect());
  14464. ASSERT_TRUE(client.send(""));
  14465. std::string msg;
  14466. EXPECT_EQ(ws::Text, client.read(msg));
  14467. EXPECT_EQ("", msg);
  14468. client.close();
  14469. }
  14470. TEST_F(WebSocketIntegrationTest, Reconnect) {
  14471. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14472. "/ws-echo");
  14473. // First connection
  14474. ASSERT_TRUE(client.connect());
  14475. ASSERT_TRUE(client.send("first"));
  14476. std::string msg;
  14477. ASSERT_TRUE(client.read(msg));
  14478. EXPECT_EQ("first", msg);
  14479. client.close();
  14480. EXPECT_FALSE(client.is_open());
  14481. // Reconnect using the same client object
  14482. ASSERT_TRUE(client.connect());
  14483. ASSERT_TRUE(client.is_open());
  14484. ASSERT_TRUE(client.send("second"));
  14485. ASSERT_TRUE(client.read(msg));
  14486. EXPECT_EQ("second", msg);
  14487. client.close();
  14488. }
  14489. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  14490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14491. "/ws-close-status");
  14492. ASSERT_TRUE(client.connect());
  14493. // Trigger the server to close with GoingAway status
  14494. ASSERT_TRUE(client.send("trigger"));
  14495. // read() should return false after receiving the close frame
  14496. std::string msg;
  14497. EXPECT_FALSE(client.read(msg));
  14498. EXPECT_FALSE(client.is_open());
  14499. }
  14500. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  14501. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14502. "/ws-echo");
  14503. ASSERT_TRUE(client.connect());
  14504. client.close(ws::CloseStatus::GoingAway, "client leaving");
  14505. EXPECT_FALSE(client.is_open());
  14506. }
  14507. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  14508. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  14509. ws::WebSocketClient client(
  14510. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14511. ASSERT_TRUE(client.connect());
  14512. // Server should have selected graphql-ws
  14513. EXPECT_EQ("graphql-ws", client.subprotocol());
  14514. client.close();
  14515. }
  14516. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  14517. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  14518. ws::WebSocketClient client(
  14519. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  14520. ASSERT_TRUE(client.connect());
  14521. // Server should not have selected any subprotocol
  14522. EXPECT_TRUE(client.subprotocol().empty());
  14523. client.close();
  14524. }
  14525. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  14526. // Connect without requesting any subprotocol
  14527. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14528. "/ws-subprotocol");
  14529. ASSERT_TRUE(client.connect());
  14530. EXPECT_TRUE(client.subprotocol().empty());
  14531. client.close();
  14532. }
  14533. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  14534. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  14535. "/ws-echo");
  14536. client.set_tcp_nodelay(true);
  14537. client.set_address_family(AF_INET);
  14538. client.set_connection_timeout(3, 0);
  14539. bool socket_options_called = false;
  14540. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  14541. ASSERT_TRUE(client.connect());
  14542. ASSERT_TRUE(client.is_open());
  14543. EXPECT_TRUE(socket_options_called);
  14544. ASSERT_TRUE(client.send("hello"));
  14545. std::string msg;
  14546. auto result = client.read(msg);
  14547. EXPECT_EQ(result, ws::ReadResult::Text);
  14548. EXPECT_EQ(msg, "hello");
  14549. client.close();
  14550. }
  14551. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  14552. Server svr;
  14553. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  14554. if (!req.has_header("Authorization")) {
  14555. res.status = StatusCode::Unauthorized_401;
  14556. res.set_content("Unauthorized", "text/plain");
  14557. return Server::HandlerResponse::Handled;
  14558. }
  14559. return Server::HandlerResponse::Unhandled;
  14560. });
  14561. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  14562. std::string msg;
  14563. while (ws.read(msg)) {
  14564. ws.send(msg);
  14565. }
  14566. });
  14567. auto port = svr.bind_to_any_port("localhost");
  14568. std::thread t([&]() { svr.listen_after_bind(); });
  14569. svr.wait_until_ready();
  14570. // Without Authorization header - should be rejected before upgrade
  14571. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  14572. EXPECT_FALSE(client1.connect());
  14573. // With Authorization header - should succeed
  14574. Headers headers = {{"Authorization", "Bearer token123"}};
  14575. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  14576. headers);
  14577. ASSERT_TRUE(client2.connect());
  14578. ASSERT_TRUE(client2.send("hello"));
  14579. std::string msg;
  14580. ASSERT_TRUE(client2.read(msg));
  14581. EXPECT_EQ("hello", msg);
  14582. client2.close();
  14583. svr.stop();
  14584. t.join();
  14585. }
  14586. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14587. class WebSocketSSLIntegrationTest : public ::testing::Test {
  14588. protected:
  14589. void SetUp() override {
  14590. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  14591. SERVER_PRIVATE_KEY_FILE);
  14592. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  14593. std::string msg;
  14594. ws::ReadResult ret;
  14595. while ((ret = ws.read(msg))) {
  14596. if (ret == ws::Binary) {
  14597. ws.send(msg.data(), msg.size());
  14598. } else {
  14599. ws.send(msg);
  14600. }
  14601. }
  14602. });
  14603. port_ = server_->bind_to_any_port(HOST);
  14604. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  14605. server_->wait_until_ready();
  14606. }
  14607. void TearDown() override {
  14608. server_->stop();
  14609. if (server_thread_.joinable()) { server_thread_.join(); }
  14610. }
  14611. std::unique_ptr<SSLServer> server_;
  14612. std::thread server_thread_;
  14613. int port_ = 0;
  14614. };
  14615. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  14616. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  14617. "/ws-echo");
  14618. client.enable_server_certificate_verification(false);
  14619. ASSERT_TRUE(client.connect());
  14620. ASSERT_TRUE(client.is_open());
  14621. ASSERT_TRUE(client.send("Hello WSS"));
  14622. std::string msg;
  14623. EXPECT_EQ(ws::Text, client.read(msg));
  14624. EXPECT_EQ("Hello WSS", msg);
  14625. client.close();
  14626. }
  14627. #endif
  14628. #if !defined(_WIN32)
  14629. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  14630. auto secret_dir = std::string("./symlink_test_secret");
  14631. auto served_dir = std::string("./symlink_test_served");
  14632. auto secret_file = secret_dir + "/secret.txt";
  14633. auto symlink_path = served_dir + "/escape";
  14634. // Setup: create directories and files
  14635. mkdir(secret_dir.c_str(), 0755);
  14636. mkdir(served_dir.c_str(), 0755);
  14637. {
  14638. std::ofstream ofs(secret_file);
  14639. ofs << "SECRET_DATA";
  14640. }
  14641. // Create symlink using absolute path so it resolves correctly
  14642. char abs_secret[PATH_MAX];
  14643. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  14644. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  14645. auto se = detail::scope_exit([&] {
  14646. unlink(symlink_path.c_str());
  14647. unlink(secret_file.c_str());
  14648. rmdir(served_dir.c_str());
  14649. rmdir(secret_dir.c_str());
  14650. });
  14651. Server svr;
  14652. svr.set_mount_point("/", served_dir);
  14653. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  14654. auto se2 = detail::scope_exit([&] {
  14655. svr.stop();
  14656. listen_thread.join();
  14657. });
  14658. svr.wait_until_ready();
  14659. Client cli("localhost", PORT);
  14660. // Symlink pointing outside base dir should be blocked
  14661. auto res = cli.Get("/escape/secret.txt");
  14662. ASSERT_TRUE(res);
  14663. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  14664. }
  14665. #endif
  14666. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  14667. // A GET request with Content-Length to a static file handler must have its
  14668. // body drained before the keep-alive connection is reused. Otherwise the
  14669. // unread body bytes are interpreted as the next HTTP request.
  14670. //
  14671. // The body is sent AFTER receiving the first response (as in the original
  14672. // PoC) so that the stream_line_reader cannot buffer it together with the
  14673. // headers of the first request.
  14674. Server svr;
  14675. svr.set_mount_point("/", "./www");
  14676. std::atomic<int> smuggled_count(0);
  14677. svr.Get("/smuggled", [&](const Request &, Response &res) {
  14678. smuggled_count++;
  14679. res.set_content("oops", "text/plain");
  14680. });
  14681. auto port = svr.bind_to_any_port("localhost");
  14682. thread t = thread([&] { svr.listen_after_bind(); });
  14683. auto se = detail::scope_exit([&] {
  14684. svr.stop();
  14685. t.join();
  14686. });
  14687. svr.wait_until_ready();
  14688. auto error = Error::Success;
  14689. auto sock = detail::create_client_socket(
  14690. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  14691. /*connection_timeout_sec=*/2, 0,
  14692. /*read_timeout_sec=*/2, 0,
  14693. /*write_timeout_sec=*/2, 0, std::string(), error);
  14694. ASSERT_NE(INVALID_SOCKET, sock);
  14695. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  14696. // The "smuggled" request will be sent as the body of the outer GET
  14697. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  14698. "Host: localhost\r\n"
  14699. "Connection: close\r\n"
  14700. "\r\n";
  14701. // Step 1: Send only the outer request headers (no body yet)
  14702. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  14703. "Host: localhost\r\n"
  14704. "Content-Length: " +
  14705. std::to_string(smuggled.size()) +
  14706. "\r\n"
  14707. "\r\n";
  14708. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  14709. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  14710. // Step 2: Read the first response (server serves file without reading body)
  14711. std::string first_response;
  14712. char buf[4096];
  14713. for (;;) {
  14714. auto n = recv(sock, buf, sizeof(buf), 0);
  14715. if (n <= 0) break;
  14716. first_response.append(buf, static_cast<size_t>(n));
  14717. // Stop once we have a complete response (headers + body)
  14718. auto hdr_end = first_response.find("\r\n\r\n");
  14719. if (hdr_end != std::string::npos) {
  14720. // Check for Content-Length to know when the body is complete
  14721. auto cl_pos = first_response.find("Content-Length:");
  14722. if (cl_pos != std::string::npos) {
  14723. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  14724. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  14725. auto cl = std::stoul(
  14726. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  14727. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  14728. } else {
  14729. break; // No Content-Length, assume headers-only response
  14730. }
  14731. }
  14732. }
  14733. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  14734. // Step 3: Now send the body, which looks like a new HTTP request.
  14735. // On a vulnerable server the keep-alive loop reads this as a second request.
  14736. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  14737. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  14738. // Step 4: Try to read a second response (should NOT exist after fix)
  14739. std::string second_response;
  14740. for (;;) {
  14741. auto n = recv(sock, buf, sizeof(buf), 0);
  14742. if (n <= 0) break;
  14743. second_response.append(buf, static_cast<size_t>(n));
  14744. }
  14745. // The smuggled request must NOT have been processed
  14746. EXPECT_EQ(0, smuggled_count.load());
  14747. }
  14748. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  14749. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  14750. // must be rejected with 400 Bad Request.
  14751. Server svr;
  14752. svr.Post("/test", [&](const Request &, Response &res) {
  14753. res.set_content("ok", "text/plain");
  14754. });
  14755. thread t = thread([&] { svr.listen(HOST, PORT); });
  14756. auto se = detail::scope_exit([&] {
  14757. svr.stop();
  14758. t.join();
  14759. ASSERT_FALSE(svr.is_running());
  14760. });
  14761. svr.wait_until_ready();
  14762. // Exact "chunked"
  14763. {
  14764. auto req = "POST /test HTTP/1.1\r\n"
  14765. "Host: localhost\r\n"
  14766. "Content-Length: 5\r\n"
  14767. "Transfer-Encoding: chunked\r\n"
  14768. "Connection: close\r\n"
  14769. "\r\n"
  14770. "hello";
  14771. std::string response;
  14772. ASSERT_TRUE(send_request(1, req, &response));
  14773. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14774. response.substr(0, response.find("\r\n")));
  14775. }
  14776. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  14777. {
  14778. auto req = "POST /test HTTP/1.1\r\n"
  14779. "Host: localhost\r\n"
  14780. "Content-Length: 5\r\n"
  14781. "Transfer-Encoding: gzip, chunked\r\n"
  14782. "Connection: close\r\n"
  14783. "\r\n"
  14784. "hello";
  14785. std::string response;
  14786. ASSERT_TRUE(send_request(1, req, &response));
  14787. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  14788. response.substr(0, response.find("\r\n")));
  14789. }
  14790. }